Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(desktop): finish Swarm controls and show live project data

dee55a7935420e9
diff --cc cli/src/lib/agentProject.spec.ts
index a6ff3f558,000000000..f7f8e0a9b
mode 100644,000000..100644
--- a/cli/src/lib/agentProject.spec.ts
+++ b/cli/src/lib/agentProject.spec.ts
@@@ -1,36 -1,0 +1,38 @@@
+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('ssh://[email protected]:22/Org/App.git')).toBe('github.com/org/app')
++ expect(canonicalRepository('ssh://[email protected]:2222/Org/App.git')).toBe('example.com:2222/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 --cc cli/src/lib/agentProject.ts
index fbc0f0b1b,000000000..1baeda12e
mode 100644,000000..100644
--- a/cli/src/lib/agentProject.ts
+++ b/cli/src/lib/agentProject.ts
@@@ -1,68 -1,0 +1,70 @@@
+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}`
++ const defaultPort = url.protocol === 'ssh:' ? '22' : url.protocol === 'git:' ? '9418' : ''
++ const port = url.port === defaultPort ? '' : url.port
++ return `${host}${port ? `:${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 --cc desktop/lib/core/crash_log.dart
index 6a132e394,672b76bdc..5131aea05
--- a/desktop/lib/core/crash_log.dart
+++ b/desktop/lib/core/crash_log.dart
@@@ -19,12 -18,8 +19,11 @@@ import 'test_run.dart'
class CrashLog {
static const _maxBytes = 256 * 1024;
+ @visibleForTesting
+ static File? testFile;
+
static File get _file =>
- testFile ??
-- File('${HarnessFileStore.defaultDirectoryPath()}/errors.log');
++ testFile ?? File('${HarnessFileStore.defaultDirectoryPath()}/errors.log');
static void record(Object error, StackTrace? stackTrace, {String? context}) {
// Mirrored into the day's app log as well, and the two are not redundant:
diff --cc desktop/lib/core/desktop_window.dart
index debbd34d4,e28c403b5..051224fa6
--- a/desktop/lib/core/desktop_window.dart
+++ b/desktop/lib/core/desktop_window.dart
@@@ -1,10 -1,7 +1,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.
///
diff --cc desktop/lib/core/models.dart
index 4136aed2a,f91e1aa16..f04bba77d
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@@ -369,52 -365,3 +369,57 @@@ 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;
++ 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 --cc desktop/lib/main.dart
index 928f85240,35f581b3e..21d28916b
--- a/desktop/lib/main.dart
+++ b/desktop/lib/main.dart
@@@ -165,6 -164,6 +165,7 @@@ class _RootShellState extends ConsumerS
switch (call.method) {
case 'checkForUpdates':
final app = ref.read(appStateProvider);
++ if (!app.desktopUpdatesEnabled) return;
final result = await app.checkForUpdates();
if (!mounted) return;
await showUpdateCheckDialog(context, app, result);
diff --cc desktop/lib/screens/home_screen.dart
index 8c5e9dcbd,8c5e9dcbd..94e2c8515
--- a/desktop/lib/screens/home_screen.dart
+++ b/desktop/lib/screens/home_screen.dart
@@@ -213,6 -213,6 +213,7 @@@ class _HomeScreenState extends State<Ho
_maybeShowLinkDialog(notifier);
return CallbackShortcuts(
bindings: buildShortcutBindings(
++ swarmMode: false,
handlers: {
ShortcutAction.toggleRail: () =>
setState(() => _collapsed = !_collapsed),
diff --cc desktop/lib/screens/swarm_screen.dart
index 27a41d6df,000000000..6f6332ca1
mode 100644,000000..100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@@ -1,686 -1,0 +1,704 @@@
+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;
++ final _shellFocus = FocusNode(debugLabel: 'Swarm shell');
+ 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;
++ FocusManager.instance.addListener(_restoreEmptyFocus);
+ unawaited(_projects.load());
+ _spokenTasks = app.spokenTasks.listen(_openSpokenTask);
+ if (_native) {
+ _channel.setMethodCallHandler(_onNative);
+ app.addListener(_syncNative);
+ _syncNative();
+ }
+ }
+
+ @override
+ void dispose() {
++ FocusManager.instance.removeListener(_restoreEmptyFocus);
++ _shellFocus.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 _restoreEmptyFocus() {
++ if (!mounted ||
++ app.panes.isNotEmpty ||
++ _dialogOpen ||
++ _spokenPaletteOpen ||
++ ModalRoute.of(context)?.isCurrent == false ||
++ _shellFocus.hasFocus) {
++ return;
++ }
++ // Hiding the final terminal releases focus after its parent has rebuilt.
++ // Only reclaim the route's empty scope, never another field or dialog.
++ if (FocusManager.instance.primaryFocus == _shellFocus.enclosingScope) {
++ _shellFocus.requestFocus();
++ }
++ }
++
+ void _syncNative() {
+ final payload = {
- 'enabled': true,
++ 'enabled': !_dialogOpen && !_spokenPaletteOpen,
+ '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;
++ if (!mounted ||
++ _dialogOpen ||
++ _spokenPaletteOpen ||
++ ModalRoute.of(context)?.isCurrent == false) {
++ 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)
++ 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;
++ if (_dialogOpen || _spokenPaletteOpen || !mounted) return;
+ _dialogOpen = true;
++ if (_native) _syncNative();
+ try {
+ await action();
+ } finally {
+ _dialogOpen = false;
++ if (_native && mounted) _syncNative();
+ }
+ }
+
+ 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)
++ 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)
++ 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;
++ if (_native) _syncNative();
+ try {
+ await revealWindow();
+ if (!mounted) {
+ spoken.cancelled();
+ return;
+ }
+ await showTaskPalette(context, app, spoken: spoken);
+ } finally {
+ _spokenPaletteOpen = false;
++ if (_native && mounted) _syncNative();
+ 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)
++ _linkDialogMachineId != null) {
+ return;
++ }
+ _linkDialogMachineId = machine.machine.machineId;
+ WidgetsBinding.instance.addPostFrameCallback((_) async {
- if (mounted)
++ 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();
++ if (app.panes.isEmpty) {
++ WidgetsBinding.instance.addPostFrameCallback(
++ (_) => _restoreEmptyFocus(),
++ );
++ }
+ return CallbackShortcuts(
+ bindings: {
+ ...buildShortcutBindings(
+ handlers: {
++ ShortcutAction.newSwarm: app.newSwarm,
++ ShortcutAction.closeSwarm: () =>
++ app.closeSwarm(app.activeSwarmId),
++ ShortcutAction.renameSwarm: () => _rename(app.activeSwarmId),
++ ShortcutAction.nextSwarm: () => app.stepSwarm(1),
++ ShortcutAction.previousSwarm: () => app.stepSwarm(-1),
++ ShortcutAction.showSettings: _settings,
+ 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)
++ 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)
++ 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(
++ focusNode: _shellFocus,
+ autofocus: true,
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.swarmField,
+ body: Column(
+ children: [
+ if (!_native) _tabStrip(),
- if (app.lastError != null)
++ if (_projects.error != null || 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!,
++ _projects.error ?? app.lastError!,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 12),
+ ),
+ ),
- if (app.lastErrorRetryable)
++ if (_projects.error == null && app.lastErrorRetryable)
+ TextButton(
+ onPressed: app.retryMachines,
+ child: const Text('Retry'),
+ ),
+ IconButton(
- onPressed: app.dismissError,
++ onPressed: _projects.error != null
++ ? _projects.dismissError
++ : 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)',
++ tooltip: withShortcutHint(
++ 'Add agent',
++ ShortcutAction.switchAgent,
++ ),
+ 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),
++ onReorderItem: (old, to) =>
++ app.reorderSwarm(app.swarms[old].id, 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)',
++ tooltip: withShortcutHint('New swarm', ShortcutAction.newSwarm),
+ 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 --cc desktop/lib/settings/sections/about_section.dart
index 4c5dfff50,4c5dfff50..ce2acf601
--- a/desktop/lib/settings/sections/about_section.dart
+++ b/desktop/lib/settings/sections/about_section.dart
@@@ -1,6 -1,6 +1,7 @@@
import 'package:flutter/material.dart';
import '../../core/app_version.dart';
++import '../../core/build_identity.dart';
import '../../shared/theme/app_theme.dart' as grid;
import '../../shared/widgets/section_scaffold.dart';
import '../../shared/widgets/skeleton.dart';
@@@ -63,7 -63,7 +64,7 @@@ class _AboutSectionState extends State<
return SectionScaffold(
title: 'About',
subtitle:
-- 'Harness Desktop attaches terminals to the agents running on your '
++ '$desktopAppName attaches terminals to the agents running on your '
'machines.',
child: SingleChildScrollView(
child: ConstrainedBox(
@@@ -83,8 -83,8 +84,10 @@@
),
const SizedBox(height: 12),
Text(
-- 'Harness checks for a newer build when it starts, and every '
-- 'six hours after that.',
++ widget.notifier.desktopUpdatesEnabled
++ ? 'Harness checks for a newer build when it starts, and every '
++ 'six hours after that.'
++ : 'Automatic and manual updates are disabled for this V2 preview.',
style: TextStyle(
color: grid.AppPalette.textFaint,
fontSize: 11.5,
@@@ -136,8 -136,8 +139,10 @@@ class _AboutCard extends StatelessWidge
const SizedBox(height: 18),
Container(height: 1, color: grid.AppPalette.divider),
const SizedBox(height: 14),
-- _CheckRow(checking: checking, onCheck: onCheck),
-- const SizedBox(height: 12),
++ if (notifier.desktopUpdatesEnabled) ...[
++ _CheckRow(checking: checking, onCheck: onCheck),
++ const SizedBox(height: 12),
++ ],
const _FlashRow(),
],
),
@@@ -171,7 -171,7 +176,7 @@@ class _Identity extends StatelessWidge
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
-- 'Harness Desktop',
++ desktopAppName,
style: TextStyle(
color: grid.AppPalette.textPrimary,
fontSize: 16,
@@@ -309,6 -309,6 +314,12 @@@ class _PillState
final bool wash;
static _PillState of(AppNotifier notifier, {required bool checking}) {
++ if (!notifier.desktopUpdatesEnabled) {
++ return _PillState(
++ 'Preview · updates disabled',
++ grid.AppPalette.textSecondary,
++ );
++ }
if (notifier.isInstallingUpdate) {
return _PillState(
'Installing…',
diff --cc desktop/lib/settings/sections/account_section.dart
index 000000000,000000000..1409a4409
new file mode 100644
--- /dev/null
+++ b/desktop/lib/settings/sections/account_section.dart
@@@ -1,0 -1,0 +1,43 @@@
++import 'package:flutter/material.dart';
++
++import '../../shared/widgets/section_scaffold.dart';
++import '../../shared/widgets/setting_row.dart';
++import '../../state/app_state.dart';
++
++class AccountSection extends StatelessWidget {
++ const AccountSection({super.key, required this.notifier});
++
++ final AppNotifier notifier;
++
++ @override
++ Widget build(BuildContext context) => ListenableBuilder(
++ listenable: notifier,
++ builder: (context, _) {
++ final local = notifier.localManualFixture != null;
++ final profile = notifier.currentUser;
++ return SectionScaffold(
++ title: 'Account',
++ subtitle: local
++ ? 'Connected to a local development session.'
++ : 'Your Harness sign-in on this computer.',
++ child: SingleChildScrollView(
++ child: SettingRow(
++ title:
++ profile?.displayName ?? (local ? 'Local session' : 'Signed in'),
++ detail:
++ profile?.email ??
++ (local ? 'Loopback backend' : 'Profile unavailable'),
++ control: OutlinedButton(
++ key: const Key('settings-sign-out-button'),
++ onPressed: () {
++ Navigator.of(context).pop();
++ notifier.logout();
++ },
++ child: Text(local ? 'Disconnect local session' : 'Sign out'),
++ ),
++ ),
++ ),
++ );
++ },
++ );
++}
diff --cc desktop/lib/settings/sections/usage_section.dart
index b958765a5,b958765a5..511f2b2a4
--- a/desktop/lib/settings/sections/usage_section.dart
+++ b/desktop/lib/settings/sections/usage_section.dart
@@@ -172,6 -172,6 +172,17 @@@ class _UsageSectionState extends State<
UsageEmptyState(onEnable: _enable)
else ...[
_cards(overview),
++ if (overview.hasUnpricedModel)
++ Padding(
++ padding: const EdgeInsets.only(top: 8),
++ child: Text(
++ 'The cost is a lower bound because some model prices are unavailable.',
++ style: TextStyle(
++ fontSize: 11.5,
++ color: AppPalette.textSecondary,
++ ),
++ ),
++ ),
if (overview.hasAnyData) ...[
const SizedBox(height: 12),
_PanelPair(
@@@ -216,6 -216,6 +227,9 @@@
label: 'Est. cost',
value: formatCost(overview.costUsd),
icon: LucideIcons.coins300,
++ footnote: overview.hasUnpricedModel
++ ? 'at least — some models unpriced'
++ : null,
),
UsageStatCard(
label: 'Active days',
diff --cc desktop/lib/settings/settings_screen.dart
index 301650f1a,301650f1a..6e70d6ea4
--- a/desktop/lib/settings/settings_screen.dart
+++ b/desktop/lib/settings/settings_screen.dart
@@@ -5,6 -5,6 +5,7 @@@ import '../shared/theme/app_theme.dart
import '../state/app_state.dart';
import '../widgets/window_chrome.dart';
import 'sections/about_section.dart';
++import 'sections/account_section.dart';
import 'sections/appearance_section.dart';
import 'sections/debug_section.dart';
import 'sections/devices_section.dart';
@@@ -158,6 -158,6 +159,7 @@@ class _SettingsBody extends StatelessWi
@override
Widget build(BuildContext context) {
final screen = switch (section) {
++ SettingsSection.account => AccountSection(notifier: notifier),
SettingsSection.appearance => const AppearanceSection(),
SettingsSection.terminal => const TerminalSection(),
SettingsSection.usage => const UsageSection(),
diff --cc desktop/lib/settings/settings_section.dart
index 57634f570,57634f570..5ab5e69f5
--- a/desktop/lib/settings/settings_section.dart
+++ b/desktop/lib/settings/settings_section.dart
@@@ -9,6 -9,6 +9,7 @@@ import '../logging/debug_surface.dart'
/// rail, the search filter and the pane all read this list, so a section cannot
/// be listed without a screen behind it or reachable without a row.
enum SettingsSection {
++ account(LucideIcons.user300, 'Account'),
appearance(LucideIcons.sun300, 'Appearance'),
terminal(LucideIcons.terminal300, 'Terminal'),
usage(LucideIcons.chartNoAxesColumn300, 'Usage'),
@@@ -86,6 -86,6 +87,7 @@@ const _kSettingsGroups =
SettingsSection.terminal,
SettingsSection.usage,
SettingsSection.devices,
++ SettingsSection.account,
]),
// Debug and Tracking sit between the two things they are most often reached
// from: the keys that open them, and the version a report has to name. The
diff --cc desktop/lib/shortcuts/app_shortcuts.dart
index 98703fa05,98703fa05..2041133e3
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@@ -45,6 -45,6 +45,12 @@@ import '../logging/debug_surface.dart'
/// which binds the same four on macOS. Do not put them back.
enum ShortcutAction {
++ newSwarm,
++ closeSwarm,
++ renameSwarm,
++ nextSwarm,
++ previousSwarm,
++ showSettings,
toggleRail,
nextAgent,
previousAgent,
@@@ -420,11 -420,11 +426,115 @@@ const AppShortcut kDebugShortcut = AppS
/// The one list the bindings, the ⌘/ sheet and the tooltips all read, so a
/// build cannot bind a key it does not document or document one it does not
/// bind.
--List<AppShortcut> appShortcuts() => [
-- ...kAppShortcuts,
++List<AppShortcut> appShortcuts({bool swarmMode = true}) => [
++ for (final shortcut in kAppShortcuts)
++ if (!swarmMode ||
++ (!const {
++ ShortcutAction.toggleRail,
++ ShortcutAction.closePane,
++ ShortcutAction.switchAgent,
++ }.contains(shortcut.action) &&
++ !shortcut.activator.control))
++ shortcut,
++ if (swarmMode) ...kSwarmShortcuts,
if (kDebugSurfaceEnabled) kDebugShortcut,
];
++/// Swarm bindings replace the old workspace navigation in the retained legacy
++/// screen. Live Swarm bindings, tooltips, and help all use this same catalog.
++const kSwarmShortcuts = [
++ AppShortcut(
++ action: ShortcutAction.newSwarm,
++ activator: SingleActivator(LogicalKeyboardKey.keyT, meta: true),
++ label: 'New swarm',
++ group: ShortcutGroup.navigate,
++ ),
++ AppShortcut(
++ action: ShortcutAction.closeSwarm,
++ activator: SingleActivator(LogicalKeyboardKey.keyW, meta: true),
++ label: 'Close this swarm',
++ group: ShortcutGroup.navigate,
++ ),
++ AppShortcut(
++ action: ShortcutAction.renameSwarm,
++ activator: SingleActivator(
++ LogicalKeyboardKey.keyR,
++ meta: true,
++ shift: true,
++ ),
++ label: 'Rename this swarm',
++ group: ShortcutGroup.navigate,
++ ),
++ AppShortcut(
++ action: ShortcutAction.nextSwarm,
++ activator: SingleActivator(
++ LogicalKeyboardKey.bracketRight,
++ meta: true,
++ shift: true,
++ ),
++ label: 'Next swarm',
++ group: ShortcutGroup.navigate,
++ ),
++ AppShortcut(
++ action: ShortcutAction.previousSwarm,
++ activator: SingleActivator(
++ LogicalKeyboardKey.bracketLeft,
++ meta: true,
++ shift: true,
++ ),
++ label: 'Previous swarm',
++ group: ShortcutGroup.navigate,
++ ),
++ AppShortcut(
++ action: ShortcutAction.nextSwarm,
++ activator: SingleActivator(LogicalKeyboardKey.tab, control: true),
++ label: 'Next swarm',
++ group: ShortcutGroup.navigate,
++ ),
++ AppShortcut(
++ action: ShortcutAction.previousSwarm,
++ activator: SingleActivator(
++ LogicalKeyboardKey.tab,
++ control: true,
++ shift: true,
++ ),
++ label: 'Previous swarm',
++ group: ShortcutGroup.navigate,
++ ),
++ AppShortcut(
++ action: ShortcutAction.switchAgent,
++ activator: SingleActivator(LogicalKeyboardKey.keyP, meta: true),
++ label: 'Add an agent to this swarm',
++ group: ShortcutGroup.actions,
++ ),
++ AppShortcut(
++ action: ShortcutAction.switchAgent,
++ activator: SingleActivator(
++ LogicalKeyboardKey.keyF,
++ meta: true,
++ shift: true,
++ ),
++ label: 'Add an agent to this swarm',
++ group: ShortcutGroup.actions,
++ ),
++ AppShortcut(
++ action: ShortcutAction.closePane,
++ activator: SingleActivator(
++ LogicalKeyboardKey.keyW,
++ meta: true,
++ shift: true,
++ ),
++ label: 'Close the focused agent view',
++ group: ShortcutGroup.panes,
++ ),
++ AppShortcut(
++ action: ShortcutAction.showSettings,
++ activator: SingleActivator(LogicalKeyboardKey.comma, meta: true),
++ label: 'Open Settings',
++ group: ShortcutGroup.actions,
++ ),
++];
++
/// `⌘1`…`⌘9` jump to the nth TILE on the grid.
///
/// Tiles, not sidebar rows: the number is the one printed on the tile and the
@@@ -549,9 -549,9 +659,10 @@@ const List<TerminalKey> kTerminalOwnedK
Map<ShortcutActivator, VoidCallback> buildShortcutBindings({
required Map<ShortcutAction, VoidCallback> handlers,
void Function(int index)? onSelectPaneIndex,
++ bool swarmMode = true,
}) {
final bindings = <ShortcutActivator, VoidCallback>{};
-- for (final shortcut in appShortcuts()) {
++ for (final shortcut in appShortcuts(swarmMode: swarmMode)) {
final handler = handlers[shortcut.action];
if (handler != null) bindings[shortcut.activator] = handler;
}
@@@ -601,15 -601,15 +712,19 @@@ String _keyLabel(LogicalKeyboardKey key
///
/// Tooltips read this instead of spelling the keys out, so a rebinding cannot
/// leave a button advertising a key that no longer works.
--String? shortcutHintFor(ShortcutAction action) {
-- for (final shortcut in appShortcuts()) {
++String? shortcutHintFor(ShortcutAction action, {bool swarmMode = true}) {
++ for (final shortcut in appShortcuts(swarmMode: swarmMode)) {
if (shortcut.action == action) return describeShortcut(shortcut.activator);
}
return null;
}
/// "Reload machines ⌘R"
--String withShortcutHint(String tooltip, ShortcutAction action) {
-- final hint = shortcutHintFor(action);
++String withShortcutHint(
++ String tooltip,
++ ShortcutAction action, {
++ bool swarmMode = true,
++}) {
++ final hint = shortcutHintFor(action, swarmMode: swarmMode);
return hint == null ? tooltip : '$tooltip $hint';
}
diff --cc desktop/lib/state/app_state.dart
index 818e7037c,96af2c202..82b5d81d2
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@@ -23,7 -22,7 +23,6 @@@ import '../stats/harness_stats.dart'
import '../terminal/terminal_session.dart';
import '../terminal/remote_media_download.dart';
import '../widgets/engine_identity.dart' show allEngines;
--import '../core/harness_file_store.dart';
import 'dial_status.dart';
import 'pane_layout_store.dart';
import 'terminal_pane.dart';
@@@ -162,6 -160,6 +161,9 @@@ class MachineState
bool get isLocalMachine => localOnly || localEndpoint != null;
bool get usesLocalTransport => localEndpoint != null;
++ AgentProject? projectOf(Agent agent) =>
++ agent.project ?? localEndpoint?.agentProjects[agent.id];
++
Agent? get activeAgent {
for (final agent in agents) {
if (agent.id == activeAgentId) return agent;
@@@ -251,6 -249,6 +253,8 @@@ class AppNotifier extends ChangeNotifie
localCliDiscovery ?? LocalCliDiscovery(config: config);
final EnvironmentProvisioner? environmentProvisioner;
final DesktopUpdater? desktopUpdater;
++ @visibleForTesting
++ final WsConn Function(String machineId)? connectionForTest;
final Map<String, Timer> _turnActivityWatchdogs = {};
/// When this launch became signed in, and by which route — until the first
@@@ -517,6 -393,6 +521,7 @@@
this.localCliDiscovery,
this.environmentProvisioner,
this.desktopUpdater,
++ this.connectionForTest,
CliLogin? cliLogin,
CliLink? cliLink,
PaneLayoutStore? paneLayoutStore,
@@@ -525,9 -401,9 +530,7 @@@
// Remembers "a dial has been seen here" on the same terms the pane
// layout is remembered: with a layout store there is a state file, and
// without one (the tests) nothing is written anywhere.
-- dial = DialState(
- paneLayoutStore?.storage,
- paneLayoutStore == null ? null : HarnessFileStore.shared,
-- ),
++ dial = DialState(paneLayoutStore?.storage),
session = authSession,
_store = configStore,
cliLogin = cliLogin ?? CliLogin(),
@@@ -1507,6 -1377,6 +1510,7 @@@
_daemonSupervisionTimer ??= discovery.startSupervising(
stillSignedIn: () async => (await cliLogin.checkStatus()).loggedIn,
onSignedOut: () => _signedOutAtRuntime(_signedOutMessage),
++ onSnapshot: _updateLocalProjectSnapshot,
onReady: (endpoint) {
// Back (or here for the first time). If the app is sitting on the error strip from a boot
// or reload that found the daemon not ready, this is the moment it was waiting for.
@@@ -1522,6 -1392,6 +1526,22 @@@
);
}
++ void _updateLocalProjectSnapshot(LocalCliEndpoint endpoint) {
++ if (_disposed) return;
++ var changed = false;
++ for (final machine in machineStates.values) {
++ final previous = machine.localEndpoint;
++ if (previous == null ||
++ previous.computerId != endpoint.computerId ||
++ mapEquals(previous.agentProjects, endpoint.agentProjects)) {
++ continue;
++ }
++ machine.localEndpoint = endpoint;
++ changed = true;
++ }
++ if (changed) notifyListeners();
++ }
++
/// Deliberately says nothing about WHY. The daemon clears its session identically whether the
/// machine was deleted from another machine or the SSO token simply expired, and guessing between
/// them in the copy would sometimes be wrong. Signing in again is the answer to both.
@@@ -1556,6 -1425,6 +1576,8 @@@
);
}
++ bool get desktopUpdatesEnabled => !isHarnessV2 || desktopUpdater != null;
++
void _handleBackgroundUpdate(UpdateInfo info) {
if (_disposed) return;
if (_skippedDesktopUpdateVersion == info.version) return;
@@@ -1611,6 -1479,6 +1633,7 @@@
/// Downloads, verifies, and installs only after an explicit user action.
/// A failed operation leaves the running app untouched and retryable.
Future<bool> installAvailableUpdate() async {
++ if (isHarnessV2 && desktopUpdater == null) return false;
final info = availableUpdate;
if (info == null || isInstallingUpdate) return false;
isInstallingUpdate = true;
@@@ -2318,6 -2182,6 +2341,8 @@@
}
WsConn _conn(String machineId) {
++ final testConnection = connectionForTest;
++ if (testConnection != null) return testConnection(machineId);
// The local-manual dev fixture exercises a locally-run backend+node stack directly (no real
// `harness` CLI involved) — keep it on the old direct-cloud dial. Every other (real) machine now
// goes through the local CLI daemon regardless of whether it's this computer's own machine or a
@@@ -3023,13 -2907,7 +3048,14 @@@
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)
++ 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) {
@@@ -3066,6 -2944,6 +3092,7 @@@
}
final raw = result['agent'];
if (raw is! Map) return 'Create agent failed: malformed response';
++ if (_disposed || machineStates[machineId] != machine) return null;
final agent = Agent.fromJson(Map<String, dynamic>.from(raw));
// Idempotent on agent.id — safe even if the CLI's own agent_synced push for this session
// arrives separately (it's fire-and-forget on the CLI side and unordered relative to this reply).
@@@ -3319,37 -3193,37 +3346,14 @@@
}
}
-- /// Bring an agent up, the way a click on the rail means it.
++ /// Opens a dial notification in this swarm without changing other memberships.
///
/// Already on screen means FOCUS it, never open it twice: the daemon keeps a
/// single controller per agent, so a second open is a takeover — the window
/// would fight itself and the first tile would go dark with
/// `TERMINAL_TAKEN_OVER`.
///
-- /// Otherwise it replaces the focused tile rather than adding one. Adding is a
-- /// deliberate act (drag a row onto an empty slot); a click is navigation, and
-- /// a click that silently grew the grid would make four terminals out of four
-- /// glances at the rail.
-- /// Bring up an agent the DIAL turned to.
-- ///
-- /// The rule the dial's carousel is built around: the tiles come first, in tile order, and past either
-- /// end of them the ring continues into agents that have no tile. Landing on one of those is what puts
-- /// it on the desk — it replaces the tile at the end it was reached from, so the grid stays the size the
-- /// user chose and the tile that changes is the one they walked off.
-- ///
-- /// Which end is the daemon's answer, not a guess made here: it owns the flat list of every agent on
-- /// every machine, so it is the only side that can say whether an agent sits before the first tile or
-- /// after the last. With no tiles at all there is no end to replace, and the agent opens a new one.
-- /// A notification on the dial was tapped: give that agent a tile of its OWN.
-- ///
-- /// A different verb from turning the dial, and the difference is the point. Turning says where the eye
-- /// is, and a tile moves to match; a notification is a turn that just FINISHED — something new to look
-- /// at, not a replacement for whatever the person was already watching. So the grid grows.
-- ///
-- /// At the ceiling it reuses the LAST tile. The alternative is refusing, and a notification that cannot
-- /// be opened is a notification that lies: it says there is something to see and then does nothing when
-- /// pressed. The last tile is the one the desk already treats as the place things arrive — it is what
-- /// the dial's own right edge replaces.
++ /// At capacity, the usual visible capacity error asks for another swarm.
Future<void> openAgentFromDial(String machineId, String agentId) async {
// Already on the desk: it has its tile, so this is only "look at it".
final existing = paneOfAgent(machineId, agentId);
@@@ -3359,11 -3233,11 +3363,7 @@@
notifyListeners();
return;
}
-- if (canAddPane) {
-- await assignAgentToPane(null, machineId, agentId);
-- return;
-- }
-- await assignAgentToPane(panes.last.id, machineId, agentId);
++ await addAgentToSwarm(machineId, agentId);
}
/// The dial turned to an agent. Ordinary selection, the same path a click on the rail takes.
@@@ -3540,7 -3412,7 +3540,9 @@@
machine.pendingOfflineAgentId = null;
_stopOfflineRetry(machineId);
notifyListeners();
- if (target == activeSwarm || pane.session != null) await _attachSession(pane);
- await _attachSession(pane);
++ if (target == activeSwarm || pane.session != null) {
++ await _attachSession(pane);
++ }
}
/// Open the stream for a tile that already knows what it wants.
@@@ -3970,103 -3844,12 +3972,111 @@@
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)
++ 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!;
++ 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']);
++ swarm.previousPaneId = paneAt(raw['previousFocus']);
+ 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;
++ final legacyPresets = await store.loadPresets();
++ if (_disposed || revision != _layoutRevision) return;
+ if (allPanes.isNotEmpty ||
+ swarms.length != 1 ||
- activeSwarm != initialSwarm)
++ activeSwarm != initialSwarm) {
+ return;
++ }
final entries = await store.load();
++ if (_disposed || revision != _layoutRevision) return;
++ panePresets.addAll(legacyPresets);
if (entries.isEmpty) {
if (panePresets.isNotEmpty) notifyListeners();
return;
diff --cc desktop/lib/state/pane_layout_store.dart
index 3bb17b53b,8ca31b6de..bbfd439ff
--- a/desktop/lib/state/pane_layout_store.dart
+++ b/desktop/lib/state/pane_layout_store.dart
@@@ -117,41 -115,6 +117,42 @@@ 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)
++ 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 --cc desktop/lib/state/swarm.dart
index 25f423101,000000000..612889250
mode 100644,000000..100644
--- a/desktop/lib/state/swarm.dart
+++ b/desktop/lib/state/swarm.dart
@@@ -1,68 -1,0 +1,72 @@@
+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),
++ 'previousFocus': panes
++ .where((p) => p.agentId != null)
++ .toList()
++ .indexWhere((p) => p.id == previousPaneId),
+ '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 --cc desktop/lib/state/swarm_catalog.dart
index 998b2486e,000000000..7a12a2a6d
mode 100644,000000..100644
--- a/desktop/lib/state/swarm_catalog.dart
+++ b/desktop/lib/state/swarm_catalog.dart
@@@ -1,142 -1,0 +1,195 @@@
+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;
++ AgentProject? get project => machine.projectOf(agent);
+ String get searchText => [
+ agent.name,
+ agent.engine,
+ machine.machine.displayName,
- agent.project?.name,
- agent.project?.branch,
- agent.project?.cwd,
++ project?.name,
++ project?.branch,
++ 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;
++ final project = entry.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)
++ 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 {
++ bool _loaded = false;
++ Future<void>? _loadFuture;
++ Future<void> _writeTail = Future.value();
++ String? error;
++
++ Future<void> load() {
++ if (_loaded || _disposed) return Future.value();
++ return _loadFuture ??= _read().whenComplete(() => _loadFuture = null);
++ }
++
++ Future<void> _read() async {
+ try {
+ final raw = await storage?.read('swarm_projects_v1');
- if (raw == null || _disposed) return;
- final rows = jsonDecode(raw);
- if (rows is! List) return;
++ if (_disposed) return;
++ final rows = raw == null ? const [] : jsonDecode(raw);
++ if (rows is! List) throw const FormatException('Invalid project catalog');
++ final loaded = <SavedSwarmProject>[];
+ for (final row in rows.take(256)) {
+ if (row is! Map ||
+ row['machineId'] is! String ||
+ row['path'] is! String ||
- row['name'] 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))
++ loaded.any((p) => p.id == item.id)) {
+ continue;
- projects.add(item);
++ }
++ loaded.add(item);
+ }
- notifyListeners();
++ projects
++ ..clear()
++ ..addAll(loaded);
++ _loaded = true;
++ error = null;
+ } catch (_) {
- /* A damaged catalog does not prevent opening live agents. */
++ if (_disposed) return;
++ error = 'Could not load saved projects. Add the project again to retry.';
+ }
++ notifyListeners();
+ }
+
- Future<void> add(SavedSwarmProject project) async {
- projects.removeWhere((p) => p.id == project.id);
- projects.add(project);
++ Future<bool> add(SavedSwarmProject project) {
++ final operation = _writeTail.then((_) async {
++ await load();
++ if (_disposed || !_loaded) return false;
++ final next = [
++ for (final item in projects)
++ if (item.id != project.id) item,
++ project,
++ ];
++ if (next.length > 256) {
++ error = 'The project list is full.';
++ notifyListeners();
++ return false;
++ }
++ try {
++ await storage?.write(
++ 'swarm_projects_v1',
++ jsonEncode(next.map((p) => p.toJson()).toList()),
++ );
++ } catch (_) {
++ if (_disposed) return false;
++ error = 'Could not save this project. Add it again to retry.';
++ notifyListeners();
++ return false;
++ }
++ if (_disposed) return false;
++ projects
++ ..clear()
++ ..addAll(next);
++ error = null;
++ notifyListeners();
++ return true;
++ });
++ _writeTail = operation.then((_) {});
++ return operation;
++ }
++
++ void dismissError() {
++ error = null;
+ notifyListeners();
- await storage?.write(
- 'swarm_projects_v1',
- jsonEncode(projects.map((p) => p.toJson()).toList()),
- );
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ super.dispose();
+ }
+}
diff --cc desktop/lib/update/desktop_updater.dart
index c353fe092,f9b811eb0..b4b58da60
--- a/desktop/lib/update/desktop_updater.dart
+++ b/desktop/lib/update/desktop_updater.dart
@@@ -7,6 -7,6 +7,7 @@@ import 'package:dio/dio.dart'
import 'package:flutter/foundation.dart';
import '../core/app_version.dart';
++import '../core/build_identity.dart';
/// Published by `scripts/upload-desktop.sh` (`make upload-desktop`) — see
/// `RELEASE.md` for the full publish-side design this mirrors.
@@@ -145,10 -145,10 +146,12 @@@ class DesktopUpdater
final Future<void> Function(String command) _launchDetached;
final String _metadataUrlForInstance;
final bool _releaseMode;
++ final bool _enabled;
final bool _isLinux;
final String _architecture;
DesktopUpdater({
++ this._enabled = !isHarnessV2,
Dio? dio,
Future<void> Function(String command)? launchDetached,
// Defaults to the real manifest (or the --dart-define build-time override — see RELEASE.md's
@@@ -197,7 -197,7 +200,7 @@@
/// bundle for a downloaded release build and relaunching, see [applyStaged]) makes no sense for a
/// local dev build and would silently clobber it mid-session.
Future<UpdateInfo?> checkOnce({String? currentVersion}) async {
-- if (!_releaseMode) return null;
++ if (!_enabled || !_releaseMode) return null;
try {
final running = currentVersion ?? await runningAppVersion();
final response = await _dio.get<Map<String, dynamic>>(
@@@ -274,6 -274,6 +277,7 @@@
/// executable and staged as-is, with nothing to unpack or recheck.
/// Returns null (and cleans up anything partially written) on any verification failure.
Future<StagedUpdate?> downloadAndStage(UpdateInfo info) async {
++ if (!_enabled) return null;
Directory? stagingDir;
try {
final response = await _dio.get<List<int>>(
@@@ -379,6 -379,6 +383,7 @@@
required int selfPid,
String? runningBundlePath,
}) async {
++ if (!_enabled) return false;
final bundlePath =
runningBundlePath ?? currentBundlePath(isLinux: _isLinux);
if (bundlePath == null) {
diff --cc desktop/lib/widgets/codex_profile_field.dart
index 479432aaa,479432aaa..c28643b50
--- a/desktop/lib/widgets/codex_profile_field.dart
+++ b/desktop/lib/widgets/codex_profile_field.dart
@@@ -43,6 -43,6 +43,7 @@@ class _CodexProfileFieldState extends S
bool _hasChosenProfile = false;
String? _error;
int _loadGeneration = 0;
++ int _machineRevision = 0;
@override
void initState() {
@@@ -53,7 -53,7 +54,17 @@@
@override
void didUpdateWidget(CodexProfileField oldWidget) {
super.didUpdateWidget(oldWidget);
-- if (!setEquals(oldWidget.observedPaths, widget.observedPaths)) _load();
++ if (oldWidget.machineId != widget.machineId ||
++ oldWidget.machineIsThisComputer != widget.machineIsThisComputer ||
++ oldWidget.notifier != widget.notifier) {
++ _machineRevision++;
++ _profiles = [];
++ _hasChosenProfile = false;
++ _linking = false;
++ _load();
++ } else if (!setEquals(oldWidget.observedPaths, widget.observedPaths)) {
++ _load();
++ }
}
Future<void> _load() async {
@@@ -112,6 -112,6 +123,9 @@@
Future<void> _link() async {
if (_linking) return;
++ final machineId = widget.machineId;
++ final revision = _machineRevision;
++ bool current() => mounted && revision == _machineRevision;
setState(() {
_linking = true;
_error = null;
@@@ -130,15 -130,15 +144,12 @@@
: await showRemoteFolderPicker(
context,
notifier: widget.notifier,
-- machineId: widget.machineId,
++ machineId: machineId,
initialPath: widget.value?.path,
);
-- if (path == null || !mounted) return;
-- final result = await widget.notifier.linkCodexProfile(
-- widget.machineId,
-- path,
-- );
-- if (!mounted) return;
++ if (path == null || !current()) return;
++ final result = await widget.notifier.linkCodexProfile(machineId, path);
++ if (!current()) return;
final error = result['error'];
if (error is String) {
setState(
@@@ -150,15 -150,15 +161,15 @@@
Map<String, dynamic>.from(result['profile'] as Map),
);
await _load();
-- if (mounted) _select(profile);
++ if (current()) _select(profile);
} catch (_) {
-- if (mounted) {
++ if (current()) {
setState(
() => _error = 'Could not link this profile folder. Check that it is accessible.',
);
}
} finally {
-- if (mounted) {
++ if (current()) {
setState(() => _linking = false);
_reportBusy();
}
diff --cc desktop/lib/widgets/machine_rail.dart
index 6b925c76d,6b925c76d..918cc8e33
--- a/desktop/lib/widgets/machine_rail.dart
+++ b/desktop/lib/widgets/machine_rail.dart
@@@ -272,6 -272,6 +272,7 @@@ class _MachineRailState extends State<M
tooltip: withShortcutHint(
'Collapse sidebar',
ShortcutAction.toggleRail,
++ swarmMode: false,
),
onPressed: widget.onCollapse!,
),
diff --cc desktop/lib/widgets/new_agent_dialog.dart
index 31799c5fe,8506c26f1..87aa1deca
--- a/desktop/lib/widgets/new_agent_dialog.dart
+++ b/desktop/lib/widgets/new_agent_dialog.dart
@@@ -76,8 -63,7 +76,9 @@@ class _NewAgentDialog extends StatefulW
class _NewAgentDialogState extends State<_NewAgentDialog> {
late String _engine = allEngines.first.id;
- String? _folder;
+ late String _machineId = widget.machineId;
++ int _machineRevision = 0;
+ late String? _folder = widget.initialFolder;
LocalCodexProfile? _codexProfile;
bool _codexProfilesBusy = true;
bool _bypassPermission = false;
@@@ -104,7 -90,7 +105,9 @@@
// 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(_machineId, force: true));
- unawaited(widget.notifier.probeEngines(widget.machineId, force: true));
++ if (mounted) {
++ unawaited(widget.notifier.probeEngines(_machineId, force: true));
++ }
});
}
@@@ -242,7 -228,6 +245,7 @@@
// 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;
++ final pickingRevision = _machineRevision;
try {
final picked = _machineIsThisComputer
? await getDirectoryPath(initialDirectory: _folder)
@@@ -255,13 -240,13 +258,17 @@@
if (!mounted) return;
setState(() {
_picking = false;
- if (picked != null && pickingMachine == _machineId) _folder = picked;
- if (picked != null) _folder = picked;
++ if (picked != null && pickingRevision == _machineRevision) {
++ _folder = picked;
++ }
});
} catch (error) {
if (!mounted) return;
setState(() {
_picking = false;
-- _error = 'Could not open the folder picker: $error';
++ if (pickingRevision == _machineRevision) {
++ _error = 'Could not open the folder picker: $error';
++ }
});
}
}
@@@ -385,36 -369,6 +392,37 @@@
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(() {
++ _machineRevision++;
+ _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`.
//
diff --cc desktop/lib/widgets/pane_grid.dart
index 540cbc896,70168fdeb..fcc3d1014
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@@ -738,12 -722,6 +738,17 @@@ class _PaneContent extends StatelessWid
);
}
+ if (agent != null && !agent.terminalAvailable) {
- return _PaneStatus(title: agentName, icon: Icons.terminal,
- message: agent.terminalUnavailableReason ?? 'This agent has no available terminal.',
- onClose: close);
++ 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(
@@@ -1173,7 -1149,7 +1178,8 @@@ class _Guide extends StatelessWidget
return LayoutBuilder(
builder: (context, constraints) {
final roomForCard =
-- constraints.maxWidth >= 520 && constraints.maxHeight >= 430;
++ constraints.maxWidth >= 520 &&
++ constraints.maxHeight >= (single ? 500 : 546);
if (roomForCard) {
if (single) return full;
return Column(
diff --cc desktop/lib/widgets/swarm_agent_selection.dart
index 000000000,000000000..9fe22c4cc
new file mode 100644
--- /dev/null
+++ b/desktop/lib/widgets/swarm_agent_selection.dart
@@@ -1,0 -1,0 +1,37 @@@
++import '../state/swarm_catalog.dart';
++
++/// Keep the highlighted agent stable when live discovery inserts or removes rows.
++class SwarmAgentSelection {
++ int _index = 0;
++ (String, String)? _identity;
++
++ void reset() {
++ _index = 0;
++ _identity = null;
++ }
++
++ int index(List<SwarmAgentRef> rows) {
++ if (rows.isEmpty) {
++ reset();
++ return 0;
++ }
++ final found = rows.indexWhere(
++ (row) => (row.machineId, row.agent.id) == _identity,
++ );
++ _select(rows, found < 0 ? _index.clamp(0, rows.length - 1) : found);
++ return _index;
++ }
++
++ void move(List<SwarmAgentRef> rows, int delta) {
++ if (rows.isEmpty) return;
++ _select(rows, (index(rows) + delta) % rows.length);
++ }
++
++ SwarmAgentRef? selected(List<SwarmAgentRef> rows) =>
++ rows.isEmpty ? null : rows[index(rows)];
++
++ void _select(List<SwarmAgentRef> rows, int index) {
++ _index = index;
++ _identity = (rows[index].machineId, rows[index].agent.id);
++ }
++}
diff --cc desktop/lib/widgets/swarm_dialogs.dart
index e9b119091,000000000..20e8ffac1
mode 100644,000000..100644
--- a/desktop/lib/widgets/swarm_dialogs.dart
+++ b/desktop/lib/widgets/swarm_dialogs.dart
@@@ -1,352 -1,0 +1,386 @@@
+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';
++import 'swarm_agent_selection.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 = '';
++ final _selection = SwarmAgentSelection();
+ @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(
++ Widget build(BuildContext context) => ListenableBuilder(
++ listenable: widget.notifier,
++ builder: (context, _) {
++ final rows = swarmAgents(widget.notifier, query);
++ return Dialog(
++ child: SizedBox(
++ width: 620,
++ height: 520,
++ child: Padding(
++ padding: const EdgeInsets.all(22),
++ child: Column(
++ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
- const Text(
- 'Add agent',
- style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
++ 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 Spacer(),
- TextButton.icon(
- onPressed: () {
- widget.onNew();
- Navigator.pop(context);
++ const SizedBox(height: 16),
++ SwarmSearchField(
++ autofocus: true,
++ onChanged: (value) => setState(() {
++ query = value;
++ _selection.reset();
++ }),
++ onMove: (delta) =>
++ setState(() => _selection.move(rows, delta)),
++ onSubmitted: () {
++ final selected = _selection.selected(rows);
++ if (selected != null) Navigator.pop(context, selected);
+ },
- 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),
++ Expanded(
++ child: SwarmAgentRows(
++ notifier: widget.notifier,
++ agents: rows,
++ selectedIndex: _selection.index(rows),
++ onAgent: (agent) => Navigator.pop(context, agent),
++ ),
+ ),
- ],
- ),
- 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),
++ const SizedBox(height: 10),
++ const Text(
++ '↑↓ or ⌃N ⌃P to choose · Return to add · Esc to cancel',
++ style: TextStyle(fontSize: 11, color: Colors.white60),
+ ),
- ),
++ ],
+ ),
- ],
++ ),
+ ),
- ),
- ),
++ );
++ },
+ );
+}
+
+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;
++ int _machineRevision = 0;
+ @override
+ void dispose() {
+ name.dispose();
+ super.dispose();
+ }
+
+ Future<void> browse() async {
+ final id = machineId;
+ if (id == null || picking) return;
++ final revision = _machineRevision;
+ 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;
++ if (!mounted || revision != _machineRevision) return;
+ setState(() {
+ path = folder ?? path;
- if (folder != null && name.text.trim().isEmpty)
- name.text = folder.split('/').where((s) => s.isNotEmpty).last;
++ if (folder != null && name.text.trim().isEmpty) {
++ name.text =
++ (folder
++ .split(RegExp(r'[/\\]'))
++ .where((s) => s.isNotEmpty)
++ .lastOrNull ??
++ folder)
++ .characters
++ .take(80)
++ .join();
++ }
+ });
+ } catch (_) {
- if (mounted)
++ if (mounted && revision == _machineRevision) {
+ 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(() {
++ if (machineId == value) return;
++ _machineRevision++;
+ machineId = value;
+ path = null;
++ error = 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 --cc desktop/lib/widgets/swarm_welcome.dart
index 11697d6ef,000000000..6c1fdeee5
mode 100644,000000..100644
--- a/desktop/lib/widgets/swarm_welcome.dart
+++ b/desktop/lib/widgets/swarm_welcome.dart
@@@ -1,453 -1,0 +1,588 @@@
+import 'dart:ui' show ImageFilter;
+
+import 'package:flutter/material.dart';
++import 'package:flutter/services.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';
++import 'swarm_agent_selection.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 = '';
++ final _selection = SwarmAgentSelection();
+ @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);
++ autofocus: true,
++ onChanged: (v) => setState(() {
++ _query = v;
++ _selection.reset();
++ }),
++ onMove: (delta) {
++ if (_query.trim().isNotEmpty) {
++ setState(
++ () => _selection.move(results, delta),
++ );
++ }
++ },
++ onSubmitted: () {
++ final selected = _selection.selected(results);
++ if (_query.trim().isNotEmpty &&
++ selected != null) {
++ widget.onAgent(selected);
++ }
+ },
+ ),
+ ),
+ 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,
++ selectedIndex: _selection.index(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 {
++class SwarmSearchField extends StatefulWidget {
+ const SwarmSearchField({
+ super.key,
+ required this.onChanged,
+ this.onSubmitted,
++ this.onMove,
+ this.autofocus = false,
+ });
+ final ValueChanged<String> onChanged;
- final ValueChanged<String>? onSubmitted;
++ final VoidCallback? onSubmitted;
++ final ValueChanged<int>? onMove;
+ 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),
++ State<SwarmSearchField> createState() => _SwarmSearchFieldState();
++}
++
++class _SwarmSearchFieldState extends State<SwarmSearchField> {
++ final _focus = FocusNode(debugLabel: 'Find agent');
++
++ @override
++ void initState() {
++ super.initState();
++ if (widget.autofocus) {
++ WidgetsBinding.instance.addPostFrameCallback((_) {
++ // The dialog veil also requests fallback focus in this frame. The
++ // search field must win so the first keystroke starts searching.
++ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
++ _focus.requestFocus();
++ }
++ });
++ }
++ }
++
++ @override
++ void dispose() {
++ _focus.dispose();
++ super.dispose();
++ }
++
++ @override
++ Widget build(BuildContext context) {
++ final onMove = widget.onMove;
++ final onSubmitted = widget.onSubmitted;
++ return CallbackShortcuts(
++ bindings: {
++ if (onSubmitted != null) ...{
++ const SingleActivator(LogicalKeyboardKey.enter): onSubmitted,
++ const SingleActivator(LogicalKeyboardKey.numpadEnter): onSubmitted,
++ },
++ if (onMove != null) ...{
++ const SingleActivator(LogicalKeyboardKey.arrowDown): () => onMove(1),
++ const SingleActivator(LogicalKeyboardKey.arrowUp): () => onMove(-1),
++ const SingleActivator(LogicalKeyboardKey.keyN, control: true): () =>
++ onMove(1),
++ const SingleActivator(LogicalKeyboardKey.keyP, control: true): () =>
++ onMove(-1),
++ },
++ },
++ child: TextField(
++ focusNode: _focus,
++ autofocus: widget.autofocus,
++ onChanged: widget.onChanged,
++ onSubmitted: (_) => onSubmitted?.call(),
++ 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 {
++class SwarmAgentRows extends StatefulWidget {
+ const SwarmAgentRows({
+ super.key,
+ required this.notifier,
+ required this.agents,
+ required this.onAgent,
++ this.selectedIndex,
+ });
+ final AppNotifier notifier;
+ final List<SwarmAgentRef> agents;
+ final ValueChanged<SwarmAgentRef> onAgent;
++ final int? selectedIndex;
++ @override
++ State<SwarmAgentRows> createState() => _SwarmAgentRowsState();
++}
++
++class _SwarmAgentRowsState extends State<SwarmAgentRows> {
++ final _scroll = ScrollController();
++ double _rowHeight = 64;
++ @override
++ void dispose() {
++ _scroll.dispose();
++ super.dispose();
++ }
++
++ void _revealSelection() {
++ final index = widget.selectedIndex;
++ if (!mounted ||
++ index == null ||
++ !_scroll.hasClients ||
++ widget.agents.isEmpty) {
++ return;
++ }
++ final position = _scroll.position;
++ final top = index * _rowHeight;
++ final bottom = top + _rowHeight;
++ final double? target = top < position.pixels
++ ? top
++ : bottom > position.pixels + position.viewportDimension
++ ? bottom - position.viewportDimension
++ : null;
++ if (target != null) {
++ _scroll.jumpTo(target.clamp(0, position.maxScrollExtent));
++ }
++ }
++
+ @override
+ Widget build(BuildContext context) {
- if (agents.isEmpty)
++ final agents = widget.agents;
++ final notifier = widget.notifier;
++ if (agents.isEmpty) {
+ return const Center(
+ child: Text(
+ 'No matching agents',
+ style: TextStyle(color: Colors.white60),
+ ),
+ );
++ }
++ final scaler = MediaQuery.textScalerOf(context);
++ _rowHeight = (scaler.scale(13) + scaler.scale(11) + 32).clamp(
++ 64,
++ double.infinity,
++ );
++ WidgetsBinding.instance.addPostFrameCallback((_) => _revealSelection());
+ return ListView.builder(
++ controller: _scroll,
++ padding: EdgeInsets.zero,
++ itemExtent: _rowHeight,
+ 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(
++ return Tooltip(
++ message: [
+ 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),
++ entry.machine.machine.displayName,
++ entry.project?.cwd,
++ ].whereType<String>().join('\n'),
++ child: Semantics(
++ selected: widget.selectedIndex == index,
++ child: ListTile(
++ key: ValueKey((entry.machineId, agent.id)),
++ selected: widget.selectedIndex == index,
++ selectedTileColor: grid.AppPalette.swarmAccent.withValues(
++ alpha: 0.14,
++ ),
++ shape: RoundedRectangleBorder(
++ borderRadius: BorderRadius.circular(8),
++ ),
++ minTileHeight: _rowHeight,
++ contentPadding: const EdgeInsets.symmetric(horizontal: 10),
++ 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 (entry.project != null) entry.project!.name,
++ if (entry.project?.branch != null) entry.project!.branch!,
++ ].join(' · '),
++ maxLines: 1,
++ overflow: TextOverflow.ellipsis,
++ style: const TextStyle(fontSize: 11, color: Colors.white70),
++ ),
++ 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: () => widget.onAgent(entry),
++ ),
+ ),
- 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 --cc desktop/lib/widgets/terminal_panel.dart
index a5466194b,0cccba8fa..3fcdc8fd4
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@@ -672,6 -661,6 +672,10 @@@ class _TerminalPanelState extends State
onClose: widget.onClose,
pinned: widget.pinned,
onTogglePin: widget.onTogglePin,
++ onToggleComposer: remote && !widget.readOnly
++ ? widget.onToggleComposer
++ : null,
++ composerVisible: widget.composerVisible,
paneDrag: widget.paneDrag,
),
@@@ -810,8 -796,7 +814,10 @@@ class _TerminalHeader extends Stateless
final TerminalSession session;
final VoidCallback? onClose;
final bool pinned;
+ final bool compact;
final VoidCallback? onTogglePin;
++ final VoidCallback? onToggleComposer;
++ final bool composerVisible;
/// This strip's drag gesture, or null when there is nothing to drag.
///
@@@ -828,8 -813,7 +834,10 @@@
required this.session,
this.onClose,
this.pinned = false,
+ this.compact = false,
this.onTogglePin,
++ this.onToggleComposer,
++ this.composerVisible = false,
this.paneDrag,
});
@@@ -873,17 -857,8 +881,17 @@@
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 project = agent == null ? null : machine?.projectOf(agent);
+ 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(
@@@ -988,8 -931,8 +996,27 @@@
// 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 (compact && onToggleComposer != null)
++ IconButton(
++ tooltip: composerVisible
++ ? 'Hide message composer'
++ : 'Show message composer',
++ onPressed: onToggleComposer,
++ icon: Icon(
++ Icons.edit_note,
++ size: 18,
++ color: composerVisible
++ ? AppColors.text
++ : AppColors.mutedStrong,
++ ),
++ constraints: const BoxConstraints.tightFor(
++ width: 28,
++ height: 28,
++ ),
++ padding: EdgeInsets.zero,
++ ),
if (onClose != null) PaneCloseButton(onPressed: onClose!),
],
),
diff --cc desktop/lib/ws/local_cli_discovery.dart
index 48ff84179,48ff84179..988187963
--- a/desktop/lib/ws/local_cli_discovery.dart
+++ b/desktop/lib/ws/local_cli_discovery.dart
@@@ -8,6 -8,6 +8,7 @@@ import '../core/serial_port_lease.dart'
import '../core/config.dart';
import '../core/harness_cli_runner.dart';
import '../core/harness_file_store.dart';
++import '../core/models.dart';
const localWsProtocolVersion = 1;
const localTerminalProtocolVersion = 3;
@@@ -18,11 -18,11 +19,16 @@@ class LocalCliEndpoint
final int protocolVersion;
final int terminalProtocolVersion;
++ /// Older daemons report local working folders in status before they support
++ /// project metadata in agent frames. This snapshot never describes a peer.
++ final Map<String, AgentProject> agentProjects;
++
const LocalCliEndpoint({
required this.computerId,
required this.wsUri,
required this.protocolVersion,
required this.terminalProtocolVersion,
++ this.agentProjects = const {},
});
}
@@@ -264,6 -264,6 +270,7 @@@ class LocalCliDiscovery
///
/// [onReady] fires on every transition INTO ready — the daemon coming back after an update, or
/// after a spawn — so the app can pick up where it left off without a click.
++ /// [onSnapshot] receives each ready probe, including changing local working folders.
Timer startSupervising({
Duration checkInterval = const Duration(seconds: 5),
Duration graceStep = const Duration(milliseconds: 500),
@@@ -274,6 -274,6 +281,7 @@@
Future<bool> Function()? stillSignedIn,
void Function()? onSignedOut,
void Function(LocalCliEndpoint endpoint)? onReady,
++ void Function(LocalCliEndpoint endpoint)? onSnapshot,
}) {
var backoff = initialBackoff;
var nextSpawnAllowedAt = DateTime.now();
@@@ -293,6 -293,6 +301,7 @@@
if (seen.ready) {
backoff = initialBackoff;
quietTicks = 0;
++ onSnapshot?.call(seen.endpoint!);
if (!wasReady) onReady?.call(seen.endpoint!);
wasReady = true;
return;
@@@ -489,6 -489,6 +498,10 @@@
.replace(scheme: base.scheme == 'https' ? 'wss' : 'ws'),
protocolVersion: protocolVersion as int,
terminalProtocolVersion: terminalProtocolVersion as int,
++ agentProjects: _localAgentProjects(
++ body['sessions'],
++ identity.environment,
++ ),
),
pid: pid,
version: version,
@@@ -496,6 -496,6 +509,57 @@@
}
}
++Map<String, AgentProject> _localAgentProjects(
++ Object? sessions,
++ Map<String, String> environment,
++) {
++ if (sessions is! List) return const {};
++ final projects = <String, AgentProject>{};
++ final home = environment['HOME'] ?? environment['USERPROFILE'];
++ for (final session in sessions) {
++ if (session is! Map || session['id'] is! String) continue;
++ final id = session['id'] as String;
++ final rawCwd = session['cwd'];
++ if (id.isEmpty ||
++ rawCwd is! String ||
++ rawCwd.isEmpty ||
++ rawCwd.length > 4096 ||
++ RegExp(r'[\x00-\x1f\x7f]').hasMatch(rawCwd)) {
++ continue;
++ }
++ String cwd = rawCwd;
++ if (cwd == '~' ||
++ cwd.startsWith('~/') ||
++ (Platform.isWindows && cwd.startsWith('~\\'))) {
++ if (home == null || home.isEmpty) continue;
++ cwd = '$home${cwd.substring(1)}';
++ }
++ final absolute = Platform.isWindows
++ ? RegExp(r'^[A-Za-z]:[\\/]|^\\\\').hasMatch(cwd)
++ : cwd.startsWith('/');
++ if (!absolute) continue;
++ try {
++ cwd = File(cwd).uri.normalizePath().toFilePath();
++ // Directory paths in the status may carry a trailing separator.
++ final separator = Platform.pathSeparator;
++ while (cwd.length > 1 &&
++ cwd.endsWith(separator) &&
++ !(Platform.isWindows && RegExp(r'^[A-Za-z]:\\$').hasMatch(cwd))) {
++ cwd = cwd.substring(0, cwd.length - 1);
++ }
++ final parts = cwd.split(separator).where((part) => part.isNotEmpty);
++ final project = AgentProject.fromJson({
++ 'name': parts.isEmpty ? cwd : parts.last,
++ 'cwd': cwd,
++ });
++ if (project != null) projects[id] = project;
++ } on FormatException {
++ // A malformed status row must not prevent discovery of the daemon.
++ }
++ }
++ return Map.unmodifiable(projects);
++}
++
String? _normalizeComputerId(Object? raw) {
if (raw is! String) return null;
final value = raw.trim().toLowerCase().replaceAll('-', '');
diff --cc desktop/linux/CMakeLists.txt
index bbf4b872d,bbf4b872d..07fdca88d
--- a/desktop/linux/CMakeLists.txt
+++ b/desktop/linux/CMakeLists.txt
@@@ -4,10 -4,10 +4,10 @@@ project(harness LANGUAGES CXX
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
--set(BINARY_NAME "harness")
++set(BINARY_NAME "harness-v2")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
--set(APPLICATION_ID "com.autonomous.harness")
++set(APPLICATION_ID "ai.autonomous.harness.v2")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
diff --cc desktop/linux/runner/my_application.cc
index f4da6f169,f4da6f169..015e560c2
--- a/desktop/linux/runner/my_application.cc
+++ b/desktop/linux/runner/my_application.cc
@@@ -164,7 -164,7 +164,7 @@@ static void my_application_activate(GAp
gtk_box_pack_start(GTK_BOX(title), icon, FALSE, FALSE, 0);
}
}
-- GtkWidget* label = gtk_label_new("Harness");
++ GtkWidget* label = gtk_label_new("Harness V2");
gtk_box_pack_start(GTK_BOX(title), label, FALSE, FALSE, 0);
gtk_widget_show_all(title);
gtk_header_bar_set_custom_title(header_bar, title);
@@@ -173,7 -173,7 +173,7 @@@
}
// Keep the native window metadata correct even when a custom header is
// drawn. Window managers use it for non-GNOME captions and accessibility.
-- gtk_window_set_title(window, "Harness");
++ gtk_window_set_title(window, "Harness V2");
gtk_window_set_default_size(window, 1280, 720);
diff --cc desktop/macos/Runner/SwarmTitlebar.swift
index 1bef0e2d4,000000000..bca5ae3fe
mode 100644,000000..100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@@ -1,270 -1,0 +1,314 @@@
+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 {
++final class SwarmTitlebar: NSObject, NSMenuItemValidation {
+ 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
++ private var actionsEnabled = false
+
+ init(window: NSWindow, messenger: FlutterBinaryMessenger) {
+ self.window = window
+ channel = FlutterMethodChannel(name: "harness/swarm_tabs", binaryMessenger: messenger)
++ super.init()
+ 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] ?? [:])
++ let state = call.arguments as? [String: Any] ?? [:]
++ self.actionsEnabled = state["enabled"] as? Bool == true
++ self.strip.update(state)
+ 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))
+ }
+
++ func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { actionsEnabled }
++
+ @objc private func menuAction(_ sender: NSMenuItem) {
- guard let action = sender.representedObject as? String else { return }
++ guard actionsEnabled, 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 = ""
++ private var actionsEnabled = false
+ 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]) {
++ actionsEnabled = state["enabled"] as? Bool == true
+ 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.actionsEnabled = actionsEnabled
+ 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
++ newButton.isEnabled = actionsEnabled && tabs.count < 24
++ notifications.isEnabled = actionsEnabled
++ settings.isEnabled = actionsEnabled
+ 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 draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { actionsEnabled ? .move : [] }
++ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { actionsEnabled ? .move : [] }
+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
- guard let id = sender.draggingPasteboard.string(forType: swarmPasteboardType),
++ guard actionsEnabled, 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 {
++private final class SwarmTabButton: NSView, NSDraggingSource {
+ let swarmId: String
+ var name = "New swarm"
+ var selected = false
+ var attention = false
+ var emit: ((String, Any?) -> Void)?
+ private let closeButton = NSButton()
++ private let selectButton = SwarmSelectButton()
++ var actionsEnabled = true {
++ didSet {
++ closeButton.isEnabled = actionsEnabled
++ selectButton.isEnabled = actionsEnabled
++ }
++ }
+ 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
++ setAccessibilityElement(true)
++ setAccessibilityRole(.group)
++ selectButton.owner = self
++ selectButton.title = ""
++ selectButton.isBordered = false
++ selectButton.target = self
++ selectButton.action = #selector(selectSwarm)
++ addSubview(selectButton)
+ 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()
++ selectButton.frame = NSRect(x: 0, y: 0, width: max(0, bounds.width - 29), height: bounds.height)
+ 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" : "")
++ selectButton.setAccessibilityLabel("Select \(name)")
++ selectButton.setAccessibilityValue(selected ? "Selected" : "")
+ toolTip = "\(name) — double-click to rename"
+ closeButton.setAccessibilityLabel("Close \(name)")
+ }
+ override func mouseDown(with event: NSEvent) {
++ guard actionsEnabled else { return }
+ downPoint = event.locationInWindow
+ if event.clickCount == 2 { renameSwarm() }
+ else { emit?("select", ["id": swarmId]) }
+ }
+ override func mouseDragged(with event: NSEvent) {
++ guard actionsEnabled else { return }
+ 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]) }
++ override func accessibilityChildren() -> [Any]? { [selectButton, closeButton] }
++ @objc private func selectSwarm() { if actionsEnabled { emit?("select", ["id": swarmId]) } }
++ @objc private func closeSwarm() { if actionsEnabled { emit?("close", ["id": swarmId]) } }
++ @objc private func renameSwarm() { if actionsEnabled { emit?("rename", ["id": swarmId]) } }
++}
++
++/// Selection and closing are sibling accessibility buttons, so VoiceOver and
++/// UI automation can reach the close action without treating the tab as a leaf.
++private final class SwarmSelectButton: NSButton {
++ weak var owner: SwarmTabButton?
++ override func mouseDown(with event: NSEvent) {
++ guard isEnabled else { return }
++ owner?.mouseDown(with: event)
++ }
++ override func mouseDragged(with event: NSEvent) {
++ guard isEnabled else { return }
++ owner?.mouseDragged(with: event)
++ }
+}
diff --cc desktop/test/about_section_test.dart
index f5b383969,f5b383969..d9663695e
--- a/desktop/test/about_section_test.dart
+++ b/desktop/test/about_section_test.dart
@@@ -29,11 -29,11 +29,15 @@@ void main()
buildSignature: '',
);
-- Future<AppNotifier> pumpAbout(WidgetTester tester) async {
++ Future<AppNotifier> pumpAbout(
++ WidgetTester tester, {
++ bool updatesEnabled = true,
++ }) async {
final notifier = AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
++ desktopUpdater: updatesEnabled ? DesktopUpdater(enabled: true) : null,
);
addTearDown(notifier.dispose);
tester.view.physicalSize = const Size(900 * 2, 700 * 2);
@@@ -64,12 -64,12 +68,32 @@@
size: 48600000,
);
++ testWidgets('the preview identifies itself and explains disabled updates', (
++ tester,
++ ) async {
++ final notifier = await pumpAbout(tester, updatesEnabled: false);
++ expect(find.text('Harness V2'), findsOneWidget);
++ expect(find.text('Preview · updates disabled'), findsOneWidget);
++ expect(
++ find.text(
++ 'Automatic and manual updates are disabled for this V2 preview.',
++ ),
++ findsOneWidget,
++ );
++ expect(
++ find.byKey(const Key('settings-check-updates-button')),
++ findsNothing,
++ );
++ notifier.availableUpdate = update;
++ expect(await notifier.installAvailableUpdate(), isFalse);
++ });
++
testWidgets('names the app, its version, and says nothing is waiting', (
tester,
) async {
await pumpAbout(tester);
-- expect(find.text('Harness Desktop'), findsOneWidget);
++ expect(find.text('Harness V2'), findsOneWidget);
expect(find.text('1.0.0'), findsOneWidget);
expect(find.text('Up to date'), findsOneWidget);
// Secondary actions, never a filled one — the pane is read, not operated.
diff --cc desktop/test/analytics_test.dart
index 4fcdef1ad,4fcdef1ad..2e4bde54c
--- a/desktop/test/analytics_test.dart
+++ b/desktop/test/analytics_test.dart
@@@ -104,7 -104,7 +104,7 @@@ void main()
expect(params['engine'], 'claude');
expect(params['bypass_permission'], true);
// Without this every stream in the shared project looks like one app.
-- expect(params['category'], 'harness-desktop');
++ expect(params['category'], 'harness-desktop-v2');
});
test('params drop nothing meaningful and carry nothing unbounded', () {
@@@ -351,7 -351,7 +351,7 @@@
// The payload, not the params: the gap between what the call site passed
// and what actually left is the bug this screen is opened to find.
expect(entry.payload, contains('"event_name": "agent_created"'));
-- expect(entry.payload, contains('harness-desktop'));
++ expect(entry.payload, contains('harness-desktop-v2'));
});
test('a retry shows as one row with two attempts, not two rows', () async {
diff --cc desktop/test/boot_flow_widget_test.dart
index 4ddcf9340,4ddcf9340..eba164fed
--- a/desktop/test/boot_flow_widget_test.dart
+++ b/desktop/test/boot_flow_widget_test.dart
@@@ -16,7 -16,7 +16,6 @@@ import 'package:harness/update/manual_u
import 'package:harness/widgets/update_notice.dart';
import 'package:harness/widgets/bootstrapping_screen.dart';
import 'package:flutter/material.dart';
--import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:package_info_plus/package_info_plus.dart';
@@@ -29,6 -29,6 +28,7 @@@ AppNotifier makeNotifier(AppStatus stat
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
++ cliLogin: _FakeCliLogin(),
);
app.status = status;
app.currentUser = const CurrentUserProfile(
@@@ -45,6 -45,6 +45,9 @@@ class _FakeCliLogin extends CliLogin
final bool loggedIn;
_FakeCliLogin({this.loggedIn = false});
++ @override
++ Future<void> logout() async {}
++
@override
Future<CliAuthStatus> checkStatus() async =>
CliAuthStatus(loggedIn: loggedIn);
@@@ -760,7 -760,7 +763,7 @@@ void main()
});
testWidgets(
-- 'authenticated with no machines shows terminal rail + empty terminal',
++ 'authenticated with no machines opens Swarm welcome and linking',
(tester) async {
final app = makeNotifier(AppStatus.authenticated);
await tester.pumpWidget(
@@@ -770,44 -770,44 +773,21 @@@
),
);
await tester.pumpAndSettle();
--
-- expect(
-- find.text('Select an agent, or drag one in from the left.'),
-- findsOneWidget,
-- );
-- expect(find.text('[email protected]'), findsOneWidget);
-- expect(find.byKey(const Key('account-menu-button')), findsOneWidget);
-- expect(find.byIcon(LucideIcons.logOut300), findsNothing);
-- // The rail is present. Not asserted on the filter field, which lives
-- // behind the rail's search toggle, nor on the "Machines" heading it used
-- // to check — a machine is a caption over its own agents now, so a caption
-- // over the captions would be two headings deep. This case is "no
-- // machines", and the rail's own answer to that is the thing to look for.
-- expect(find.text('no remote machines'), findsOneWidget);
--
-- await tester.tap(find.byKey(const Key('account-menu-button')));
++ expect(find.text('Start a swarm'), findsOneWidget);
++ expect(find.text('New agent'), findsOneWidget);
++ expect(find.text('Add project'), findsOneWidget);
++ await tester.tap(find.text('Link machine'));
await tester.pumpAndSettle();
--
-- expect(find.text('Diego'), findsOneWidget);
-- expect(find.text('Sign out'), findsOneWidget);
-- expect(find.byIcon(LucideIcons.logOut300), findsOneWidget);
-- expect(find.text('Remote into another machine…'), findsOneWidget);
--
-- // The running version is no longer a row in this menu: it moved to
-- // Settings ▸ About when Settings became a screen, and
-- // settings_screen_test is where it is asserted now. What this menu still
-- // owes is the order — what you can add, then the way out.
-- final linkY = tester
-- .getTopLeft(find.byKey(const Key('link-a-machine-menu-item')))
-- .dy;
-- final signOutY = tester
-- .getTopLeft(find.byKey(const Key('sign-out-menu-item')))
-- .dy;
-- expect(linkY, lessThan(signOutY));
++ expect(find.text('harness login\nharness start'), findsOneWidget);
++ await tester.tap(find.text('Done'));
++ await tester.pumpAndSettle();
++ expect(app.panes, isEmpty);
++ await tester.pumpWidget(const SizedBox());
++ app.dispose();
},
);
-- testWidgets('Settings sits directly above Sign out in the account menu', (
++ testWidgets('Settings exposes the signed-in account and sign-out', (
tester,
) async {
final app = makeNotifier(AppStatus.authenticated);
@@@ -818,23 -818,23 +798,20 @@@
),
);
await tester.pumpAndSettle();
--
-- await tester.tap(find.byKey(const Key('account-menu-button')));
++ await tester.tap(find.byTooltip('Settings'));
await tester.pumpAndSettle();
--
-- expect(find.text('Settings'), findsOneWidget);
--
-- final linkY = tester
-- .getTopLeft(find.byKey(const Key('link-a-machine-menu-item')))
-- .dy;
-- final settingsY = tester
-- .getTopLeft(find.byKey(const Key('settings-menu-item')))
-- .dy;
-- final signOutY = tester
-- .getTopLeft(find.byKey(const Key('sign-out-menu-item')))
-- .dy;
-- expect(linkY, lessThan(settingsY));
-- expect(settingsY, lessThan(signOutY));
++ await tester.tap(find.text('Account'));
++ await tester.pumpAndSettle();
++ expect(find.text('Diego'), findsOneWidget);
++ expect(find.text('[email protected]'), findsOneWidget);
++ await tester.tap(find.byKey(const Key('settings-sign-out-button')));
++ // The login relay diagram keeps animating after sign-out.
++ await tester.pump();
++ await tester.pump(const Duration(milliseconds: 400));
++ expect(app.status, AppStatus.unauthenticated);
++ expect(find.text('Account'), findsNothing);
++ await tester.pumpWidget(const SizedBox());
++ app.dispose();
});
testWidgets('available update is shown above the login screen', (
@@@ -895,53 -895,53 +872,57 @@@
app.dispose();
});
-- testWidgets('offline selected agent shows the Harness join guide', (
-- tester,
-- ) async {
-- final app = makeNotifier(AppStatus.authenticated);
-- const machine = Machine(
-- machineId: 'offline-machine',
-- apiKey: '',
-- authMode: MachineAuthMode.remote,
-- name: 'offline-mac',
-- status: 'offline',
-- );
-- final state = MachineState(machine)
-- ..localOnly = true
-- ..nodeOnline = false
-- ..activeAgentId = 'offline-agent'
-- ..pendingOfflineAgentId = 'offline-agent'
-- ..agentLoadStatus = AgentLoadStatus.loaded
-- ..agents = [
-- Agent.fromJson({
-- 'id': 'offline-agent',
-- 'name': 'claude-session',
-- 'engine': 'claude',
-- 'terminal': {
-- 'runtimes': [
-- {'backend': 'tmux', 'paneId': '%1'},
-- ],
-- },
-- }),
-- ];
-- app.machines = [machine];
-- app.machineStates[machine.machineId] = state;
-- app.expandedMachines.add(machine.machineId);
-- app.selectedMachineId = machine.machineId;
-- await app.selectAgent(machine.machineId, 'offline-agent');
++ testWidgets(
++ 'offline selected agent retains its Swarm view with an offline message',
++ (tester) async {
++ final app = makeNotifier(AppStatus.authenticated);
++ const machine = Machine(
++ machineId: 'offline-machine',
++ apiKey: '',
++ authMode: MachineAuthMode.remote,
++ name: 'offline-mac',
++ status: 'offline',
++ );
++ final state = MachineState(machine)
++ ..localOnly = true
++ ..nodeOnline = false
++ ..activeAgentId = 'offline-agent'
++ ..pendingOfflineAgentId = 'offline-agent'
++ ..agentLoadStatus = AgentLoadStatus.loaded
++ ..agents = [
++ Agent.fromJson({
++ 'id': 'offline-agent',
++ 'name': 'claude-session',
++ 'engine': 'claude',
++ 'terminal': {
++ 'runtimes': [
++ {'backend': 'tmux', 'paneId': '%1'},
++ ],
++ },
++ }),
++ ];
++ app.machines = [machine];
++ app.machineStates[machine.machineId] = state;
++ app.expandedMachines.add(machine.machineId);
++ app.selectedMachineId = machine.machineId;
++ await app.selectAgent(machine.machineId, 'offline-agent');
-- await tester.pumpWidget(
-- ProviderScope(
-- overrides: [appStateProvider.overrideWithValue(app)],
-- child: const DesktopApp(),
-- ),
-- );
-- await tester.pump();
++ await tester.pumpWidget(
++ ProviderScope(
++ overrides: [appStateProvider.overrideWithValue(app)],
++ child: const DesktopApp(),
++ ),
++ );
++ await tester.pump();
-- expect(find.text('Harness is offline'), findsOneWidget);
-- expect(find.text('harness start'), findsOneWidget);
-- app.dispose();
-- });
++ expect(
++ find.text('Harness is not running on this computer.'),
++ findsOneWidget,
++ );
++ expect(app.panes.single.agentId, 'offline-agent');
++ app.dispose();
++ },
++ );
testWidgets('unlinked remote with a pending agent shows the link form', (
tester,
@@@ -1043,7 -1043,7 +1024,7 @@@
await tester.pump();
expect(find.text('Link this machine'), findsNothing);
-- await tester.tap(find.byKey(const ValueKey('link-required')));
++ await tester.tap(find.text('link-mac'));
// Same popup-transition reasoning as above.
await tester.pumpAndSettle();
@@@ -1108,6 -1108,6 +1089,8 @@@
app.panes.add(otherPane);
app.focusedPaneId = otherPane.id;
app.selectedMachineId = otherMachine.machineId;
++ final originalSwarm = app.activeSwarm;
++ app.newSwarm();
await tester.pumpWidget(
ProviderScope(
@@@ -1118,13 -1118,13 +1101,15 @@@
await tester.pump();
expect(find.text('Link this machine'), findsNothing);
-- await tester.tap(find.byKey(const ValueKey('link-required')));
++ await tester.tap(find.text('link-mac'));
await tester.pumpAndSettle();
expect(find.text('Link this machine'), findsOneWidget);
// No second pane was opened for the popup — just the one terminal pane that was
// already there.
-- expect(app.panes, hasLength(1));
++ expect(app.allPanes, hasLength(1));
++ expect(originalSwarm.panes.single, same(otherPane));
++ expect(app.panes, isEmpty);
expect(
find.text('link-mac is not linked to this computer yet.'),
findsNothing,
diff --cc desktop/test/crash_log_test.dart
index 50dd8794c,746c49e6e..74b7b6f72
--- a/desktop/test/crash_log_test.dart
+++ b/desktop/test/crash_log_test.dart
@@@ -6,10 -6,10 +6,15 @@@ import 'package:harness/core/crash_log.
void main() {
test('an error reaches the log with its stack', () {
- final directory = Directory.systemTemp.createTempSync('harness-v2-crash-test-');
- final file = File(
- '${Platform.environment['HOME']}/.harness/desktop-app/errors.log',
++ final directory = Directory.systemTemp.createTempSync(
++ 'harness-v2-crash-test-',
+ );
- if (file.existsSync()) file.deleteSync();
+ final file = File('${directory.path}/errors.log');
+ CrashLog.testFile = file;
- addTearDown(() { CrashLog.testFile = null; directory.deleteSync(recursive: true); });
++ addTearDown(() {
++ CrashLog.testFile = null;
++ directory.deleteSync(recursive: true);
++ });
CrashLog.record(
TypeError(),
diff --cc desktop/test/daemon_readiness_test.dart
index 74bea3422,74bea3422..15bf92485
--- a/desktop/test/daemon_readiness_test.dart
+++ b/desktop/test/daemon_readiness_test.dart
@@@ -6,6 -6,6 +6,7 @@@ import 'package:harness/auth/cli_login.
import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
++import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/ws/local_cli_discovery.dart';
/// A daemon that answers whatever the test says, with the supervisor's callbacks captured so the
@@@ -17,6 -17,6 +18,7 @@@ class _ScriptedDiscovery extends LocalC
int ensureCalls = 0;
int superviseCalls = 0;
void Function(LocalCliEndpoint endpoint)? onReady;
++ void Function(LocalCliEndpoint endpoint)? onSnapshot;
@override
Future<LocalCliProbe> ensureRunning({
@@@ -38,9 -38,9 +40,11 @@@
Future<bool> Function()? stillSignedIn,
void Function()? onSignedOut,
void Function(LocalCliEndpoint endpoint)? onReady,
++ void Function(LocalCliEndpoint endpoint)? onSnapshot,
}) {
superviseCalls++;
this.onReady = onReady;
++ this.onSnapshot = onSnapshot;
return Timer(const Duration(days: 1), () {});
}
}
@@@ -84,6 -84,6 +88,82 @@@ final _endpoint = LocalCliEndpoint
);
void main() {
++ test('local folder snapshots refresh projects without leaking to peers or changing membership', () async {
++ final discovery = _ScriptedDiscovery([LocalCliProbe.ready(_endpoint)]);
++ final notifier = _Notifier(discovery);
++ addTearDown(notifier.dispose);
++ const oldAgent = Agent(id: 'shared-id', name: 'Existing agent');
++ const wireProject = AgentProject(
++ name: 'Reported repository',
++ cwd: '/wire',
++ remote: 'host/org/repo',
++ );
++ final local =
++ MachineState(
++ const Machine(
++ machineId: 'local',
++ name: 'Local',
++ authMode: MachineAuthMode.remote,
++ ),
++ )
++ ..localEndpoint = _endpoint
++ ..agents = [
++ oldAgent,
++ const Agent(id: 'native', name: 'New daemon', project: wireProject),
++ ];
++ final peer = MachineState(
++ const Machine(
++ machineId: 'peer',
++ name: 'Peer',
++ authMode: MachineAuthMode.remote,
++ ),
++ )..agents = [oldAgent];
++ notifier.machineStates.addAll({'local': local, 'peer': peer});
++ await notifier.ensureCliDaemonReady();
++ final swarm = notifier.activeSwarm;
++ var notifications = 0;
++ notifier.addListener(() => notifications++);
++ LocalCliEndpoint snapshot(String computerId, String folder) =>
++ LocalCliEndpoint(
++ computerId: computerId,
++ wsUri: _endpoint.wsUri,
++ protocolVersion: 1,
++ terminalProtocolVersion: 3,
++ agentProjects: {
++ 'shared-id': AgentProject(name: folder, cwd: '/work/$folder'),
++ 'native': const AgentProject(name: 'Fallback', cwd: '/fallback'),
++ },
++ );
++ final current = snapshot(_endpoint.computerId, 'Current project');
++ discovery.onSnapshot!(current);
++ expect(local.projectOf(oldAgent)!.name, 'Current project');
++ expect(peer.projectOf(oldAgent), isNull);
++ expect(local.projectOf(local.agents.last), wireProject);
++ expect(swarmAgents(notifier, 'Current project').map((a) => a.machineId), [
++ 'local',
++ ]);
++ expect(
++ swarmProjects(notifier, const [
++ SavedSwarmProject(
++ machineId: 'local',
++ path: '/work/Current project',
++ name: 'Saved folder',
++ ),
++ ]),
++ hasLength(2),
++ );
++ discovery.onSnapshot!(current);
++ discovery.onSnapshot!(snapshot('another-computer', 'Wrong project'));
++ expect(notifications, 1);
++ discovery.onSnapshot!(snapshot(_endpoint.computerId, 'Moved project'));
++ expect(local.projectOf(oldAgent)!.name, 'Moved project');
++ expect(notifications, 2);
++ expect(notifier.activeSwarm, same(swarm));
++ expect(notifier.swarms, hasLength(1));
++ expect(notifier.panes, isEmpty);
++ expect(notifier.refreshes, 0);
++ });
++
test('a daemon that answers but is still connecting is reported as such, and supervised', () async {
final discovery = _ScriptedDiscovery([
const LocalCliProbe.notReady(
diff --cc desktop/test/desktop_updater_test.dart
index 92c003101,92c003101..4d3da20a3
--- a/desktop/test/desktop_updater_test.dart
+++ b/desktop/test/desktop_updater_test.dart
@@@ -138,6 -138,6 +138,7 @@@ void main()
() async {
final url = await serveMetadataAndZip(manifestVersion: newVersion);
final updater = DesktopUpdater(
++ enabled: true,
dio: Dio(),
isLinux: false,
metadataUrl: url,
@@@ -155,6 -155,6 +156,7 @@@
final url = await serveMetadataAndZip(manifestVersion: newVersion);
// No releaseMode override — defaults to kReleaseMode, which is false under `flutter test`.
final updater = DesktopUpdater(
++ enabled: true,
dio: Dio(),
isLinux: false,
metadataUrl: url,
@@@ -162,6 -162,6 +164,7 @@@
expect(await updater.checkOnce(currentVersion: '1.0.0'), isNull);
final explicitlyOff = DesktopUpdater(
++ enabled: true,
dio: Dio(),
isLinux: false,
metadataUrl: url,
@@@ -170,9 -170,9 +173,36 @@@
expect(await explicitlyOff.checkOnce(currentVersion: '1.0.0'), isNull);
});
++ test(
++ 'V2 disables checks, downloads and applying even in release mode',
++ () async {
++ final updater = DesktopUpdater(releaseMode: true);
++ const info = UpdateInfo(
++ version: '9.9.9',
++ url: 'https://fixture.invalid/update.zip',
++ sha256: 'unused',
++ size: 1,
++ );
++ expect(await updater.checkOnce(currentVersion: '1.0.0'), isNull);
++ expect(await updater.downloadAndStage(info), isNull);
++ expect(
++ await updater.applyStaged(
++ const StagedUpdate(
++ version: '9.9.9',
++ bundlePath: '/nonexistent/fixture.app',
++ stagingDirPath: '/nonexistent',
++ ),
++ selfPid: 1,
++ ),
++ isFalse,
++ );
++ },
++ );
++
test('checkOnce returns null when the running version is already current or newer', () async {
final url = await serveMetadataAndZip(manifestVersion: '1.0.0');
final updater = DesktopUpdater(
++ enabled: true,
dio: Dio(),
isLinux: false,
metadataUrl: url,
@@@ -186,6 -186,6 +216,7 @@@
'checkOnce returns null (not an error) when the manifest is unreachable',
() async {
final updater = DesktopUpdater(
++ enabled: true,
dio: Dio(),
isLinux: false,
metadataUrl: 'http://127.0.0.1:1/metadata.json', // nothing listens here
@@@ -197,6 -197,6 +228,7 @@@
test('checkOnce also treats unavailable package metadata as no update', () async {
final updater = DesktopUpdater(
++ enabled: true,
dio: Dio(),
isLinux: false,
metadataUrl: 'http://127.0.0.1:1/metadata.json',
@@@ -223,6 -223,6 +255,7 @@@
final noUpdates = <UpdateInfo>[];
final t1 =
DesktopUpdater(
++ enabled: true,
dio: Dio(),
isLinux: false,
metadataUrl: urlUpToDate,
@@@ -242,6 -242,6 +275,7 @@@
final found = <UpdateInfo>[];
final t2 =
DesktopUpdater(
++ enabled: true,
dio: Dio(),
isLinux: false,
metadataUrl: urlNewer,
@@@ -262,7 -262,7 +296,7 @@@
'downloadAndStage verifies sha256 before trusting the download',
() async {
await serveMetadataAndZip(manifestVersion: newVersion);
-- final updater = DesktopUpdater(dio: Dio(), isLinux: false);
++ final updater = DesktopUpdater(enabled: true, dio: Dio(), isLinux: false);
final badInfo = UpdateInfo(
version: newVersion,
url: 'http://127.0.0.1:${server!.port}/Harness-macos.zip',
@@@ -276,7 -276,7 +310,7 @@@
test('downloadAndStage unpacks and confirms the staged bundle really carries the advertised version', () async {
await serveMetadataAndZip(manifestVersion: newVersion);
-- final updater = DesktopUpdater(dio: Dio(), isLinux: false);
++ final updater = DesktopUpdater(enabled: true, dio: Dio(), isLinux: false);
final info = UpdateInfo(
version: newVersion,
url: 'http://127.0.0.1:${server!.port}/Harness-macos.zip',
@@@ -292,7 -292,7 +326,7 @@@
test('downloadAndStage rejects a bundle whose Info.plist does not match the advertised version', () async {
await serveMetadataAndZip(manifestVersion: newVersion);
-- final updater = DesktopUpdater(dio: Dio(), isLinux: false);
++ final updater = DesktopUpdater(enabled: true, dio: Dio(), isLinux: false);
// Real zip on disk is stamped $newVersion — advertise a different one.
final mismatched = UpdateInfo(
version: '1.2.3',
@@@ -307,6 -307,6 +341,7 @@@
test('applyStaged spawns a detached command and never launches a real process', () async {
final calls = <String>[];
final updater = DesktopUpdater(
++ enabled: true,
// The macOS relaunch, asked for by name rather than inherited from the
// host — the Linux one is the group at the bottom of this file, and both
// deserve to run wherever the suite does.
@@@ -337,6 -337,6 +372,7 @@@
() async {
var called = false;
final updater = DesktopUpdater(
++ enabled: true,
// Same as above: the macOS "not inside a .app" branch. On Linux every
// executable has a parent directory, so the host's own answer would
// never be the null this is about.
@@@ -426,6 -426,6 +462,7 @@@
Map<String, String> versions,
) async {
final updater = DesktopUpdater(
++ enabled: true,
dio: Dio(),
metadataUrl: await serveMacManifest(versions),
releaseMode: true,
@@@ -526,6 -526,6 +563,7 @@@
manifestVersion: newVersion,
);
final updater = DesktopUpdater(
++ enabled: true,
dio: Dio(),
metadataUrl: url,
releaseMode: true,
@@@ -544,6 -544,6 +582,7 @@@
architecture: 'arm64',
);
final updater = DesktopUpdater(
++ enabled: true,
dio: Dio(),
metadataUrl: url,
releaseMode: true,
@@@ -561,6 -561,6 +600,7 @@@
() async {
await serveLinuxMetadataAndAppImage(manifestVersion: newVersion);
final updater = DesktopUpdater(
++ enabled: true,
dio: Dio(),
isLinux: true,
architecture: 'x64',
@@@ -587,6 -587,6 +627,7 @@@
() async {
await serveLinuxMetadataAndAppImage(manifestVersion: newVersion);
final updater = DesktopUpdater(
++ enabled: true,
dio: Dio(),
isLinux: true,
architecture: 'x64',
@@@ -605,6 -605,6 +646,7 @@@
test('applyStaged on Linux execs the swapped AppImage file directly instead of `open -n`', () async {
final calls = <String>[];
final updater = DesktopUpdater(
++ enabled: true,
isLinux: true,
architecture: 'x64',
launchDetached: (command) async => calls.add(command),
diff --cc desktop/test/dial_desk_test.dart
index c44cf0566,a30480ea8..2ff239939
--- a/desktop/test/dial_desk_test.dart
+++ b/desktop/test/dial_desk_test.dart
@@@ -97,7 -97,7 +97,7 @@@ void main()
final app = await _withTiles(['a1', 'a2']);
await app.selectAgentFromDial('m1', 'a3');
-- expect(app.panes.length, 2);
++ expect(_desk(app), ['a1', 'a2', 'a3']);
expect(app.focusedPane?.agentId, 'a3');
app.dispose();
},
@@@ -126,34 -126,34 +126,25 @@@
app.dispose();
});
-- test('at the ceiling it reuses the LAST tile rather than refusing', () async {
-- // Refusing would make the notification a liar: it says there is something to
-- // see and then does nothing when pressed. The last tile is already the place
-- // the desk treats as where things arrive — it is what the dial's own right
-- // edge replaces.
-- final app = _notifier();
-- _machine(app, 'm1', [
-- for (var i = 0; i < AppNotifier.maxPanes + 1; i++) 'a$i',
-- ]);
-- for (var i = 0; i < AppNotifier.maxPanes; i++) {
-- await app.assignAgentToPane(null, 'm1', 'a$i');
-- }
-- expect(app.canAddPane, isFalse);
-- final untouched = [
-- for (final p in app.panes.take(app.panes.length - 1)) p.agentId,
-- ];
--
-- await app.openAgentFromDial('m1', 'a${AppNotifier.maxPanes}');
--
-- expect(app.panes.length, AppNotifier.maxPanes, reason: 'the grid holds');
-- expect(app.panes.last.agentId, 'a${AppNotifier.maxPanes}');
-- expect(
-- [for (final p in app.panes.take(app.panes.length - 1)) p.agentId],
-- untouched,
-- reason: 'every other tile is where it was',
-- );
-- app.dispose();
-- });
++ test(
++ 'at capacity a notification reports the limit without evicting a view',
++ () async {
++ final app = _notifier();
++ _machine(app, 'm1', [
++ for (var i = 0; i <= AppNotifier.maxPanes; i++) 'a$i',
++ ]);
++ for (var i = 0; i < AppNotifier.maxPanes; i++) {
++ await app.assignAgentToPane(null, 'm1', 'a$i');
++ }
++ final before = List.of(app.panes);
++ final focus = app.focusedPaneId;
++ await app.openAgentFromDial('m1', 'a${AppNotifier.maxPanes}');
++ expect(app.panes, before);
++ expect(app.focusedPaneId, focus);
++ expect(app.lastError, contains('Open another swarm'));
++ app.dispose();
++ },
++ );
test('a notification for a tile already open only focuses it', () async {
final app = await _withTiles(['a1', 'a2', 'a3']);
@@@ -207,31 -207,31 +198,29 @@@
app.dispose();
});
-- test(
- 'dial_open and dial_focus retain the other agent views',
- 'a dial_open frame opens a tile, where dial_focus would replace one',
-- () 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.
-- final app = await _withTiles(['a1', 'a2']);
-- await app.handleEventForTest('m1', {
-- 'type': 'dial_open',
-- 'payload': {'machineId': 'm1', 'agentId': 'a4'},
-- });
-- expect(_desk(app), ['a1', 'a2', 'a4']);
--
-- app.focusPane(app.panes.last.id);
-- await dialFocus(app, 'a5');
-- expect(_desk(app), [
-- 'a1',
-- 'a2',
-- 'a5',
- ], reason: 'neither event removes a view');
- ], reason: 'focus replaces, open adds');
-- app.dispose();
-- },
-- );
++ test('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.
++ final app = await _withTiles(['a1', 'a2']);
++ await app.handleEventForTest('m1', {
++ 'type': 'dial_open',
++ 'payload': {'machineId': 'm1', 'agentId': 'a4'},
++ });
++ expect(_desk(app), ['a1', 'a2', 'a4']);
++
++ app.focusPane(app.panes.last.id);
++ await dialFocus(app, 'a5');
++ expect(_desk(app), [
++ 'a1',
++ 'a2',
++ 'a4',
++ 'a5',
++ ], 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);
diff --cc desktop/test/local_cli_discovery_test.dart
index 4c75f8fb0,4c75f8fb0..59824a4be
--- a/desktop/test/local_cli_discovery_test.dart
+++ b/desktop/test/local_cli_discovery_test.dart
@@@ -1,3 -1,3 +1,4 @@@
++import 'dart:async';
import 'dart:convert';
import 'dart:io';
@@@ -207,6 -207,6 +208,89 @@@ void main()
spawnCommand: spawnCommand,
);
++ test(
++ 'reads real working folders from older local status snapshots',
++ () async {
++ const computerId = '0123456789abcdef0123456789abcdef';
++ final identityFile = File('${scratch.path}/computer-id')
++ ..writeAsStringSync(computerId);
++ server = await serveStatus(
++ await freePort(),
++ () => {
++ ...readyStatus(computerId),
++ 'sessions': [
++ {'id': 'first', 'cwd': '~/work/project/'},
++ {'id': 'same', 'cwd': '${scratch.path}/work/project'},
++ {'id': 'missing'},
++ {'id': 'relative', 'cwd': 'work/project'},
++ {'id': 'other-user', 'cwd': '~other/work'},
++ {'id': 'control', 'cwd': '/work/\u0000bad'},
++ {'id': '', 'cwd': '/work/ignored'},
++ ],
++ },
++ );
++ final endpoint = await LocalCliDiscovery(
++ config: AppConfig(
++ apiBaseUrl: 'https://fixture.invalid',
++ localCliBaseUrl: 'http://127.0.0.1:${server!.port}',
++ ),
++ identity: LocalMachineIdentity(
++ computerIdFile: identityFile,
++ environment: {'HOME': scratch.path},
++ ),
++ ).discover();
++ final projects = endpoint!.agentProjects;
++ expect(projects.keys, ['first', 'same']);
++ expect(projects['first']!.cwd, '${scratch.path}/work/project');
++ expect(projects['first']!.name, 'project');
++ expect(projects['first'], projects['same']);
++ expect(projects['first']!.remote, isNull);
++ expect(projects['first']!.branch, isNull);
++ },
++ skip: Platform.isWindows,
++ );
++
++ test(
++ 'supervision publishes changing folders without reconnecting or spawning',
++ () async {
++ const computerId = '0123456789abcdef0123456789abcdef';
++ final identityFile = File('${scratch.path}/computer-id')
++ ..writeAsStringSync(computerId);
++ var cwd = '${scratch.path}/before';
++ server = await serveStatus(
++ await freePort(),
++ () => {
++ ...readyStatus(computerId),
++ 'sessions': [
++ {'id': 'agent', 'cwd': cwd},
++ ],
++ },
++ );
++ var readyCount = 0;
++ final before = Completer<void>();
++ final after = Completer<void>();
++ final discovery = discoveryFor(
++ server!.port,
++ identityFile,
++ spawnCommand: () async => fail('A ready daemon must not be restarted'),
++ );
++ final timer = discovery.startSupervising(
++ checkInterval: const Duration(milliseconds: 20),
++ onReady: (_) => readyCount++,
++ onSnapshot: (endpoint) {
++ final name = endpoint.agentProjects['agent']?.name;
++ if (name == 'before' && !before.isCompleted) before.complete();
++ if (name == 'after' && !after.isCompleted) after.complete();
++ },
++ );
++ addTearDown(timer.cancel);
++ await before.future.timeout(const Duration(seconds: 3));
++ cwd = '${scratch.path}/after';
++ await after.future.timeout(const Duration(seconds: 3));
++ expect(readyCount, 1);
++ },
++ );
++
group('probe', () {
const computerId = '0123456789abcdef0123456789abcdef';
late File identityFile;
diff --cc desktop/test/new_agent_codex_profile_test.dart
index 42bd435f8,8612393f1..683850f76
--- a/desktop/test/new_agent_codex_profile_test.dart
+++ b/desktop/test/new_agent_codex_profile_test.dart
@@@ -179,9 -178,9 +179,10 @@@ void main()
'Link a profile folder…',
'/custom/work-login',
'Checking whether this computer supports Codex profiles…',
-- ])
++ ]) {
// ignore: avoid_print
-- print('PROBE $t -> ' + tester.widgetList(find.text(t)).length.toString());
++ print('PROBE $t -> ${tester.widgetList(find.text(t)).length}');
++ }
return n;
}
diff --cc desktop/test/pane_lattice_test.dart
index 01a1285ed,3e07548d1..b8acd7ce1
--- a/desktop/test/pane_lattice_test.dart
+++ b/desktop/test/pane_lattice_test.dart
@@@ -40,9 -40,9 +40,9 @@@ Future<void> _pump(WidgetTester tester
}
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);
++ expect(AppNotifier.maxPanes, greaterThan(PaneLayoutStore.maxPanes));
});
for (final n in [5, 6, 7, 8, 9]) {
diff --cc desktop/test/settings_section_test.dart
index e49229ed1,e49229ed1..5b5e6adf3
--- a/desktop/test/settings_section_test.dart
+++ b/desktop/test/settings_section_test.dart
@@@ -35,6 -35,6 +35,7 @@@ void main()
// there is nothing here for a shipped build to hide.
SettingsSection.usage,
SettingsSection.devices,
++ SettingsSection.account,
SettingsSection.shortcuts,
SettingsSection.about,
]);
diff --cc desktop/test/shortcuts_deck_test.dart
index e3021617a,e3021617a..c8d64981b
--- a/desktop/test/shortcuts_deck_test.dart
+++ b/desktop/test/shortcuts_deck_test.dart
@@@ -86,14 -86,14 +86,14 @@@ void main()
);
}
-- // ⇧⌘] is three caps, not one glyph run.
++ // ⌘] is two caps. Ctrl+Tab switches swarms.
final next = find.ancestor(
of: find.text('Next agent'),
matching: find.byType(Row),
);
expect(
find.descendant(of: next.first, matching: find.byType(KeyCap)),
-- findsNWidgets(3),
++ findsNWidgets(2),
);
// And the keys the app deliberately leaves alone are named too.
diff --cc desktop/test/shortcuts_test.dart
index eec83e0a8,eec83e0a8..3c7e057eb
--- a/desktop/test/shortcuts_test.dart
+++ b/desktop/test/shortcuts_test.dart
@@@ -271,7 -271,7 +271,7 @@@ void main()
);
});
-- test('the brackets mean exactly one thing', () {
++ test('brackets walk agents, and Shift walks swarms', () {
// They used to carry three verbs told apart only by modifiers: ⌘[ ] walked
// panes, ⇧⌘[ ] walked agents, ⌥⌘[ ] moved panes. Panes went to hjkl, so
// the brackets keep the one job a bracket is good at.
@@@ -283,6 -283,6 +283,8 @@@
expect(bracketed, {
ShortcutAction.previousAgent,
ShortcutAction.nextAgent,
++ ShortcutAction.previousSwarm,
++ ShortcutAction.nextSwarm,
});
});
@@@ -320,9 -320,9 +322,9 @@@
['⌘', '→'],
]);
-- final next = rows.firstWhere((row) => row.label == 'Next agent');
++ final next = rows.firstWhere((row) => row.label == 'Next swarm');
expect(next.chords, [
-- ['⌘', ']'],
++ ['⇧', '⌘', ']'],
['⌃', '⇥'],
]);
});
diff --cc desktop/test/swarm_async_test.dart
index 000000000,000000000..489feb6d9
new file mode 100644
--- /dev/null
+++ b/desktop/test/swarm_async_test.dart
@@@ -1,0 -1,0 +1,155 @@@
++import 'dart:async';
++
++import 'dart:convert';
++
++import 'package:flutter_test/flutter_test.dart';
++import 'package:harness/state/swarm_catalog.dart';
++import 'package:harness/ws/ws_conn.dart';
++
++import 'swarm_state_test.dart' show createApp, MemoryStore;
++
++class _PendingConnection extends WsConn {
++ _PendingConnection()
++ : super(
++ wsBaseUrl: 'ws://fixture.invalid',
++ autonomousEnv: 'test',
++ machineId: 'm',
++ accessTokenProvider: (_, _) async => '',
++ onAuthFailure: (_) {},
++ onEvent: (_) {},
++ onStatus: (_) {},
++ );
++ final reply = Completer<Map<String, dynamic>>();
++ final calls = <String>[];
++ @override
++ Future<Map<String, dynamic>> request(
++ String type, {
++ Map<String, dynamic> payload = const {},
++ Duration timeout = const Duration(seconds: 20),
++ }) {
++ calls.add(type);
++ return reply.future;
++ }
++
++ void complete() => reply.complete({
++ 'agent': {'id': 'created', 'name': 'Created', 'engine': 'claude'},
++ });
++}
++
++class _DelayedStore extends MemoryStore {
++ String? blockedKey;
++ final entered = Completer<void>();
++ final answer = Completer<String?>();
++ bool failWrites = false;
++ @override
++ Future<String?> read(String key) {
++ if (key != blockedKey) return super.read(key);
++ if (!entered.isCompleted) entered.complete();
++ return answer.future;
++ }
++
++ @override
++ Future<void> write(String key, String value) async {
++ if (failWrites) throw StateError('Fixture disk unavailable');
++ await super.write(key, value);
++ }
++}
++
++void main() {
++ for (final change in ['switch', 'close', 'dispose']) {
++ test(
++ 'an agent launch stays with its destination after $change during the RPC',
++ () async {
++ final connection = _PendingConnection();
++ final app = createApp(connectionForTest: (_) => connection);
++ final destination = app.activeSwarm;
++ final launch = app.createAgent('m', engine: 'claude', folder: '/work');
++ expect(connection.calls, ['agent_create']);
++ app.newSwarm();
++ if (change == 'close') await app.closeSwarm(destination.id);
++ if (change == 'dispose') app.dispose();
++ connection.complete();
++ expect(await launch, isNull);
++ expect(app.panes, isEmpty);
++ expect(
++ destination.panes.map((p) => p.agentId),
++ change == 'switch' ? ['created'] : isEmpty,
++ );
++ expect(connection.calls, isNot(contains('agent_delete')));
++ if (change != 'dispose') app.dispose();
++ },
++ );
++ }
++
++ for (final key in ['terminal_pane_presets', 'terminal_pane_layout']) {
++ for (final change in ['rename', 'dispose']) {
++ test(
++ 'legacy $key restore cannot overwrite a $change during the read',
++ () async {
++ final store = _DelayedStore()..blockedKey = key;
++ final app = createApp(store: store);
++ final restore = app.restorePaneLayoutForTest();
++ await store.entered.future;
++ if (change == 'rename') app.renameSwarm(app.activeSwarmId, 'Chosen');
++ if (change == 'dispose') app.dispose();
++ store.answer.complete(
++ key == 'terminal_pane_presets'
++ ? '{"2":"rows"}'
++ : jsonEncode([
++ {'machineId': 'm', 'agentId': 'a0'},
++ ]),
++ );
++ await restore;
++ expect(app.panes, isEmpty);
++ expect(app.panePresets, isEmpty);
++ if (change == 'rename') {
++ expect(app.activeSwarm.name, 'Chosen');
++ app.dispose();
++ }
++ },
++ );
++ }
++ }
++
++ test(
++ 'adding while saved projects load preserves old and concurrent additions',
++ () async {
++ final storage = _DelayedStore()..blockedKey = 'swarm_projects_v1';
++ final store = SwarmProjectStore(storage: storage);
++ final load = store.load();
++ final addA = store.add(
++ const SavedSwarmProject(machineId: 'm', path: '/a', name: 'A'),
++ );
++ final addB = store.add(
++ const SavedSwarmProject(machineId: 'm', path: '/b', name: 'B'),
++ );
++ storage.answer.complete(
++ '[{"machineId":"m","path":"/saved","name":"Saved"}]',
++ );
++ await load;
++ expect(await addA, isTrue);
++ expect(await addB, isTrue);
++ expect(store.projects.map((p) => p.path), ['/saved', '/a', '/b']);
++ final saved = jsonDecode(storage.values['swarm_projects_v1']!) as List;
++ expect(saved.map((p) => p['path']), ['/saved', '/a', '/b']);
++ store.dispose();
++ },
++ );
++
++ test(
++ 'a project write failure is visible and does not claim it was saved',
++ () async {
++ final storage = _DelayedStore()..failWrites = true;
++ final store = SwarmProjectStore(storage: storage);
++ const project = SavedSwarmProject(machineId: 'm', path: '/a', name: 'A');
++ expect(await store.add(project), isFalse);
++ expect(store.projects, isEmpty);
++ expect(store.error, contains('Could not save'));
++ storage.failWrites = false;
++ expect(await store.add(project), isTrue);
++ expect(store.projects.single, same(project));
++ expect(store.error, isNull);
++ store.dispose();
++ },
++ );
++}
diff --cc desktop/test/swarm_interactions_test.dart
index 000000000,000000000..12daef093
new file mode 100644
--- /dev/null
+++ b/desktop/test/swarm_interactions_test.dart
@@@ -1,0 -1,0 +1,358 @@@
++import 'dart:async';
++
++import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
++import 'package:flutter/material.dart';
++import 'package:flutter/services.dart';
++import 'package:flutter_test/flutter_test.dart';
++import 'package:harness/auth/auth_session.dart';
++import 'package:harness/core/codex_profiles.dart';
++import 'package:harness/core/config.dart';
++import 'package:harness/core/models.dart';
++import 'package:harness/screens/swarm_screen.dart';
++import 'package:harness/settings/settings_screen.dart';
++import 'package:harness/shared/widgets/app_select_field.dart';
++import 'package:harness/state/app_state.dart';
++import 'package:harness/state/swarm_catalog.dart';
++import 'package:harness/widgets/codex_profile_field.dart';
++import 'package:harness/widgets/new_agent_dialog.dart';
++import 'package:harness/widgets/swarm_dialogs.dart';
++import 'package:harness/widgets/terminal_composer.dart';
++
++import 'swarm_screen_test.dart' show mount, terminal;
++import 'swarm_state_test.dart' show createApp;
++
++class _ProfilesNotifier extends AppNotifier {
++ _ProfilesNotifier()
++ : super(
++ config: AppConfig.dev,
++ authSession: AuthSession(),
++ configStore: null,
++ );
++ final pending = <String, Completer<Map<String, dynamic>>>{};
++ @override
++ Future<void> probeEngines(String machineId, {bool force = false}) async {}
++ @override
++ Future<Map<String, dynamic>> listCodexProfiles(
++ String machineId, {
++ Set<String> observedPaths = const {},
++ }) => (pending[machineId] = Completer()).future;
++}
++
++class _PendingFolder extends FileSelectorPlatform {
++ final answer = Completer<String?>();
++ @override
++ Future<String?> getDirectoryPath({
++ String? initialDirectory,
++ String? confirmButtonText,
++ }) => answer.future;
++}
++
++Future<void> chord(
++ WidgetTester tester,
++ LogicalKeyboardKey key, {
++ bool shift = false,
++}) async {
++ await tester.sendKeyDownEvent(LogicalKeyboardKey.meta);
++ if (shift) await tester.sendKeyDownEvent(LogicalKeyboardKey.shift);
++ await tester.sendKeyEvent(key);
++ if (shift) await tester.sendKeyUpEvent(LogicalKeyboardKey.shift);
++ await tester.sendKeyUpEvent(LogicalKeyboardKey.meta);
++ await tester.pump();
++ await tester.pump(const Duration(milliseconds: 100));
++}
++
++void main() {
++ testWidgets(
++ 'the picker walks and scrolls by keyboard and keeps its agent through live refreshes',
++ (tester) async {
++ final app = createApp();
++ await mount(tester, app);
++ await chord(tester, LogicalKeyboardKey.keyP);
++ await tester.pump(const Duration(milliseconds: 200));
++ for (var i = 0; i < 12; i++) {
++ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
++ await tester.pump();
++ }
++ await tester.pump();
++ final selected = find.byWidgetPredicate(
++ (w) => w is ListTile && w.selected,
++ );
++ expect(
++ find.descendant(of: selected, matching: find.text('Agent 12')),
++ findsOneWidget,
++ );
++ final row = tester.getRect(find.text('Agent 12'));
++ final list = tester.getRect(find.byType(ListView));
++ expect(row.top, greaterThanOrEqualTo(list.top));
++ expect(row.bottom, lessThanOrEqualTo(list.bottom));
++ final machine = app.machineStates['m']!;
++ machine.agents = [
++ const Agent(id: 'new', name: 'Discovered'),
++ ...machine.agents,
++ ];
++ app.dismissError();
++ await tester.pump();
++ await tester.pump();
++ expect(
++ find.descendant(of: selected, matching: find.text('Agent 12')),
++ findsOneWidget,
++ );
++ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
++ await tester.pump(const Duration(milliseconds: 200));
++ expect(app.panes.single.agentId, 'a12');
++ await tester.pumpWidget(const SizedBox());
++ app.dispose();
++ },
++ );
++
++ testWidgets(
++ 'welcome search supports readline selection and ignores an empty Return',
++ (tester) async {
++ final app = createApp();
++ await mount(tester, app);
++ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
++ await tester.pump();
++ expect(app.panes, isEmpty);
++ await tester.enterText(find.byType(TextField), 'Agent 1');
++ await tester.pump();
++ await tester.sendKeyDownEvent(LogicalKeyboardKey.control);
++ await tester.sendKeyEvent(LogicalKeyboardKey.keyN);
++ await tester.sendKeyUpEvent(LogicalKeyboardKey.control);
++ await tester.pump();
++ final selected = find.byWidgetPredicate(
++ (w) => w is ListTile && w.selected,
++ );
++ expect(
++ find.descendant(of: selected, matching: find.text('Agent 10')),
++ findsOneWidget,
++ );
++ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
++ await tester.pump();
++ expect(app.panes.single.agentId, 'a10');
++ await tester.pumpWidget(const SizedBox());
++ app.dispose();
++ },
++ );
++
++ testWidgets(
++ 'close view and close swarm shortcuts keep shared sessions alive',
++ (tester) async {
++ final app = createApp();
++ app.machineStates['m']!.nodeOnline = true;
++ final session = terminal('a0', []);
++ app.adoptSessionForTest(session);
++ final original = app.activeSwarm;
++ app.newSwarm();
++ await app.addAgentToSwarm('m', 'a0');
++ await mount(tester, app);
++ await chord(tester, LogicalKeyboardKey.keyW, shift: true);
++ expect(app.swarms.length, 2);
++ expect(app.panes, isEmpty);
++ expect(original.panes.single.session, same(session));
++ await chord(tester, LogicalKeyboardKey.keyW);
++ expect(app.swarms.single, same(original));
++ expect(app.panes.single.session, same(session));
++ await tester.pumpWidget(const SizedBox());
++ app.dispose();
++ },
++ );
++
++ testWidgets('a remote compact pane exposes its message composer', (
++ tester,
++ ) async {
++ final app = createApp();
++ app.machineStates['m']!.nodeOnline = true;
++ app.adoptSessionForTest(terminal('a0', []));
++ await mount(tester, app);
++ expect(find.byType(TerminalComposer), findsNothing);
++ await tester.tap(find.byTooltip('Show message composer'));
++ await tester.pump();
++ expect(find.byType(TerminalComposer), findsOneWidget);
++ await tester.tap(find.byTooltip('Hide message composer'));
++ await tester.pump();
++ expect(find.byType(TerminalComposer), findsNothing);
++ await tester.pumpWidget(const SizedBox());
++ app.dispose();
++ });
++
++ testWidgets('native Swarm commands cannot mutate the view behind Settings', (
++ tester,
++ ) async {
++ const channel = MethodChannel('harness/swarm_tabs');
++ final updates = <Map>[];
++ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
++ call,
++ ) async {
++ if (call.method == 'update') updates.add(call.arguments as Map);
++ return null;
++ });
++ addTearDown(
++ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
++ channel,
++ null,
++ ),
++ );
++ Future<void> native(String method) {
++ final result = Completer<void>();
++ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
++ channel.name,
++ const StandardMethodCodec().encodeMethodCall(MethodCall(method)),
++ (_) => result.complete(),
++ );
++ return result.future;
++ }
++
++ final app = createApp();
++ final projects = SwarmProjectStore();
++ await tester.pumpWidget(
++ MaterialApp(
++ home: SwarmScreen(
++ notifier: app,
++ nativeTabs: true,
++ projectStore: projects,
++ ),
++ ),
++ );
++ await tester.pump();
++ final opening = native('settings');
++ await tester.pump();
++ await tester.pump(const Duration(milliseconds: 300));
++ expect(find.byType(SettingsScreen), findsOneWidget);
++ expect(updates.last['enabled'], isFalse);
++ await native('new');
++ await native('closeActive');
++ expect(app.swarms.single.id, 'swarm-1');
++ Navigator.of(tester.element(find.byType(SettingsScreen))).pop();
++ await tester.pump(const Duration(milliseconds: 300));
++ await opening;
++ expect(updates.last['enabled'], isTrue);
++ await tester.pumpWidget(const SizedBox());
++ projects.dispose();
++ app.dispose();
++ });
++
++ testWidgets(
++ 'late profile discovery cannot cross a machine switch with identical observed paths',
++ (tester) async {
++ final app = _ProfilesNotifier();
++ final selected = <LocalCodexProfile?>[];
++ Widget host(String id) => MaterialApp(
++ home: Scaffold(
++ body: CodexProfileField(
++ notifier: app,
++ machineId: id,
++ machineIsThisComputer: false,
++ value: null,
++ onChanged: selected.add,
++ ),
++ ),
++ );
++ await tester.pumpWidget(host('a'));
++ await tester.pump();
++ await tester.pumpWidget(host('b'));
++ await tester.pump();
++ app.pending['a']!.complete({
++ 'profiles': [
++ {'path': '/old', 'label': 'Old'},
++ ],
++ });
++ await tester.pump();
++ expect(selected, isEmpty);
++ app.pending['b']!.complete({
++ 'profiles': [
++ {'path': '/new', 'label': 'New'},
++ ],
++ });
++ await tester.pump();
++ expect(selected.single?.path, '/new');
++ await tester.pumpWidget(const SizedBox());
++ app.dispose();
++ },
++ );
++
++ testWidgets(
++ 'a folder picker result is discarded after switching away and back',
++ (tester) async {
++ final app = _ProfilesNotifier();
++ for (final id in ['a', 'b']) {
++ app.machineStates[id] = MachineState(
++ Machine(machineId: id, authMode: MachineAuthMode.remote),
++ )..localOnly = true;
++ }
++ final previous = FileSelectorPlatform.instance;
++ final folder = _PendingFolder();
++ FileSelectorPlatform.instance = folder;
++ addTearDown(() => FileSelectorPlatform.instance = previous);
++ await tester.pumpWidget(
++ MaterialApp(
++ home: Builder(
++ builder: (context) => TextButton(
++ onPressed: () =>
++ showNewAgentDialog(context, app, 'a', source: 'test'),
++ child: const Text('Open'),
++ ),
++ ),
++ ),
++ );
++ await tester.tap(find.text('Open'));
++ await tester.pump(const Duration(milliseconds: 300));
++ await tester.tap(find.text('Browse…'));
++ await tester.pump();
++ final field = find.byKey(const Key('new-agent-machine-field'));
++ tester.widget<AppSelectField<String>>(field).onChanged('b');
++ await tester.pump();
++ tester.widget<AppSelectField<String>>(field).onChanged('a');
++ await tester.pump();
++ folder.answer.complete('/old-machine-folder');
++ await tester.pump();
++ expect(find.textContaining('/old-machine-folder'), findsNothing);
++ expect(find.text('Browse…'), findsOneWidget);
++ await tester.pumpWidget(const SizedBox());
++ app.dispose();
++ },
++ );
++
++ testWidgets(
++ 'Add project discards an old folder after switching away and back',
++ (tester) async {
++ final app = createApp();
++ app.machineStates['m']!.localOnly = true;
++ app.machineStates['other'] = MachineState(
++ const Machine(machineId: 'other', authMode: MachineAuthMode.remote),
++ );
++ final previous = FileSelectorPlatform.instance;
++ final folder = _PendingFolder();
++ FileSelectorPlatform.instance = folder;
++ addTearDown(() => FileSelectorPlatform.instance = previous);
++ await tester.pumpWidget(
++ MaterialApp(
++ home: Builder(
++ builder: (context) => TextButton(
++ onPressed: () => showSwarmProjectDialog(context, app),
++ child: const Text('Open'),
++ ),
++ ),
++ ),
++ );
++ await tester.tap(find.text('Open'));
++ await tester.pump(const Duration(milliseconds: 200));
++ await tester.tap(find.text('Choose folder'));
++ await tester.pump();
++ final field = find.byType(AppSelectField<String>);
++ tester.widget<AppSelectField<String>>(field).onChanged('other');
++ await tester.pump();
++ tester.widget<AppSelectField<String>>(field).onChanged('m');
++ await tester.pump();
++ folder.answer.complete('/stale-folder');
++ await tester.pump();
++ expect(find.text('/stale-folder'), findsNothing);
++ expect(find.text('Choose folder'), findsOneWidget);
++ expect(
++ tester.widget<FilledButton>(find.byType(FilledButton)).onPressed,
++ isNull,
++ );
++ await tester.pumpWidget(const SizedBox());
++ app.dispose();
++ },
++ );
++}
diff --cc desktop/test/swarm_screen_test.dart
index df2def140,000000000..c1e8ba0a9
mode 100644,000000..100644
--- a/desktop/test/swarm_screen_test.dart
+++ b/desktop/test/swarm_screen_test.dart
@@@ -1,128 -1,0 +1,243 @@@
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
++import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/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:harness/ws/local_cli_discovery.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.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';
++
++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(
++ 'an older daemon working folder is searchable and seeds its real agents',
++ (tester) async {
++ final app = createApp();
++ app.machineStates['m']!.localEndpoint = LocalCliEndpoint(
++ computerId: 'local-computer',
++ wsUri: Uri.parse('ws://fixture.invalid'),
++ protocolVersion: 1,
++ terminalProtocolVersion: 3,
++ agentProjects: const {
++ 'a0': AgentProject(name: 'Existing project', cwd: '/work/existing'),
++ 'a1': AgentProject(name: 'Existing project', cwd: '/work/existing'),
++ },
++ );
++ await mount(tester, app);
++ expect(find.text('Existing project'), findsOneWidget);
++ await tester.enterText(find.byType(TextField), '/work/existing');
++ await tester.pump();
++ expect(find.text('Agent 0'), findsOneWidget);
++ expect(find.text('Agent 1'), findsOneWidget);
++ expect(find.text('Agent 2'), findsNothing);
++ await tester.enterText(find.byType(TextField), '');
++ await tester.pump();
++ await tester.tap(find.text('Existing project'));
++ await tester.pump(const Duration(milliseconds: 100));
++ expect(app.activeSwarm.name, 'Existing project');
++ expect(app.panes.map((p) => p.agentId), ['a0', 'a1']);
++ await tester.pumpWidget(const SizedBox());
++ app.dispose();
++ },
++ );
++
++ 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 ⌘P'));
++ 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(
++ '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();
- });
++ 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.widgetWithIcon(IconButton, 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.widgetWithIcon(IconButton, 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 --cc desktop/test/swarm_state_test.dart
index 48affab4f,000000000..7a9731bdb
mode 100644,000000..100644
--- a/desktop/test/swarm_state_test.dart
+++ b/desktop/test/swarm_state_test.dart
@@@ -1,167 -1,0 +1,270 @@@
- 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';
++import 'package:harness/ws/ws_conn.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); }
++ @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');
++
++AppNotifier createApp({
++ MemoryStore? store,
++ WsConn Function(String)? connectionForTest,
++}) {
++ final app = AppNotifier(
++ config: AppConfig.dev,
++ authSession: AuthSession(),
++ configStore: null,
++ connectionForTest: connectionForTest,
++ 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
++ 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)];
++ ..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(
++ '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(
++ '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(
++ '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.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.activeSwarm.previousPaneId, restored.panes.last.id);
+ 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();
++ 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');
++ 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();
- });
++ 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 --cc desktop/test/terminal_pane_test.dart
index 18ce4edd0,10e39dd45..903727ac6
--- a/desktop/test/terminal_pane_test.dart
+++ b/desktop/test/terminal_pane_test.dart
@@@ -80,7 -80,7 +80,11 @@@ void main()
await app.selectAgent('m1', 'a');
await app.selectAgent('m1', 'b');
- expect(app.panes.length, 2, reason: 'selecting adds a view without replacing the existing one');
- 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);
diff --cc desktop/test/usage_section_test.dart
index b23a4bc1a,b23a4bc1a..eeade57c9
--- a/desktop/test/usage_section_test.dart
+++ b/desktop/test/usage_section_test.dart
@@@ -568,10 -568,10 +568,7 @@@ void main()
await controller.load();
await pumpUsage(tester, controller);
-- expect(
-- find.text('Off — nothing on this machine is read.'),
-- findsNWidgets(LedgerProvider.values.length),
-- );
++ expect(find.text('Off'), findsNWidgets(LedgerProvider.values.length));
});
testWidgets('every provider keeps a row whether it is on or not', (
diff --cc desktop/windows/CMakeLists.txt
index 8847d3436,8847d3436..7a506b6df
--- a/desktop/windows/CMakeLists.txt
+++ b/desktop/windows/CMakeLists.txt
@@@ -4,7 -4,7 +4,7 @@@ project(harness LANGUAGES CXX
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
--set(BINARY_NAME "harness")
++set(BINARY_NAME "harness-v2")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
diff --cc desktop/windows/runner/Runner.rc
index e91e933be,e91e933be..0cbeaecec
--- a/desktop/windows/runner/Runner.rc
+++ b/desktop/windows/runner/Runner.rc
@@@ -90,12 -90,12 +90,12 @@@ BEGI
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "com.autonomous" "\0"
-- VALUE "FileDescription", "Harness" "\0"
++ VALUE "FileDescription", "Harness V2" "\0"
VALUE "FileVersion", VERSION_AS_STRING "\0"
-- VALUE "InternalName", "harness" "\0"
++ VALUE "InternalName", "harness-v2" "\0"
VALUE "LegalCopyright", "Copyright (C) 2026 com.autonomous. All rights reserved." "\0"
-- VALUE "OriginalFilename", "harness.exe" "\0"
-- VALUE "ProductName", "Harness" "\0"
++ VALUE "OriginalFilename", "harness-v2.exe" "\0"
++ VALUE "ProductName", "Harness V2" "\0"
VALUE "ProductVersion", VERSION_AS_STRING "\0"
END
END
diff --cc desktop/windows/runner/main.cpp
index 896c886b8,896c886b8..ee6d955e1
--- a/desktop/windows/runner/main.cpp
+++ b/desktop/windows/runner/main.cpp
@@@ -27,7 -27,7 +27,7 @@@ int APIENTRY wWinMain(_In_ HINSTANCE in
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
-- if (!window.Create(L"Harness", origin, size)) {
++ if (!window.Create(L"Harness V2", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
diff --cc docs/harness-v2-progress.md
index b17e24f5d,000000000..b547dc479
mode 100644,000000..100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@@ -1,206 -1,0 +1,205 @@@
+# Harness App V2 — development handoff
+
- Updated 2026-09-12. This is a working preview, not a release or a finished implementation.
++Updated 2026-09-12 after the implementation continuation and live-data review. This is a working preview, not a release.
+
+## 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.
++- The user resumed implementation here, requested real machines/projects after seeing the temporary QA app, and then asked Codex to keep working while away for a couple of hours. The original active goal is a polished, very fast, keyboard-first native app with each tab representing a Swarm.
++- The QA app was closed. Review uses the normal `lib/main.dart` entry point, the existing Harness account, and saved V2 Swarms. Keep sample fixtures out of the foreground review app.
++- Continue implementation here. 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 preview was developed from monorepo commit `9bd8cf1667310def711e8c491c9e6b317cdece78`. Current main through `84a23e5f8d358b78d24ba92ce185b482b5f97ebc` is now incorporated into `app-v2`: reboot restoration, release CI changes, and terminal input sequence recovery. Swarm transport fan-out still uses all deduplicated sessions. This does not merge V2 into main or publish a release.
+
+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.
++- Limits: 24 swarms, 64 panes per swarm. Add, seed, and dial paths report capacity explicitly without silently evicting a view; legacy migration retains the nine-pane storage limit.
+- `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.
++- Restore pools shared pane identity, keeps disconnected memberships, and defers initial attachment of inactive panes until shown. Previous focus is persisted; grid columns remain measured runtime geometry. Revision guards cover every asynchronous legacy restore read.
+- 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.
++- Compact remote panes expose a Show/Hide message composer button in their header. Closing the final visible pane restores keyboard focus even when its shared terminal remains parked in another Swarm.
+
+### 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.
++- `NewAgentDialog`: machine chooser, initial folder, captured destination swarm; local default when available. Reuses engine probes, Codex profiles, advanced permission behavior, and remote browsing. Profile/folder responses are rejected after a machine switch, including switching away and back. Launch replies are ignored after notifier disposal or machine replacement.
+- `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.
++- Project-store load/add operations are serialized, and failures are visible without claiming a project was saved.
++- Search supports arrows, Ctrl-N/P, and Return, reveals the selected row, and retains the highlighted agent across live list changes. Both the welcome and picker immediately focus search; blank Return on welcome does not open an invisible first result.
+- 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.
++- Spoken-task subscription/reporting/window reveal and existing linking dialogs are retained. Settings is in the title bar, with Account/sign-out restored inside Settings.
+- 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.
++- Real tabs alongside traffic lights were visually verified. Native selection, new tabs, modal-disabled controls, and independently accessible select/close buttons were checked. Drag/reorder, overflow, and a wider keyboard/accessibility audit remain.
+
+### 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.
++- Remote normalization strips credentials/transport syntax and normalizes explicit default SSH/git ports. Missing/non-Git metadata degrades gracefully; optional Dart `AgentProject` accepts older daemon payloads.
++- Production CLI was **not** installed/restarted. Newer daemons report full project/branch metadata across machines.
++- Older local daemons already report real session working folders in `/api/status`. The existing validated loopback discovery probe now carries that snapshot into project grouping, search, and headers, refreshing every ready supervision probe without extra HTTP calls. Home-relative folders are expanded for this computer only. Rich agent metadata takes precedence; local folders cannot be applied to peers or establish cross-machine repository identity.
++- The compatibility path was tested against a running CLI 0.2.17. Remote machines still require their actual existing links and connectivity; no link credentials were fabricated or daemons upgraded.
+
+### 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.
++- `debugShowCheckedModeBanner` is false. About identifies Harness V2 and explicitly describes disabled updates. Check, download/stage, and apply are all blocked by default for V2.
++- Linux/Windows names and binary identity now also use Harness V2 / `harness-v2`; those platforms have not been built on this Mac.
+
+## 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 |
++| Close agent view | Cmd+Shift+W |
+
- 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.
++Swarm shortcuts, help, and tooltips now read the same catalog in `shortcuts/app_shortcuts.dart`. The retained legacy HomeScreen explicitly opts into its old bindings. Native Swarm actions and controls are blocked while Swarm dialogs or Settings are open. Clipboard/select-all and shell/TUI keys remain owned by the terminal. Do not add AppKit menu equivalents that intercept 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.
++| macOS debug build | Passed and launched from the monorepo with real saved Swarms and terminals. |
++| macOS optimized local build | Passed with ad hoc signing and the real entry point. The distribution Developer ID certificate is unavailable; nothing was uploaded. The Mac locked before visual review, and the running debug app declined a normal quit request, so it was left running. |
++| Full Flutter suite | **968 passed, 1 skipped** after live-project discovery, keyboard navigation, and multi-machine folder-race fixes. |
++| Focused interaction checks | 8 passed: picker navigation/scroll/refresh, welcome keys, shared-view close, composer, native modal guard, profile and folder races. |
++| Local CLI discovery | 25 passed, including older-daemon folder parsing and continuous snapshots without spawning/reconnecting. |
++| CLI typecheck | `npm run typecheck` passed. |
++| CLI targeted tests | 135 passed across project/frame, registry/restore, and terminal recovery files. Project/frame tests rerun after port normalization: 9 passed. |
++| Flutter analyzer | **0 errors, 0 warnings, 12 existing vendored xterm infos**; passes with `--no-fatal-infos`. |
++| Remote terminals / production release | No remote takeover, release, installer, or production CLI update/restart. Cross-platform and latency measurements remain. |
++
++Tests now exercise the actual V2 welcome/settings/linking flow. Usage pricing again explains a partial estimate as a lower bound. Small offline panes avoid overflowing the full connection guide. No remaining full-suite failures are being dismissed as baseline.
+
+**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.
++- `harness-v2-final-tests.log`: full 968-test pass.
++- `harness-v2-final-analyze.log`: latest diagnostics.
++- `harness-v2-final-build.log`: real-entry debug build.
++- `harness-v2-release-build.log`: optimized local build.
++- `harness-v2-final-cli-check.log`, `harness-v2-final-cli-tests.log`: final metadata checks.
++- `harness-v2-resume-cli-tests.log`: 135-test CLI pass.
++- `harness-v2-keyboard-tests.log`, `harness-v2-local-project-tests.log`: focused interaction/discovery checks.
+
- 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.
++Earlier logs contain superseded failures. Temporary logs and toolchains are local conveniences, not committed artifacts.
+
- ## Remaining work, in recommended order
++## Remaining work
+
- 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.
++1. Launch the completed optimized real-data build after the Mac is unlocked; verify actual local project starters and keyboard navigation in the native shell.
++2. Audit native drag/reorder, overflow, close-last-tab, renaming and accessibility without changing the user's saved agent memberships. Keep any integration runner separate and out of the foreground review app.
++3. Measure terminal input and tab-switch responsiveness before making latency claims. Preserve the existing immediate first-input flush and shared retained renderers.
++4. Audit app-menu modal interactions (the older `harness/app_menu` path also opens Layout/Shortcuts/Firmware dialogs).
++5. Build/review Linux and Windows when their toolchains are available. Remote full project/branch metadata requires daemons running the new wire format; do not upgrade them automatically.
++6. Continue the agreed goal autonomously. The user has stepped away; lack of immediate replies is not a reason to stop independent implementation, checks, or app-v2 publishing.
+
+## 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.
++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. Use `--no-fatal-infos` for the existing vendored xterm infos; do not modify vendored style merely to erase them.
+
+```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.
++The real review app is now built in `/Users/ab/code/autonomous-harness/desktop/build/macos/Build/Products/Debug/Harness V2.app`, with the separate V2 bundle identity and saved V2 state. An optimized ad hoc signed local build is ready in the sibling `Release/` directory. It has not been launched yet: the Mac is locked and the running debug app declined a normal quit request. No process was force-terminated. Production Harness remains a separate running app. Never automatically take over its terminals or use a real Harness home as a test fixture.
+
+## 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.