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: add Cmd-P orchestrator launcher and live project workspace

Deea2da73d15769
diff --git a/cli/src/orchestrator/service.spec.ts b/cli/src/orchestrator/service.spec.ts
index c30bf2f6c..210f3539b 100644
--- a/cli/src/orchestrator/service.spec.ts
+++ b/cli/src/orchestrator/service.spec.ts
@@ -38,7 +38,8 @@ describe('durable orchestrator lifecycle', () => {
await Promise.all([start(), start()]); await active()
expect(launches).toHaveLength(1)
expect(launches[0].bypassPermission).toBe(false)
- expect(launches[0].prompt).toContain('test/blender')
+ expect(launches[0].prompt.length).toBeLessThan(2000)
+ expect(readFileSync(join(launches[0].cwd, 'ORCHESTRATOR.md'), 'utf8')).toContain('test/blender')
await expect(service.start({ id, engine: 'claude', prompt: 'Different' })).rejects.toMatchObject({ code: 'PROJECT_CONFLICT' })
})
it('validates every dependency and harness before launching any task', async () => {
@@ -61,7 +62,7 @@ describe('durable orchestrator lifecycle', () => {
const scene = await running('scene')
expect(readFileSync(join(scene.cwd, 'inputs/part/part.step'), 'utf8')).toBe('verified CAD v1')
expect(scene.inputs).toEqual({ part: 1, research: 1 })
- expect(launches.find(l => l.cwd === scene.cwd)!.prompt).toContain('warm, minimal')
+ expect(readFileSync(join(scene.cwd, 'ORCHESTRATOR_TASK.md'), 'utf8')).toContain('warm, minimal')
writeFileSync(join(scene.cwd, 'scene.png'), 'render fixture')
await service.finish(id, 'scene', 1, 'Render checked', ['scene.png'])
const film = await running('film')
diff --git a/cli/src/orchestrator/service.ts b/cli/src/orchestrator/service.ts
index 39fba926a..f381a911e 100644
--- a/cli/src/orchestrator/service.ts
+++ b/cli/src/orchestrator/service.ts
@@ -151,9 +151,11 @@ export class OrchestratorService {
}
private async launchDirector(run: Run): Promise<void> {
try {
+ writeFileSync(join(run.root, 'ORCHESTRATOR.md'), directorPrompt(run, this.catalog(), this.deps.command), { mode: 0o600, flag: 'wx' })
const result = await this.deps.create({
engine: run.engine, cwd: run.root, dsh: null, bypassPermission: run.bypassPermission,
- prompt: directorPrompt(run, this.catalog(), this.deps.command), name: `Director ${run.id.slice(0, 8)}`,
+ prompt: 'Read ORCHESTRATOR.md in this project folder. It contains the user’s request, your director role, the installed harness catalog, and the tools for coordinating specialists. Begin the project and keep the user informed.',
+ name: `Director ${run.id.slice(0, 8)}`,
})
run.directorId = result.agentId
if (run.state === 'cancelled') this.deps.cancel(result.agentId)
@@ -209,11 +211,12 @@ export class OrchestratorService {
if (task.state !== 'launching' || run.state !== 'active') return
const harness = this.catalog().find(h => h.id === task.harness)
requireThat(harness || task.harness === `engine:${run.engine}`, 'HARNESS_UNAVAILABLE', `${task.harness} is no longer installed.`)
+ writeFileSync(join(task.cwd, 'ORCHESTRATOR_TASK.md'), workerPrompt(run, task, this.deps.command), { mode: 0o600, flag: 'wx' })
creating = true
const result = await this.deps.create({
engine: (harness?.engine ?? run.engine) as AgentEngine, cwd: task.cwd,
dsh: harness?.id ?? null, bypassPermission: run.bypassPermission,
- prompt: workerPrompt(run, task, this.deps.command), name: task.title,
+ prompt: 'Read ORCHESTRATOR_TASK.md in this folder and complete the specialist assignment using your harness. Verify the result, update the viewer/verdict, then report through the exact finish or fail command in that file.', name: task.title,
})
task.agentId = result.agentId
if ((task as Task).state === 'cancelled' || (run as Run).state === 'cancelled') this.deps.cancel(result.agentId)
diff --git a/desktop/lib/orchestrator/orchestrator_controller.dart b/desktop/lib/orchestrator/orchestrator_controller.dart
new file mode 100644
index 000000000..9f20644d8
--- /dev/null
+++ b/desktop/lib/orchestrator/orchestrator_controller.dart
@@ -0,0 +1,185 @@
+import 'dart:async';
+import 'dart:math';
+
+import 'package:flutter/foundation.dart';
+
+typedef OrchestratorRequest = Future<Map<String, dynamic>> Function(
+ Map<String, dynamic> payload,
+);
+
+String orchestratorRequestId() {
+ final random = Random.secure();
+ return List.generate(
+ 16,
+ (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'),
+ ).join();
+}
+
+class OrchestratorTask {
+ OrchestratorTask(this.data);
+ final Map<String, dynamic> data;
+ String get id => data['id'] as String;
+ String get title => data['title'] as String? ?? id;
+ String get state => data['state'] as String? ?? 'queued';
+ String get harness => data['harness'] as String? ?? '';
+ String? get agentId => data['agentId'] as String?;
+ int get attempt => data['attempt'] as int? ?? 1;
+ String? get error => data['error'] as String? ?? runtime?['error'] as String?;
+ String get summary => data['summary'] as String? ?? '';
+ bool get uncertain => data['uncertain'] == true;
+ Map<String, dynamic>? get runtime =>
+ (data['runtime'] as Map?)?.cast<String, dynamic>();
+ String? get viewerUrl => runtime?['viewerUrl'] as String?;
+ String get viewerName => runtime?['viewerName'] as String? ?? title;
+ List<String> get artifacts => [
+ for (final file in data['artifacts'] as List? ?? [])
+ if (file is Map && file['path'] is String) file['path'] as String,
+ ];
+}
+
+/// A projection of daemon-owned work. Mounting a view only starts reads; disposing
+/// it never sends stop, delete, or create. Drafts survive tab switches in memory.
+class OrchestratorController extends ChangeNotifier {
+ OrchestratorController({
+ required this.id,
+ required this.request,
+ this.pollInterval = const Duration(seconds: 3),
+ });
+ final String id;
+ final OrchestratorRequest request;
+ final Duration pollInterval;
+ Map<String, dynamic>? project;
+ String? error;
+ String draft = '';
+ bool sending = false;
+ bool operating = false;
+ Timer? _poll, _coalesce;
+ Future<void>? _refresh;
+ String? _pendingMessageId, _pendingMessageText;
+ bool _disposed = false;
+ int _readers = 0;
+
+ String get state => project?['state'] as String? ?? 'connecting';
+ String? get directorId => project?['directorId'] as String?;
+ bool get directorWorking => project?['directorWorking'] == true;
+ bool get canChat =>
+ directorId != null && (state == 'active' || state == 'completed');
+ List<OrchestratorTask> get tasks => [
+ for (final task in project?['tasks'] as List? ?? [])
+ if (task is Map) OrchestratorTask(task.cast<String, dynamic>()),
+ ];
+ List<Map<String, dynamic>> get messages => [
+ for (final m in project?['messages'] as List? ?? [])
+ if (m is Map) m.cast<String, dynamic>(),
+ ];
+
+ void watch() {
+ if (_disposed || _readers++ > 0) return;
+ unawaited(refresh());
+ _poll = Timer.periodic(pollInterval, (_) => unawaited(refresh()));
+ }
+
+ void unwatch() {
+ if (_readers > 0) _readers--;
+ if (_readers > 0) return;
+ _poll?.cancel();
+ _poll = null;
+ _coalesce?.cancel();
+ _coalesce = null;
+ }
+
+ void changed() {
+ if (_disposed || _readers == 0 || _coalesce != null) return;
+ _coalesce = Timer(const Duration(milliseconds: 180), () {
+ _coalesce = null;
+ unawaited(refresh());
+ });
+ }
+
+ void _apply(Map<String, dynamic> reply) {
+ if (_disposed) return;
+ if (reply['error'] != null) {
+ throw StateError(reply['detail'] as String? ?? reply['error'].toString());
+ }
+ final incoming = (reply['project'] as Map?)?.cast<String, dynamic>();
+ if (incoming != null &&
+ incoming['id'] == id &&
+ (incoming['revision'] as num? ?? 0) >=
+ (project?['revision'] as num? ?? -1)) {
+ project = incoming;
+ }
+ error = null;
+ notifyListeners();
+ }
+
+ Future<void> refresh() =>
+ _refresh ??= _read().whenComplete(() => _refresh = null);
+ Future<void> _read() async {
+ try {
+ _apply(await request({'action': 'status', 'id': id}));
+ } catch (e) {
+ if (!_disposed) {
+ error = e.toString();
+ notifyListeners();
+ }
+ }
+ }
+
+ Future<bool> perform(String action, {String? taskId}) async {
+ if (operating || _disposed) return false;
+ operating = true;
+ notifyListeners();
+ try {
+ _apply(await request({'action': action, 'id': id, 'taskId': ?taskId}));
+ return true;
+ } catch (e) {
+ if (!_disposed) error = e.toString();
+ return false;
+ } finally {
+ if (!_disposed) {
+ operating = false;
+ notifyListeners();
+ }
+ }
+ }
+
+ Future<bool> send(String text) async {
+ if (sending || _disposed || text.trim().isEmpty) return false;
+ if (_pendingMessageText != text) {
+ _pendingMessageId = orchestratorRequestId();
+ _pendingMessageText = text;
+ }
+ sending = true;
+ notifyListeners();
+ try {
+ _apply(
+ await request({
+ 'action': 'message',
+ 'id': id,
+ 'messageId': _pendingMessageId,
+ 'text': text,
+ }),
+ );
+ _pendingMessageId = null;
+ _pendingMessageText = null;
+ if (draft == text) draft = '';
+ return true;
+ } catch (e) {
+ if (!_disposed) error = e.toString();
+ return false;
+ } finally {
+ if (!_disposed) {
+ sending = false;
+ notifyListeners();
+ }
+ }
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _poll?.cancel();
+ _coalesce?.cancel();
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/orchestrator/orchestrator_launcher.dart b/desktop/lib/orchestrator/orchestrator_launcher.dart
new file mode 100644
index 000000000..793f2e527
--- /dev/null
+++ b/desktop/lib/orchestrator/orchestrator_launcher.dart
@@ -0,0 +1,322 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_icon_button.dart';
+import '../shared/widgets/app_select_field.dart';
+import '../state/app_state.dart';
+import 'orchestrator_controller.dart';
+
+Future<void> showOrchestratorLauncher(
+ BuildContext context,
+ AppNotifier notifier,
+) async {
+ await showAppDialog<void>(
+ context: context,
+ builder: (_) => OrchestratorLauncher(notifier: notifier),
+ );
+}
+
+class OrchestratorLauncher extends StatefulWidget {
+ const OrchestratorLauncher({super.key, required this.notifier});
+ final AppNotifier notifier;
+ @override
+ State<OrchestratorLauncher> createState() => _OrchestratorLauncherState();
+}
+
+class _OrchestratorLauncherState extends State<OrchestratorLauncher> {
+ final _prompt = TextEditingController(), _folder = TextEditingController();
+ final _focus = FocusNode();
+ String _engine = 'claude';
+ String? _error;
+ bool _starting = false, _automatic = false, _advanced = false;
+ Map<String, dynamic>? _attempt;
+ List<Map<String, dynamic>> _recent = [];
+ String? get _machine => widget.notifier.localMachineState?.machine.machineId;
+
+ @override
+ void initState() {
+ super.initState();
+ final preferred = widget.notifier.agentPreference.value;
+ if (const ['claude', 'codex', 'opencode'].contains(preferred)) {
+ _engine = preferred!;
+ }
+ unawaited(_loadRecent());
+ }
+
+ Future<void> _loadRecent() async {
+ final machine = _machine;
+ if (machine == null) return;
+ try {
+ final reply = await widget.notifier.orchestratorRequest(machine, {
+ 'action': 'list',
+ });
+ if (!mounted) return;
+ setState(
+ () => _recent = [
+ for (final item in reply['projects'] as List? ?? [])
+ if (item is Map) item.cast<String, dynamic>(),
+ ],
+ );
+ } catch (e) {
+ if (mounted) setState(() => _error = e.toString());
+ }
+ }
+
+ Future<void> _start() async {
+ if (_starting || _prompt.text.trim().isEmpty) return;
+ final machine = _machine;
+ if (machine == null) {
+ setState(() => _error = 'Connect this computer’s Harness daemon first.');
+ return;
+ }
+ _attempt ??= {
+ 'action': 'start',
+ 'id': orchestratorRequestId(),
+ 'prompt': _prompt.text.trim(),
+ 'engine': _engine,
+ 'bypassPermission': _automatic,
+ if (_folder.text.trim().isNotEmpty) 'cwd': _folder.text.trim(),
+ };
+ setState(() {
+ _starting = true;
+ _error = null;
+ });
+ try {
+ final reply = await widget.notifier.orchestratorRequest(
+ machine,
+ _attempt!,
+ );
+ if (reply['error'] != null) {
+ throw StateError(
+ reply['detail'] as String? ?? reply['error'].toString(),
+ );
+ }
+ final project = reply['project'] as Map;
+ if (!mounted) return;
+ widget.notifier.openOrchestratorProject(
+ machine,
+ project['id'] as String,
+ project['prompt'] as String,
+ );
+ Navigator.of(context).pop();
+ } catch (e) {
+ // Retain the exact id and payload after an uncertain reply. A second click
+ // asks about the same launch instead of starting another director.
+ if (mounted) {
+ setState(
+ () => _error =
+ '${e.toString()}\nRetry checks the same launch; it will not create a duplicate.',
+ );
+ }
+ } finally {
+ if (mounted) setState(() => _starting = false);
+ }
+ }
+
+ @override
+ void dispose() {
+ _prompt.dispose();
+ _folder.dispose();
+ _focus.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Dialog(
+ backgroundColor: grid.AppPalette.panelBg,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
+ insetPadding: const EdgeInsets.all(24),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 740, maxHeight: 740),
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(28),
+ child: CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.enter, meta: true):
+ _start,
+ },
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Row(
+ children: [
+ Icon(
+ LucideIcons.sparkles,
+ size: 18,
+ color: grid.AppPalette.swarmAccent,
+ ),
+ const SizedBox(width: 10),
+ const Expanded(child: Text('Orchestrator')),
+ AppIconButton(
+ icon: LucideIcons.x,
+ tooltip: 'Close',
+ onPressed: () => Navigator.of(context).pop(),
+ ),
+ ],
+ ),
+ const SizedBox(height: 28),
+ Text(
+ 'What would you like to make?',
+ style: Theme.of(context).textTheme.headlineMedium,
+ ),
+ const SizedBox(height: 10),
+ Text(
+ 'One conversation. The right harnesses working together.',
+ style: TextStyle(color: grid.AppPalette.textSecondary),
+ ),
+ const SizedBox(height: 24),
+ TextField(
+ key: const ValueKey('orchestrator-prompt'),
+ controller: _prompt,
+ focusNode: _focus,
+ autofocus: true,
+ readOnly: _attempt != null,
+ minLines: 5,
+ maxLines: 9,
+ maxLength: 24000,
+ style: Theme.of(context).textTheme.titleMedium,
+ onChanged: (_) => setState(() {}),
+ decoration: const InputDecoration(
+ border: InputBorder.none,
+ counterText: '',
+ hintText: 'Design a desk lamp, render it in a warm room, and create a short launch film…',
+ ),
+ ),
+ const SizedBox(height: 12),
+ Wrap(
+ spacing: 12,
+ runSpacing: 10,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ SizedBox(
+ width: 180,
+ child: IgnorePointer(
+ ignoring: _attempt != null,
+ child: AppSelectField<String>(
+ value: _engine,
+ options: const [
+ SelectOption(
+ value: 'claude',
+ label: 'Claude director',
+ ),
+ SelectOption(
+ value: 'codex',
+ label: 'Codex director',
+ ),
+ SelectOption(
+ value: 'opencode',
+ label: 'OpenCode director',
+ ),
+ ],
+ onChanged: (value) => setState(() => _engine = value),
+ ),
+ ),
+ ),
+ TextButton(
+ onPressed: () => setState(() => _advanced = !_advanced),
+ child: const Text('Project options'),
+ ),
+ FilledButton.icon(
+ key: const ValueKey('orchestrator-start'),
+ onPressed: _starting || _prompt.text.trim().isEmpty
+ ? null
+ : _start,
+ icon: Icon(
+ _starting
+ ? LucideIcons.ellipsis
+ : LucideIcons.arrowUpRight,
+ size: 16,
+ ),
+ label: Text(
+ _starting
+ ? 'Starting…'
+ : _attempt == null
+ ? 'Start creating ⌘↵'
+ : 'Check launch',
+ ),
+ ),
+ ],
+ ),
+ if (_advanced) ...[
+ const SizedBox(height: 18),
+ TextField(
+ controller: _folder,
+ readOnly: _attempt != null,
+ decoration: const InputDecoration(
+ labelText: 'Project folder (optional)',
+ hintText: 'Absolute path to an existing folder',
+ ),
+ ),
+ CheckboxListTile(
+ contentPadding: EdgeInsets.zero,
+ value: _automatic,
+ onChanged: _attempt != null
+ ? null
+ : (value) =>
+ setState(() => _automatic = value ?? false),
+ title: const Text(
+ 'Use the engines’ automatic approval modes',
+ ),
+ subtitle: const Text(
+ 'Off by default. Otherwise inspect an agent to answer its permission prompts.',
+ ),
+ ),
+ ],
+ const SizedBox(height: 18),
+ Text(
+ 'Runs on this computer with installed harnesses. Each specialist gets its own folder; no automatic installs.',
+ style: TextStyle(
+ color: grid.AppPalette.textSecondary,
+ fontSize: 12,
+ ),
+ ),
+ if (_error != null)
+ Padding(
+ padding: const EdgeInsets.only(top: 16),
+ child: SelectableText(
+ _error!,
+ style: TextStyle(color: grid.AppPalette.warn),
+ ),
+ ),
+ if (_recent.isNotEmpty) ...[
+ const Divider(height: 32),
+ const Text('Recent projects'),
+ for (final project in _recent.take(4))
+ ListTile(
+ contentPadding: EdgeInsets.zero,
+ dense: true,
+ title: Text(
+ project['prompt'] as String? ?? 'Project',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ subtitle: Text(project['state'] as String? ?? ''),
+ trailing: const Icon(LucideIcons.arrowUpRight, size: 14),
+ onTap: _machine == null
+ ? null
+ : () {
+ widget.notifier.openOrchestratorProject(
+ _machine!,
+ project['id'] as String,
+ project['prompt'] as String? ?? 'Project',
+ );
+ Navigator.of(context).pop();
+ },
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/orchestrator/orchestrator_workspace.dart b/desktop/lib/orchestrator/orchestrator_workspace.dart
new file mode 100644
index 000000000..532b601bc
--- /dev/null
+++ b/desktop/lib/orchestrator/orchestrator_workspace.dart
@@ -0,0 +1,550 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_icon_button.dart';
+import '../state/app_state.dart';
+import '../state/terminal_pane.dart';
+import '../widgets/web_pane_panel.dart';
+import 'orchestrator_controller.dart';
+import 'orchestrator_launcher.dart';
+
+class OrchestratorWorkspace extends StatefulWidget {
+ const OrchestratorWorkspace({
+ super.key,
+ required this.notifier,
+ required this.machineId,
+ required this.projectId,
+ this.controller,
+ });
+ final AppNotifier notifier;
+ final String machineId, projectId;
+ final OrchestratorController? controller;
+ @override
+ State<OrchestratorWorkspace> createState() => _OrchestratorWorkspaceState();
+}
+
+class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {
+ late final OrchestratorController model =
+ widget.controller ??
+ widget.notifier.orchestratorProject(widget.machineId, widget.projectId);
+ late final _composer = TextEditingController(text: model.draft);
+ final _composerFocus = FocusNode(), _messagesScroll = ScrollController();
+ final _viewers = <String, TerminalPane>{};
+ int _nextPane = -1;
+ String? _expanded;
+
+ @override
+ void initState() {
+ super.initState();
+ model.addListener(_changed);
+ model.watch();
+ }
+
+ void _changed() {
+ if (!mounted) return;
+ final follow =
+ !_messagesScroll.hasClients ||
+ _messagesScroll.position.extentAfter < 100;
+ setState(() {});
+ if (follow) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && _messagesScroll.hasClients) {
+ _messagesScroll.jumpTo(_messagesScroll.position.maxScrollExtent);
+ }
+ });
+ }
+ }
+
+ @override
+ void dispose() {
+ model.removeListener(_changed);
+ model.unwatch();
+ _composer.dispose();
+ _composerFocus.dispose();
+ _messagesScroll.dispose();
+ super.dispose();
+ }
+
+ Future<void> _send() async {
+ final text = _composer.text;
+ if (await model.send(text) && mounted && _composer.text == text) {
+ _composer.clear();
+ }
+ if (mounted) _composerFocus.requestFocus();
+ }
+
+ Future<void> _stop() async {
+ final confirmed = await showAppDialog<bool>(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: const Text('Stop this project?'),
+ content: const Text(
+ 'Stops the director and active specialist turns. Files and agent sessions remain available to inspect. Other projects are unaffected.',
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context, false),
+ child: const Text('Keep working'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text('Stop project'),
+ ),
+ ],
+ ),
+ );
+ if (confirmed == true) await model.perform('cancel');
+ }
+
+ void _inspect(String agentId) => unawaited(
+ widget.notifier.inspectOrchestratorAgent(widget.machineId, agentId),
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Padding(
+ padding: const EdgeInsets.all(12),
+ child: Column(
+ children: [
+ Row(
+ children: [
+ Icon(
+ LucideIcons.sparkles,
+ size: 17,
+ color: grid.AppPalette.swarmAccent,
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ 'Orchestrator · ${model.state}',
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ if (const ['cancelled', 'paused', 'failed'].contains(model.state))
+ TextButton(
+ onPressed: model.operating
+ ? null
+ : () => model.perform('resume'),
+ child: const Text('Resume'),
+ ),
+ if (const ['starting', 'active'].contains(model.state))
+ TextButton(
+ onPressed: model.operating ? null : _stop,
+ child: const Text('Stop'),
+ ),
+ AppIconButton(
+ icon: LucideIcons.plus,
+ tooltip: 'New project (⌘P)',
+ onPressed: () =>
+ showOrchestratorLauncher(context, widget.notifier),
+ ),
+ ],
+ ),
+ if ((model.error ?? model.project?['error']) != null) ...[
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ model.error ?? model.project?['error'] as String? ?? '',
+ style: TextStyle(color: grid.AppPalette.warn),
+ ),
+ ),
+ TextButton(
+ onPressed: model.refresh,
+ child: const Text('Reconnect'),
+ ),
+ ],
+ ),
+ ],
+ const SizedBox(height: 12),
+ Expanded(
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ if (constraints.maxWidth < 760) {
+ return Column(
+ children: [
+ Expanded(child: _outputs()),
+ const SizedBox(height: 10),
+ Expanded(child: _conversation()),
+ ],
+ );
+ }
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(child: _outputs()),
+ const SizedBox(width: 12),
+ SizedBox(
+ width: (constraints.maxWidth * .34).clamp(300, 440),
+ child: _conversation(),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _outputs() {
+ final tasks = model.tasks;
+ if (tasks.isEmpty) {
+ return _surface(
+ Center(
+ child: Padding(
+ padding: const EdgeInsets.all(32),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ LucideIcons.layers,
+ color: grid.AppPalette.textSecondary,
+ size: 28,
+ ),
+ const SizedBox(height: 16),
+ const Text('Your work takes shape here'),
+ const SizedBox(height: 8),
+ Text(
+ model.state == 'starting' ? 'Starting your director…' : 'Live views appear as specialists begin. You can keep talking on the right.',
+ textAlign: TextAlign.center,
+ style: TextStyle(color: grid.AppPalette.textSecondary),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+ final visible = _expanded == null
+ ? tasks
+ : tasks.where((t) => t.id == _expanded).toList();
+ return Column(
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Live views · ${tasks.length} tasks',
+ style: TextStyle(color: grid.AppPalette.textSecondary),
+ ),
+ ),
+ if (_expanded != null)
+ TextButton(
+ onPressed: () => setState(() => _expanded = null),
+ child: const Text('All views'),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Expanded(
+ child: LayoutBuilder(
+ builder: (context, c) => GridView.builder(
+ key: const ValueKey('orchestrator-views'),
+ itemCount: visible.length,
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: visible.length > 1 && c.maxWidth >= 680 ? 2 : 1,
+ mainAxisExtent: visible.length == 1
+ ? c.maxHeight.clamp(180, 1000)
+ : 330,
+ mainAxisSpacing: 12,
+ crossAxisSpacing: 12,
+ ),
+ itemBuilder: (context, index) => _task(visible[index]),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget _task(OrchestratorTask task) {
+ final paneKey = '${task.id}/${task.attempt}';
+ Widget content;
+ final viewerUrl = task.viewerUrl;
+ final uri = viewerUrl == null ? null : Uri.tryParse(viewerUrl);
+ // Mirror same-host ownership. Never mount an arbitrary remote URL returned by
+ // an older or malformed daemon as a privileged local viewer.
+ final safeViewer =
+ uri != null &&
+ const ['http', 'https'].contains(uri.scheme) &&
+ const ['127.0.0.1', 'localhost', '::1', '[::1]'].contains(uri.host);
+ if (safeViewer && task.agentId != null) {
+ final pane = _viewers.putIfAbsent(
+ paneKey,
+ () => TerminalPane(
+ id: _nextPane--,
+ machineId: widget.machineId,
+ kind: PaneKind.web,
+ ownerAgentId: task.agentId,
+ ),
+ )..url = viewerUrl;
+ content = WebPanePanel(
+ notifier: widget.notifier,
+ pane: pane,
+ title: task.viewerName,
+ ownerName: task.title,
+ ownerEngine: null,
+ ownerDisplayName: task.harness,
+ working: task.state == 'running',
+ compactHeader: true,
+ zoomed: _expanded == task.id,
+ onToggleZoom: () =>
+ setState(() => _expanded = _expanded == task.id ? null : task.id),
+ );
+ } else {
+ content = Center(
+ child: Padding(
+ padding: const EdgeInsets.all(20),
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ task.state == 'succeeded'
+ ? LucideIcons.check
+ : LucideIcons.layers,
+ size: 24,
+ color: grid.AppPalette.textSecondary,
+ ),
+ const SizedBox(height: 12),
+ Text(
+ task.error ??
+ (task.summary.isNotEmpty
+ ? task.summary
+ : task.state == 'queued'
+ ? 'Waiting for upstream results or an available worker.'
+ : 'The specialist’s live view will appear when its viewer is ready.'),
+ textAlign: TextAlign.center,
+ ),
+ if (task.artifacts.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.only(top: 10),
+ child: SelectableText(task.artifacts.join('\n')),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+ return _surface(
+ Column(
+ key: ValueKey('task:$paneKey'),
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(12, 8, 8, 8),
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ task.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ Text(
+ '${task.harness} · ${task.state}${task.attempt > 1 ? ' · attempt ${task.attempt}' : ''}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: task.error == null
+ ? grid.AppPalette.textSecondary
+ : grid.AppPalette.warn,
+ fontSize: 12,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (!task.uncertain &&
+ const [
+ 'failed',
+ 'blocked',
+ 'cancelled',
+ ].contains(task.state) &&
+ model.state == 'active')
+ AppIconButton(
+ icon: LucideIcons.rotateCcw,
+ tooltip: 'Retry task',
+ onPressed: model.operating
+ ? null
+ : () => model.perform('retry', taskId: task.id),
+ ),
+ if (task.agentId != null)
+ AppIconButton(
+ icon: LucideIcons.terminal,
+ tooltip: 'Inspect ${task.title}',
+ onPressed: () => _inspect(task.agentId!),
+ ),
+ ],
+ ),
+ ),
+ Expanded(child: content),
+ ],
+ ),
+ );
+ }
+
+ Widget _conversation() => _surface(
+ Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(18, 10, 10, 10),
+ child: Row(
+ children: [
+ const Expanded(child: Text('Director')),
+ if (model.directorId != null)
+ AppIconButton(
+ icon: LucideIcons.terminal,
+ tooltip: 'Inspect director',
+ onPressed: () => _inspect(model.directorId!),
+ ),
+ ],
+ ),
+ ),
+ const Divider(height: 1),
+ Expanded(
+ child: SelectionArea(
+ child: ListView.builder(
+ key: const ValueKey('orchestrator-conversation'),
+ controller: _messagesScroll,
+ padding: const EdgeInsets.all(18),
+ itemCount: model.messages.length,
+ itemBuilder: (context, index) {
+ final message = model.messages[index];
+ final role = message['role'];
+ return Padding(
+ key: ValueKey(message['id']),
+ padding: const EdgeInsets.only(bottom: 22),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ role == 'user'
+ ? 'You'
+ : role == 'assistant'
+ ? 'Director'
+ : 'Project update',
+ style: TextStyle(
+ color: grid.AppPalette.textSecondary,
+ fontSize: 12,
+ ),
+ ),
+ const SizedBox(height: 6),
+ Text(message['text'] as String? ?? ''),
+ if (message['delivery'] == 'failed')
+ Text(
+ 'Delivery failed. Inspect the director before resending.',
+ style: TextStyle(color: grid.AppPalette.warn),
+ ),
+ ],
+ ),
+ );
+ },
+ ),
+ ),
+ ),
+ if (model.directorWorking)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 6),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ 'Director is working…',
+ style: TextStyle(
+ color: grid.AppPalette.textSecondary,
+ fontSize: 12,
+ ),
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.all(12),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: grid.AppSurface.recess,
+ borderRadius: BorderRadius.circular(14),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(12, 8, 6, 6),
+ child: Column(
+ children: [
+ Focus(
+ onKeyEvent: (_, event) {
+ if (event is KeyDownEvent &&
+ event.logicalKey == LogicalKeyboardKey.enter &&
+ !HardwareKeyboard.instance.isShiftPressed &&
+ !_composer.value.composing.isValid) {
+ if (model.canChat) unawaited(_send());
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: TextField(
+ key: const ValueKey('orchestrator-composer'),
+ controller: _composer,
+ focusNode: _composerFocus,
+ minLines: 2,
+ maxLines: 6,
+ maxLength: 24000,
+ enabled: model.canChat,
+ onChanged: (value) => model.draft = value,
+ decoration: InputDecoration(
+ border: InputBorder.none,
+ counterText: '',
+ hintText: model.canChat
+ ? 'Keep shaping the project…'
+ : 'Waiting for the director…',
+ ),
+ ),
+ ),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ Text(
+ 'Shift ↵ for a new line',
+ style: TextStyle(
+ color: grid.AppPalette.textSecondary,
+ fontSize: 11,
+ ),
+ ),
+ const SizedBox(width: 10),
+ AppIconButton(
+ icon: LucideIcons.arrowUp,
+ tooltip: 'Send to director',
+ onPressed: !model.canChat || model.sending
+ ? null
+ : _send,
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+
+ Widget _surface(Widget child) => Container(
+ decoration: BoxDecoration(
+ color: grid.AppPalette.panelBg,
+ border: Border.all(color: grid.AppPalette.divider),
+ borderRadius: BorderRadius.circular(16),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: child,
+ );
+}
diff --git a/desktop/lib/screens/home_screen.dart b/desktop/lib/screens/home_screen.dart
index 044d7b8d1..ecdb1aa66 100644
--- a/desktop/lib/screens/home_screen.dart
+++ b/desktop/lib/screens/home_screen.dart
@@ -18,6 +18,8 @@ import '../settings/settings_section.dart';
import '../shortcuts/app_shortcuts.dart';
import '../widgets/new_agent_dialog.dart';
import '../widgets/task_palette.dart';
+import '../orchestrator/orchestrator_launcher.dart';
+import '../orchestrator/orchestrator_workspace.dart';
import '../widgets/pane_grid.dart';
import '../widgets/shortcuts_sheet.dart';
import '../widgets/status_rail/status_rail.dart';
@@ -258,6 +260,8 @@ class _HomeScreenState extends State<HomeScreen> {
ShortcutAction.newAgent: _newAgent,
ShortcutAction.routeTask: () =>
unawaited(showTaskPalette(context, notifier)),
+ ShortcutAction.orchestrate: () =>
+ unawaited(showOrchestratorLauncher(context, notifier)),
ShortcutAction.reload: () => unawaited(notifier.retryMachines()),
ShortcutAction.pinPane: () {
final id = notifier.focusedPaneId;
@@ -371,7 +375,21 @@ class _HomeScreenState extends State<HomeScreen> {
}),
),
Expanded(
- child: PaneGrid(notifier: notifier),
+ child:
+ notifier.activeSwarm.isOrchestrator
+ ? OrchestratorWorkspace(
+ key: ValueKey(
+ 'orchestrator:${notifier.activeSwarm.orchestratorId}',
+ ),
+ notifier: notifier,
+ machineId: notifier
+ .activeSwarm
+ .orchestratorMachineId!,
+ projectId: notifier
+ .activeSwarm
+ .orchestratorId!,
+ )
+ : PaneGrid(notifier: notifier),
),
],
),
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 814b39a64..39d5f8b2a 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -50,6 +50,8 @@ import '../widgets/swarm_wallpaper.dart';
import '../widgets/agent_action_icons.dart';
import '../widgets/swarm_icon.dart';
import '../widgets/task_palette.dart';
+import '../orchestrator/orchestrator_launcher.dart';
+import '../orchestrator/orchestrator_workspace.dart';
class SwarmScreen extends StatefulWidget {
const SwarmScreen({
@@ -1289,6 +1291,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
ShortcutAction.newAgent: _newAgent,
ShortcutAction.routeTask: () =>
_dialog(() => showTaskPalette(context, app)),
+ ShortcutAction.orchestrate: () =>
+ _dialog(() => showOrchestratorLauncher(context, app)),
ShortcutAction.reload: app.retryMachines,
ShortcutAction.showLayout: () =>
_dialog(() => showLayoutPalette(context, app)),
@@ -1501,66 +1505,75 @@ class _SwarmScreenState extends State<SwarmScreen> {
key: ValueKey('harness-start-background'),
child: SwarmWallpaper(),
),
- if (app.activeSwarm.isStore)
+ if (app.activeSwarm.isOrchestrator)
+ OrchestratorWorkspace(
+ key: ValueKey(
+ 'orchestrator:${app.activeSwarm.orchestratorId}',
+ ),
+ notifier: app,
+ machineId: app.activeSwarm.orchestratorMachineId!,
+ projectId: app.activeSwarm.orchestratorId!,
+ )
+ else if (app.activeSwarm.isStore)
StoreTab(
key: ValueKey('store-tab:${app.activeSwarmId}'),
notifier: app,
source: 'tab',
)
else
- Padding(
- padding: app.panes.isEmpty
- ? EdgeInsets.zero
- : const EdgeInsets.all(10),
- child: Focus.withExternalFocusNode(
- focusNode: _canvasFocus,
- includeSemantics: false,
- child: Stack(
- children: [
- Positioned.fill(
- child: PaneGrid(
- notifier: app,
- swarmMode: true,
- onSplit: (paneId, axis) => unawaited(
- _splitAgent(axis, paneId: paneId),
- ),
- onNewSplit: (paneId, axis) => unawaited(
- _splitAgent(
- axis,
- paneId: paneId,
- create: true,
+ Padding(
+ padding: app.panes.isEmpty
+ ? EdgeInsets.zero
+ : const EdgeInsets.all(10),
+ child: Focus.withExternalFocusNode(
+ focusNode: _canvasFocus,
+ includeSemantics: false,
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: PaneGrid(
+ notifier: app,
+ swarmMode: true,
+ onSplit: (paneId, axis) => unawaited(
+ _splitAgent(axis, paneId: paneId),
+ ),
+ onNewSplit: (paneId, axis) => unawaited(
+ _splitAgent(
+ axis,
+ paneId: paneId,
+ create: true,
+ ),
),
+ empty: app.panes.isEmpty
+ ? HarnessStartPage(
+ key: ValueKey(
+ 'harness-start:${app.activeSwarmId}',
+ ),
+ focusNode: _startSearchFocus,
+ createSearch: () =>
+ SwarmSearchController(
+ app,
+ _navigation.recent,
+ projects: _projects,
+ commands: _searchCommands,
+ adding: true,
+ catalog: _searchCatalog,
+ ),
+ onNew: _newAgent,
+ onStore: app.openStore,
+ onChoose: (selection) =>
+ _activateSearch(
+ selection,
+ app.activeSwarmId,
+ ),
+ )
+ : null,
),
- empty: app.panes.isEmpty
- ? HarnessStartPage(
- key: ValueKey(
- 'harness-start:${app.activeSwarmId}',
- ),
- focusNode: _startSearchFocus,
- createSearch: () =>
- SwarmSearchController(
- app,
- _navigation.recent,
- projects: _projects,
- commands: _searchCommands,
- adding: true,
- catalog: _searchCatalog,
- ),
- onNew: _newAgent,
- onStore: app.openStore,
- onChoose: (selection) =>
- _activateSearch(
- selection,
- app.activeSwarmId,
- ),
- )
- : null,
),
- ),
- ],
+ ],
+ ),
),
),
- ),
],
),
),
@@ -1649,7 +1662,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
children: [
if (swarm.isStore)
StoreMark(
- key: ValueKey('tab-store:${swarm.id}'),
+ key: ValueKey(
+ 'tab-store:${swarm.id}',
+ ),
)
else if (_tabAgents(swarm).length == 1)
EngineMark(
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index 844608b07..4b6d7f020 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -54,6 +54,7 @@ enum ShortcutAction {
closePane,
newAgent,
routeTask,
+ orchestrate,
reload,
showLayout,
pinPane,
@@ -289,6 +290,12 @@ const List<AppShortcut> kAppShortcuts = [
label: 'Describe a task, and let it pick the agent',
group: ShortcutGroup.actions,
),
+ AppShortcut(
+ action: ShortcutAction.orchestrate,
+ activator: SingleActivator(LogicalKeyboardKey.keyP, meta: true),
+ label: 'Create with the orchestrator',
+ group: ShortcutGroup.actions,
+ ),
AppShortcut(
action: ShortcutAction.reload,
activator: SingleActivator(LogicalKeyboardKey.keyR, meta: true),
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index e9d875b53..a30fe6c93 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -315,6 +315,12 @@ final harnessCommands = <HarnessCommand>[
ShortcutGroup.actions,
action: ShortcutAction.routeTask,
),
+ const HarnessCommand(
+ 'project.orchestrate',
+ 'Create with the orchestrator',
+ ShortcutGroup.actions,
+ action: ShortcutAction.orchestrate,
+ ),
const HarnessCommand(
'app.settings',
'Open Settings',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 351114ecb..7578e61c1 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -61,6 +61,7 @@ import 'pending_question.dart';
import 'session_preview.dart';
import '../usage/remote_usage.dart';
import '../usage/usage_accounts.dart';
+import '../orchestrator/orchestrator_controller.dart';
enum AppStatus {
bootstrapping,
@@ -291,6 +292,7 @@ class AppNotifier extends ChangeNotifier {
final AuthSession session;
AppConfig config;
late ApiClient api;
+
/// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,
/// [ViewerServices.login] in a viewer build — which has no CLI — under one name, so every call
/// site reads the same in both.
@@ -501,11 +503,9 @@ class AppNotifier extends ChangeNotifier {
final target = swarms.where((s) => s.id == entry.swarmId).firstOrNull;
return target == null ||
target.panes.length < maxPanes ||
- target.panes.any(
- (p) =>
- p.machineId == entry.machineId &&
- p.agentId == entry.agentId,
- );
+ target.panes.any(
+ (p) => p.machineId == entry.machineId && p.agentId == entry.agentId,
+ );
}
bool _canReopenSwarm(ClosedSwarm saved) {
@@ -544,6 +544,74 @@ class AppNotifier extends ChangeNotifier {
Iterable<TerminalPane> get allPanes => swarms.expand((s) => s.panes).toSet();
String get activeSwarmId => activeSwarm.id;
+ final _orchestratorProjects = <String, OrchestratorController>{};
+
+ Future<Map<String, dynamic>> orchestratorRequest(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) async {
+ if (machineId != localMachineState?.machine.machineId) {
+ throw StateError(
+ 'Orchestrator projects currently run on this computer only.',
+ );
+ }
+ try {
+ return await _conn(machineId).request(
+ 'orchestrator',
+ payload: payload,
+ timeout: const Duration(seconds: 35),
+ );
+ } on WsRequestFailure catch (e) {
+ if (e.code == 'UNSUPPORTED') {
+ throw StateError(
+ 'Update the local Harness CLI to use the orchestrator.',
+ );
+ }
+ rethrow;
+ }
+ }
+
+ OrchestratorController orchestratorProject(String machineId, String id) =>
+ _orchestratorProjects.putIfAbsent(
+ '$machineId/$id',
+ () => OrchestratorController(
+ id: id,
+ request: (payload) => orchestratorRequest(machineId, payload),
+ ),
+ );
+
+ void openOrchestratorProject(String machineId, String id, String title) {
+ final existing = swarms
+ .where(
+ (s) => s.orchestratorId == id && s.orchestratorMachineId == machineId,
+ )
+ .firstOrNull;
+ if (existing != null) {
+ selectSwarm(existing.id);
+ return;
+ }
+ final name = title.trim().replaceAll(RegExp(r'\s+'), ' ');
+ newSwarm(
+ name: name.isEmpty
+ ? 'Orchestrator'
+ : name.substring(0, name.length.clamp(0, 48)),
+ );
+ activeSwarm
+ ..kind = 'orchestrator'
+ ..orchestratorId = id
+ ..orchestratorMachineId = machineId;
+ _persistLayout();
+ notifyListeners();
+ }
+
+ Future<void> inspectOrchestratorAgent(
+ String machineId,
+ String agentId,
+ ) async {
+ newSwarm(name: 'Inspect agent');
+ await addAgentToSwarm(machineId, agentId, swarmId: activeSwarmId);
+ }
+
// A New Tab remains temporary until it has content or a custom name.
// The return destination is session-local; abandoned drafts are never saved.
final _draftSwarmReturns = <String, String>{};
@@ -838,6 +906,8 @@ class AppNotifier extends ChangeNotifier {
return;
}
final restored = Swarm(id: saved.id, name: saved.name, kind: saved.kind)
+ ..orchestratorId = saved.orchestratorId
+ ..orchestratorMachineId = saved.orchestratorMachineId
..gridColumns = saved.gridColumns
..presets.addAll(saved.presets)
..paneSizes.addAll(saved.paneSizes);
@@ -2493,7 +2563,8 @@ class AppNotifier extends ChangeNotifier {
final updater = desktopUpdater ?? DesktopUpdater();
final staged = await updater.downloadAndStage(info);
if (staged == null) {
- updateError = 'Could not download and verify OpenHarness ${info.version}.';
+ updateError =
+ 'Could not download and verify OpenHarness ${info.version}.';
return false;
}
final applied = await updater.applyStaged(staged, selfPid: pid);
@@ -3559,7 +3630,10 @@ class AppNotifier extends ChangeNotifier {
if (decision == null) return;
// The dialog may list the machines, and the person may have moved the choice.
machineId = decision.machineId;
- final error = await _startLocalModelAgent(machineId, prompt: decision.prompt);
+ final error = await _startLocalModelAgent(
+ machineId,
+ prompt: decision.prompt,
+ );
if (error != null) {
_lastError = error;
_lastErrorRetryable = false;
@@ -3591,7 +3665,10 @@ class AppNotifier extends ChangeNotifier {
/// before this dialog had buttons.
///
/// Null on success, else the sentence for the person.
- Future<String?> _startLocalModelAgent(String machineId, {String? prompt}) async {
+ Future<String?> _startLocalModelAgent(
+ String machineId, {
+ String? prompt,
+ }) async {
final machine = machineStates[machineId];
if (machine == null) return 'Machine not found';
final home = await _homeFolderOf(machine);
@@ -6118,17 +6195,32 @@ class AppNotifier extends ChangeNotifier {
raw['kind'] == 'store' ||
(raw['name'] == Swarm.storeName && (raw['panes'] as List).isEmpty);
if (isStore && restored.any((s) => s.isStore)) 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),
- )
- : Swarm.defaultName,
- kind: isStore ? 'store' : 'harness',
- );
+ 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),
+ )
+ : Swarm.defaultName,
+ kind: isStore
+ ? 'store'
+ : raw['kind'] == 'orchestrator'
+ ? 'orchestrator'
+ : 'harness',
+ )
+ ..orchestratorId =
+ raw['orchestratorId'] is String &&
+ RegExp(r'^[a-f0-9]{32}$')
+ .hasMatch(raw['orchestratorId'] as String)
+ ? raw['orchestratorId'] as String
+ : null
+ ..orchestratorMachineId = raw['orchestratorMachineId'] is String
+ ? raw['orchestratorMachineId'] as String
+ : null;
for (final item in (raw['panes'] as List).take(maxPanes)) {
final entry = PaneLayoutEntry.fromJson(item);
if (entry == null) continue;
@@ -6345,6 +6437,10 @@ class AppNotifier extends ChangeNotifier {
if (machine == null) return;
final type = event['type'] as String? ?? '';
final payload = (event['payload'] as Map<String, dynamic>?) ?? {};
+ if (type == 'orchestrator_changed') {
+ _orchestratorProjects['$machineId/${payload['id']}']?.changed();
+ return;
+ }
// Only terminal protocol frames visit the session pool. Heartbeats, dial
// scroll and discovery events must not await every retained terminal.
// Each session still sees terminal frames: ready replies match their own
@@ -6677,6 +6773,9 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
+ for (final project in _orchestratorProjects.values) {
+ project.dispose();
+ }
grid.AppTheme.palette.removeListener(_announceTerminalThemeEverywhere);
terminalThemeStore.removeListener(_announceTerminalThemeEverywhere);
_localGitProjects.dispose();
diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dart
index 7bfa001de..dc799bbb3 100644
--- a/desktop/lib/state/swarm.dart
+++ b/desktop/lib/state/swarm.dart
@@ -18,6 +18,11 @@ class Swarm {
/// over the New Tab it was opened from, the way a first agent does.
String kind;
bool get isStore => kind == 'store';
+ bool get isOrchestrator =>
+ kind == 'orchestrator' &&
+ orchestratorId != null &&
+ orchestratorMachineId != null;
+ String? orchestratorId, orchestratorMachineId;
static const storeName = 'Harness Store';
static const defaultName = 'New Tab';
@@ -104,6 +109,8 @@ class Swarm {
'id': id,
'name': name,
if (kind != 'harness') 'kind': kind,
+ if (isOrchestrator) 'orchestratorId': orchestratorId,
+ if (isOrchestrator) 'orchestratorMachineId': orchestratorMachineId,
'focus': agents.indexWhere((p) => p.id == focusedPaneId),
'previousFocus': agents.indexWhere((p) => p.id == previousPaneId),
'zoom': agents.indexWhere((p) => p.id == zoomedPaneId),
@@ -174,6 +181,8 @@ class ClosedSwarm extends ClosedWork {
}) : id = swarm.id,
name = swarm.name,
kind = swarm.kind,
+ orchestratorId = swarm.orchestratorId,
+ orchestratorMachineId = swarm.orchestratorMachineId,
gridColumns = swarm.gridColumns,
focus = swarm.panes.indexWhere((p) => p.id == swarm.focusedPaneId),
previousFocus = swarm.panes.indexWhere(
@@ -198,6 +207,7 @@ class ClosedSwarm extends ClosedWork {
/// So a closed store tab reopens as the store, not as an empty harness tab.
final String kind;
+ final String? orchestratorId, orchestratorMachineId;
final String? engine;
final int index;
final int? gridColumns;
diff --git a/desktop/test/orchestrator_test.dart b/desktop/test/orchestrator_test.dart
new file mode 100644
index 000000000..ee255ff19
--- /dev/null
+++ b/desktop/test/orchestrator_test.dart
@@ -0,0 +1,235 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/orchestrator/orchestrator_controller.dart';
+import 'package:harness/orchestrator/orchestrator_workspace.dart';
+import 'package:harness/shortcuts/app_shortcuts.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/terminal_panel.dart';
+import 'package:harness/widgets/web_pane_panel.dart';
+
+import 'swarm_state_test.dart' show createApp, MemoryStore;
+
+const projectId = '0123456789abcdef0123456789abcdef';
+Map<String, dynamic> project({
+ int revision = 1,
+ List<Map<String, dynamic>> tasks = const [],
+}) => {
+ 'id': projectId,
+ 'revision': revision,
+ 'state': 'active',
+ 'directorId': 'director',
+ 'directorWorking': false,
+ 'tasks': tasks,
+ 'messages': <Map<String, dynamic>>[
+ {'id': 'prompt', 'role': 'user', 'text': 'Build a lamp and launch film'},
+ {
+ 'id': 'reply',
+ 'role': 'assistant',
+ 'text': 'I’ll coordinate CAD, Blender, and video.',
+ },
+ ],
+};
+Map<String, dynamic> task(String id, {String state = 'running', String? url}) =>
+ {
+ 'id': id,
+ 'title': id,
+ 'harness': 'test/$id',
+ 'state': state,
+ 'attempt': 1,
+ 'agentId': 'agent-$id',
+ 'artifacts': <dynamic>[],
+ 'runtime': {'viewerUrl': url, 'viewerName': '$id view'},
+ };
+
+void main() {
+ test('Cmd-P is two keys and leaves Cmd-B and Shift-Cmd-P distinct', () {
+ final shortcut = kAppShortcuts
+ .singleWhere((s) => s.action == ShortcutAction.orchestrate)
+ .activator;
+ expect(shortcut.trigger, LogicalKeyboardKey.keyP);
+ expect(shortcut.meta, isTrue);
+ expect(shortcut.shift, isFalse);
+ expect(shortcut.control, isFalse);
+ expect(shortcut.alt, isFalse);
+ expect(
+ kAppShortcuts
+ .singleWhere((s) => s.action == ShortcutAction.routeTask)
+ .activator
+ .trigger,
+ LogicalKeyboardKey.keyB,
+ );
+ });
+
+ test(
+ 'transient chat failure retries the same receipt and retains the draft',
+ () async {
+ final requests = <Map<String, dynamic>>[];
+ var fail = true;
+ final controller = OrchestratorController(
+ id: projectId,
+ request: (payload) async {
+ requests.add(payload);
+ if (fail) throw StateError('Disconnected');
+ return {'project': project(revision: 2)};
+ },
+ );
+ addTearDown(controller.dispose);
+ controller.draft = 'Make it taller';
+ expect(await controller.send(controller.draft), isFalse);
+ expect(controller.draft, 'Make it taller');
+ fail = false;
+ expect(await controller.send(controller.draft), isTrue);
+ expect(requests[0]['messageId'], requests[1]['messageId']);
+ expect(controller.draft, isEmpty);
+ },
+ );
+
+ test('late polling results do not replace newer action results', () async {
+ final poll = Completer<Map<String, dynamic>>();
+ final controller = OrchestratorController(
+ id: projectId,
+ request: (payload) => payload['action'] == 'status'
+ ? poll.future
+ : Future.value({'project': project(revision: 5)}),
+ );
+ addTearDown(controller.dispose);
+ final pending = controller.refresh();
+ await controller.perform('resume');
+ poll.complete({'project': project(revision: 2)});
+ await pending;
+ expect(controller.project!['revision'], 5);
+ });
+
+ testWidgets(
+ 'progressive viewers never expose worker terminals or steal a draft',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ var current = project();
+ final requests = <Map<String, dynamic>>[];
+ final controller = OrchestratorController(
+ id: projectId,
+ request: (payload) async {
+ requests.add(payload);
+ return {'project': current};
+ },
+ );
+ addTearDown(controller.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 850);
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: OrchestratorWorkspace(
+ notifier: app,
+ machineId: 'm',
+ projectId: projectId,
+ controller: controller,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ final composer = find.byKey(const ValueKey('orchestrator-composer'));
+ await tester.tap(composer);
+ await tester.enterText(composer, 'Keep the base slimmer');
+ current = project(
+ revision: 2,
+ tasks: [task('cad', url: 'http://127.0.0.1:9999/cad')],
+ );
+ await controller.refresh();
+ await tester.pump();
+ current = project(
+ revision: 3,
+ tasks: [
+ task('cad', url: 'http://127.0.0.1:9999/cad'),
+ task('blender', url: 'http://127.0.0.1:9998/scene'),
+ task('video'),
+ ],
+ );
+ await controller.refresh();
+ await tester.pump();
+ expect(
+ tester.widget<TextField>(composer).controller!.text,
+ 'Keep the base slimmer',
+ );
+ expect(tester.widget<TextField>(composer).focusNode!.hasFocus, isTrue);
+ expect(find.byType(TerminalPanel), findsNothing);
+ expect(find.byType(WebPanePanel), findsNWidgets(2));
+ expect(app.panes, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(
+ requests.where((r) => r['action'] == 'message').single['text'],
+ 'Keep the base slimmer',
+ );
+ expect(tester.widget<TextField>(composer).controller!.text, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ expect(requests.any((r) => r['action'] == 'cancel'), isFalse);
+ },
+ );
+
+ testWidgets('small workspace fits and unsafe viewer URLs are not mounted', (
+ tester,
+ ) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final controller = OrchestratorController(
+ id: projectId,
+ request: (_) async => {
+ 'project': project(
+ tasks: [task('cad', url: 'https://untrusted.example/view')],
+ ),
+ },
+ );
+ addTearDown(controller.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(600, 850);
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: OrchestratorWorkspace(
+ notifier: app,
+ machineId: 'm',
+ projectId: projectId,
+ controller: controller,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ expect(find.byType(WebPanePanel), findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ test(
+ 'project tabs survive close/reopen and persisted layout restore',
+ () async {
+ final store = MemoryStore();
+ final app = createApp(store: store);
+ addTearDown(app.dispose);
+ app.openOrchestratorProject('m', projectId, 'Lamp project');
+ final tabId = app.activeSwarmId;
+ expect(app.activeSwarm.isOrchestrator, isTrue);
+ await app.closeSwarm(tabId);
+ app.reopenClosedSwarm();
+ expect(app.activeSwarm.orchestratorId, projectId);
+ expect(app.activeSwarm.orchestratorMachineId, 'm');
+ await app.flushPaneLayout();
+ expect(store.values['swarm_layout_v1'], contains(projectId));
+ final restored = createApp(store: store);
+ addTearDown(restored.dispose);
+ await restored.restorePaneLayoutForTest();
+ expect(restored.swarms.singleWhere((s) => s.orchestratorId == projectId).isOrchestrator, isTrue);
+ },
+ );
+}
diff --git a/docs/keyboard.md b/docs/keyboard.md
index 388ce655d..2939dbd7d 100644
--- a/docs/keyboard.md
+++ b/docs/keyboard.md
@@ -10,6 +10,7 @@ The defaults, in the workspace:
| ⌘O | Open Harness — search sessions, tabs, machines, history; `>` for commands |
| ⇧⌘P | Command palette |
| ⌘B | Boss mode: describe a task, it picks the agent |
+| ⌘P | Orchestrator: describe a project, coordinate background harnesses and live viewers |
| ⌘T · ⌘W · ⇧⌘T · ⇧⌘R | New tab · close tab · reopen last closed · rename tab |
| ⌘1 … ⌘9 | Select tab by position |
| ⇧⌘] · ⇧⌘[ · ⌃Tab · ⌃⇧Tab | Next · previous tab |