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 file attachment support to New Harness

Dev jacob59318f87fb9b
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 5f92e10f7..44bae7431 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -46,6 +46,7 @@ import '../widgets/notification_inbox.dart';
import '../widgets/workspace_notifications_button.dart';
import '../state/harness_sessions.dart';
import '../state/harness_activity.dart';
+import '../state/harness_attachments.dart';
import '../state/harness_placement.dart';
import '../state/new_harness.dart';
import 'swarm_menu_bus.dart';
@@ -472,7 +473,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
children: [
WorkspaceMachinePrompt(
loading: app.machinesLoading,
- preparing: app.localMachineState != null,
+ preparing: _hasNewHarnessMachine,
onChoose: () => unawaited(_openMachines()),
),
if (recent != null) ...[
@@ -513,7 +514,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
_search == null &&
!_commandBarOpen &&
!_pickingFolder &&
- app.localMachineState != null;
+ _hasNewHarnessMachine;
+
+ /// A machine New Harness can start on without asking: this computer, or the
+ /// host's choice when it runs none (a browser's connected machine).
+ bool get _hasNewHarnessMachine =>
+ app.localMachineState != null ||
+ widget.chrome?.newHarnessMachine?.call() != null;
void _scheduleWelcomeComposer() {
if (_welcomeEntryScheduled || !_canShowWelcomeComposer) return;
@@ -2936,6 +2943,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
swarmId: swarmId,
split: split,
placement: placement,
+ attachments: widget.chrome?.attachesFiles == true
+ ? HarnessAttachments(onDeliveryProblem: _showPaneActionHint)
+ : null,
);
_newHarnessFormKey = GlobalKey<NewHarnessFormState>();
_newHarnessDevicePort = DeviceFormPort();
diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dart
index 5ed943f39..d56929afc 100644
--- a/desktop/lib/shared/theme/app_icons.dart
+++ b/desktop/lib/shared/theme/app_icons.dart
@@ -65,6 +65,7 @@ abstract final class AppIcons {
static const externalLink = LucideIcons.externalLink400;
static const eye = LucideIcons.eye400;
static const eyeOff = LucideIcons.eyeOff400;
+ static const file = LucideIcons.file400;
static const fileText = LucideIcons.fileText400;
static const film = LucideIcons.film400;
static const flaskConical = LucideIcons.flaskConical400;
@@ -103,6 +104,7 @@ abstract final class AppIcons {
static const packageCheck = LucideIcons.packageCheck400;
static const packageOpen = LucideIcons.packageOpen400;
static const palette = LucideIcons.palette400;
+ static const paperclip = LucideIcons.paperclip400;
static const panelsTopLeft = LucideIcons.panelsTopLeft400;
static const pause = LucideIcons.pause400;
static const pencil = LucideIcons.pencil400;
diff --git a/desktop/lib/state/attached_task_delivery.dart b/desktop/lib/state/attached_task_delivery.dart
new file mode 100644
index 000000000..de5eaf374
--- /dev/null
+++ b/desktop/lib/state/attached_task_delivery.dart
@@ -0,0 +1,115 @@
+import 'dart:async';
+
+import '../logging/app_log.dart';
+import '../terminal/terminal_session.dart';
+import 'app_state.dart';
+import 'harness_attachments.dart';
+
+/// How long a new harness has to open its terminal and start its engine.
+const kAttachedTaskOpenTimeout = Duration(minutes: 2);
+
+/// A beat after the engine reports ready, for its input to be drawn.
+const kAttachedTaskSettle = Duration(milliseconds: 800);
+
+/// Can [machineId] take files into a harness's prompt? Both halves are the
+/// daemon's: a file written there and its path pasted, then a space pasted.
+bool canAttachFiles(AppNotifier app, String machineId) {
+ final machine = app.stateOf(machineId);
+ return machine != null &&
+ machine.terminalPasteFileAvailable &&
+ machine.terminalPasteRawAvailable;
+}
+
+/// Hands a new harness its files, then its first message.
+///
+/// A first message given at creation reaches the engine as a launch argument,
+/// before any file could: files only travel into a live terminal, which writes
+/// each on the harness's machine and pastes its path into the prompt. So a task
+/// with files is created without one, and sent here once the prompt holds the
+/// paths — as a composer message, which the machine submits and retries Enter
+/// for. Returns what went wrong, or null.
+Future<String?> deliverAttachedTask(
+ AppNotifier app, {
+ required String machineId,
+ required String agentId,
+ required List<HarnessAttachment> files,
+ required String task,
+}) async {
+ appLog.info('attach', 'waiting on $agentId for ${files.length} file(s)');
+ final session = await _readySession(app, machineId, agentId);
+ if (session == null) {
+ appLog.warn('attach', '$agentId never took input');
+ return 'The harness did not open in time. Attach the files in its pane.';
+ }
+ for (final file in files) {
+ if (!await session.pasteFile(file.name, file.bytes) ||
+ !await session.pasteText(' ')) {
+ appLog.warn('attach', '${file.name} did not reach $agentId');
+ return 'Could not attach ${file.name}. Attach it in the pane.';
+ }
+ }
+ appLog.info('attach', '${files.length} file(s) in $agentId; sending task');
+ if (task.trim().isEmpty) return null;
+ return await session.sendComposerText(task)
+ ? null
+ : 'The files are attached, but the task was not sent.';
+}
+
+/// The harness's terminal once its engine is up and the pane takes input.
+Future<TerminalSession?> _readySession(
+ AppNotifier app,
+ String machineId,
+ String agentId,
+) async {
+ var claimed = false;
+ TerminalSession? ready() {
+ final agent = app
+ .stateOf(machineId)
+ ?.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ if (agent?.launchState != 'ready') return null;
+ final session = app
+ .panesFor(machineId)
+ .where((pane) => pane.agentId == agentId)
+ .map((pane) => pane.session)
+ .nonNulls
+ .firstOrNull;
+ if (session == null) return null;
+ if (session.acceptsInput) return session;
+ // A pane that arrives over the desk opens as a watcher, and another window
+ // on the account (the Mac's own app) may hold the terminal. Pressing New
+ // Harness with files is this person asking to type here: take it, once,
+ // as the band's "Take control" does.
+ if (!claimed &&
+ session.streamId != null &&
+ (session.watching ||
+ session.status == TerminalSessionStatus.takenOver)) {
+ claimed = true;
+ appLog.info('attach', 'taking control of $agentId to hand it its files');
+ unawaited(session.reopen(force: true));
+ }
+ return null;
+ }
+
+ final found = Completer<TerminalSession?>();
+ void check() {
+ if (found.isCompleted) return;
+ if (ready() case final session?) found.complete(session);
+ }
+
+ final timeout = Timer(kAttachedTaskOpenTimeout, () {
+ if (!found.isCompleted) found.complete(null);
+ });
+ app.addListener(check);
+ check();
+ try {
+ final session = await found.future;
+ if (session == null) return null;
+ await Future<void>.delayed(kAttachedTaskSettle);
+ return session.acceptsInput ? session : null;
+ } finally {
+ timeout.cancel();
+ app.removeListener(check);
+ }
+}
diff --git a/desktop/lib/state/harness_attachments.dart b/desktop/lib/state/harness_attachments.dart
new file mode 100644
index 000000000..6c3664458
--- /dev/null
+++ b/desktop/lib/state/harness_attachments.dart
@@ -0,0 +1,63 @@
+import 'package:flutter/foundation.dart';
+
+import '../terminal/terminal_binary.dart'
+ show terminalLocalPasteFileMaxPayloadBytes;
+
+/// One file attached to a harness that does not exist yet.
+@immutable
+class HarnessAttachment {
+ const HarnessAttachment(this.name, this.bytes);
+
+ final String name;
+ final Uint8List bytes;
+}
+
+/// The files a New Harness box carries into its harness. Held in memory
+/// until the harness's terminal is open to take them ([deliverAttachedTask]).
+class HarnessAttachments extends ChangeNotifier {
+ HarnessAttachments({this.onDeliveryProblem});
+
+ /// What one file may weigh: the daemon's own ceiling for a pasted file.
+ static const maxBytes = terminalLocalPasteFileMaxPayloadBytes;
+
+ /// Told when files could not reach a created harness — after its box has
+ /// closed, so the workspace says it rather than the box.
+ final void Function(String message)? onDeliveryProblem;
+
+ final _files = <HarnessAttachment>[];
+
+ List<HarnessAttachment> get files => List.unmodifiable(_files);
+ bool get isEmpty => _files.isEmpty;
+
+ /// Adds the files that fit, replacing one of the same name. Returns what
+ /// to tell the person about any left out, or null when all were taken.
+ String? add(Iterable<HarnessAttachment> files) {
+ final tooLarge = <String>[];
+ for (final file in files) {
+ if (file.bytes.isEmpty) continue;
+ if (file.bytes.length > maxBytes) {
+ tooLarge.add(file.name);
+ continue;
+ }
+ _files
+ ..removeWhere((kept) => kept.name == file.name)
+ ..add(file);
+ }
+ notifyListeners();
+ if (tooLarge.isEmpty) return null;
+ final limit = '${maxBytes ~/ (1024 * 1024)} MB';
+ return tooLarge.length == 1
+ ? '${tooLarge.single} is over $limit.'
+ : '${tooLarge.length} files are over $limit.';
+ }
+
+ void remove(HarnessAttachment file) {
+ if (_files.remove(file)) notifyListeners();
+ }
+
+ void clear() {
+ if (_files.isEmpty) return;
+ _files.clear();
+ notifyListeners();
+ }
+}
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 65ceaa022..5f7dd487f 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -24,7 +24,9 @@ import '../core/test_run.dart';
import '../widgets/engine_identity.dart';
import '../widgets/resting_model_words.dart';
import 'app_state.dart';
+import 'attached_task_delivery.dart';
import 'harness_placement.dart';
+import 'harness_attachments.dart';
import 'pane_arrangement.dart';
/// Whether New Harness opens as a line in the box, or as the full form.
@@ -406,6 +408,7 @@ class NewHarnessController extends ChangeNotifier {
String? home,
ModelsMenuController? modelUsage,
Random? random,
+ this.attachments,
}) : _random = random ?? Random(),
placement =
placement ?? (split == null ? HarnessPlacement.currentTab : null),
@@ -1072,6 +1075,10 @@ class NewHarnessController extends ChangeNotifier {
NewHarnessField field = NewHarnessField.agent;
final bool offersStore;
+
+ /// Files for the harness's prompt, when the host lets New Harness attach
+ /// them (the browser). Null leaves the box as desktop has it.
+ final HarnessAttachments? attachments;
String query = '';
/// The harness's first message, sent exactly as written as it starts. Empty
@@ -3398,6 +3405,16 @@ class NewHarnessController extends ChangeNotifier {
permissionMode != null && permissionModeApproves(permissionMode);
final folder = _project.folder;
final firstMessage = task.trim();
+ // Files ride into the live terminal after creation, and the task follows
+ // them there (see deliverAttachedTask), so neither is a launch argument.
+ final files = takesTask
+ ? attachments?.files ?? const <HarnessAttachment>[]
+ : const <HarnessAttachment>[];
+ if (files.isNotEmpty && !canAttachFiles(app, _machineId)) {
+ return _fail(
+ 'Update Harness CLI on $machineLabel to attach files, or remove them.',
+ );
+ }
final failure = await app.createAgent(
_machineId,
engine: base,
@@ -3412,13 +3429,21 @@ class NewHarnessController extends ChangeNotifier {
model: _model,
dsh: harness,
// Sent exactly as written; an agent that cannot take one is never sent it.
- prompt: takesTask && firstMessage.isNotEmpty ? firstMessage : null,
+ prompt: takesTask && files.isEmpty && firstMessage.isNotEmpty
+ ? firstMessage
+ : null,
// A new project named by the person, or after its task, names the agent
// too — until the engine titles the session. A clock-named one leaves
// it to the machine ("Solder harness 9-18 13:02").
name: projectFolderRequest?.agentName,
attempt: attempt,
);
+ // Before the disposed check: on an empty tab the new pane replaces this
+ // box as soon as it opens, disposing it while createAgent returns — and
+ // the files still have to follow the harness there.
+ if (failure == null && files.isNotEmpty) {
+ _deliverFiles(attempt.agentId, files, firstMessage);
+ }
if (_disposed) return NewHarnessOutcome.failed;
if (failure != null) {
// A folder already made for this attempt is the project now: a retry
@@ -3439,6 +3464,34 @@ class NewHarnessController extends ChangeNotifier {
return NewHarnessOutcome.created;
}
+ /// Hands a created harness its files and then its task, detached from this
+ /// box, which may already be gone ([deliverAttachedTask]).
+ void _deliverFiles(
+ String? agentId,
+ List<HarnessAttachment> files,
+ String task,
+ ) {
+ final report = attachments?.onDeliveryProblem;
+ if (!_disposed) attachments?.clear();
+ if (agentId == null) {
+ report?.call(
+ 'The harness started without its files. Attach them in its pane.',
+ );
+ return;
+ }
+ unawaited(
+ deliverAttachedTask(
+ app,
+ machineId: _machineId,
+ agentId: agentId,
+ files: files,
+ task: task,
+ ).then((problem) {
+ if (problem != null) report?.call(problem);
+ }),
+ );
+ }
+
NewHarnessOutcome _fail(String message) {
busy = false;
status = null;
@@ -3450,6 +3503,8 @@ class NewHarnessController extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
+ // Its files were copied out for delivery; only the list goes.
+ attachments?.dispose();
_appTick?.cancel();
_listDebounce?.cancel();
app.removeListener(_onApp);
diff --git a/desktop/lib/state/workspace_chrome.dart b/desktop/lib/state/workspace_chrome.dart
index c63b2085b..7c3529ef0 100644
--- a/desktop/lib/state/workspace_chrome.dart
+++ b/desktop/lib/state/workspace_chrome.dart
@@ -47,6 +47,7 @@ class WorkspaceChrome {
this.viewMachineCloses = false,
this.showsShareStatus = false,
this.scrollsTabsByArrows = false,
+ this.attachesFiles = false,
this.compactTabs,
this.compactBelow = 0,
});
@@ -76,6 +77,9 @@ class WorkspaceChrome {
/// True puts arrows either side of a tab list too long for the bar.
final bool scrollsTabsByArrows;
+ /// True lets New Harness take files — a button and drops on its box.
+ final bool attachesFiles;
+
/// Below [compactBelow] of window width the workspace goes compact: this
/// replaces the tab list (the Store button steps aside), and only the focused
/// harness is drawn — a phone has room for neither a tab row nor a grid.
diff --git a/desktop/lib/web/picker/web_picker_bar.dart b/desktop/lib/web/picker/web_picker_bar.dart
index d792156fc..4db7e1ca0 100644
--- a/desktop/lib/web/picker/web_picker_bar.dart
+++ b/desktop/lib/web/picker/web_picker_bar.dart
@@ -1,50 +1,61 @@
import 'package:flutter/material.dart';
-import '../../shared/theme/app_theme.dart' as grid;
+import '../../shared/theme/app_icons.dart';
+import '../../shared/widgets/app_icon_button.dart';
import '../../state/workspace_chrome.dart';
-import '../../terminal/terminal_text.dart';
-import '../../terminal/terminal_theme.dart';
-import '../../terminal/terminal_theme_store.dart';
+import '../../widgets/desktop_chrome.dart';
import 'web_picker_scopes.dart';
/// The row over the picker's input: Back out of a scope, the scopes the
-/// prefix keys reach, and close — each a click instead of a key.
+/// prefix keys reach, and close — each a click instead of a key. Scopes are
+/// the design system's compact scope pills (design/desktop-design-system.md).
class WebPickerBar extends StatelessWidget {
const WebPickerBar({super.key, required this.picker});
final WorkspacePicker picker;
+ /// Lines the first pill up with the search field's text, past its icon.
+ static const _fieldTextInset = 57.0;
+
@override
Widget build(BuildContext context) {
final search = picker.search;
- final cell = terminalCellSizeOf(context);
return ListenableBuilder(
listenable: search,
builder: (context, _) => Padding(
key: const ValueKey('web-picker-bar'),
- // Align the host scopes with the shared search editor text.
- padding: EdgeInsets.fromLTRB(57, cell.height * .5, cell.width, 0),
+ padding: const EdgeInsets.fromLTRB(
+ _fieldTextInset,
+ DesktopChrome.controlGap + 4,
+ DesktopChrome.controlGap,
+ 0,
+ ),
child: Row(
children: [
if (search.canGoBack) ...[
- _BarText(
+ DesktopPill(
key: const ValueKey('web-picker-back'),
- label: '‹ Back',
+ label: 'Back',
+ leading: const Icon(AppIcons.chevronLeft, size: 14),
+ quiet: true,
+ compact: true,
onPressed: () {
if (search.back()) picker.focus();
},
),
- SizedBox(width: cell.width * 2),
+ const SizedBox(width: DesktopChrome.controlGap),
],
Expanded(
child: Wrap(
- spacing: cell.width * 2,
+ spacing: 6,
+ runSpacing: 6,
children: [
for (final scope in webPickerScopes(search))
- _BarText(
+ DesktopPill(
key: ValueKey('web-picker-scope:${scope.prefix}'),
label: scope.label,
- active:
+ compact: true,
+ selected:
!search.isHelpMode &&
search.scopePrefix == scope.prefix,
onPressed: () {
@@ -55,9 +66,11 @@ class WebPickerBar extends StatelessWidget {
],
),
),
- _BarText(
+ AppIconButton(
key: const ValueKey('web-picker-close'),
- label: '×',
+ icon: AppIcons.close,
+ tooltip: 'Close',
+ size: 16,
onPressed: picker.close,
),
],
@@ -66,45 +79,3 @@ class WebPickerBar extends StatelessWidget {
);
}
}
-
-/// A line of picker text that is also a button: dim until hovered, full ink
-/// and underlined when it names where the picker is.
-class _BarText extends StatelessWidget {
- const _BarText({
- super.key,
- required this.label,
- required this.onPressed,
- this.active = false,
- });
-
- final String label;
- final VoidCallback onPressed;
- final bool active;
-
- @override
- Widget build(BuildContext context) {
- final theme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- );
- return TextButton(
- onPressed: onPressed,
- style: TextButton.styleFrom(
- foregroundColor: theme.foreground.withValues(alpha: active ? 1 : .54),
- textStyle: terminalContentStyle().copyWith(
- decoration: active ? TextDecoration.underline : null,
- ),
- padding: EdgeInsets.zero,
- minimumSize: Size.zero,
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- shape: const RoundedRectangleBorder(),
- ),
- child: SizedBox(
- height: terminalCellSizeOf(context).height * 1.5,
- // Centered on the row's height only: a plain Center would take the
- // whole width and stack every scope on a line of its own.
- child: Center(widthFactor: 1, child: Text(label)),
- ),
- );
- }
-}
diff --git a/desktop/lib/web/shell/web_chrome.dart b/desktop/lib/web/shell/web_chrome.dart
index 0a60d7ca6..bfdcd8598 100644
--- a/desktop/lib/web/shell/web_chrome.dart
+++ b/desktop/lib/web/shell/web_chrome.dart
@@ -20,6 +20,7 @@ WorkspaceChrome webWorkspaceChrome(AppNotifier app) => WorkspaceChrome(
viewMachineCloses: true,
showsShareStatus: true,
scrollsTabsByArrows: true,
+ attachesFiles: true,
compactTabs: (context, commands) =>
WebTabSwitcher(app: app, commands: commands),
compactBelow: kWebCompactBelow,
diff --git a/desktop/lib/widgets/new_harness_attachments.dart b/desktop/lib/widgets/new_harness_attachments.dart
new file mode 100644
index 000000000..447ae35eb
--- /dev/null
+++ b/desktop/lib/widgets/new_harness_attachments.dart
@@ -0,0 +1,185 @@
+import 'dart:async';
+
+import 'package:desktop_drop/desktop_drop.dart';
+import 'package:file_selector/file_selector.dart';
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/widgets/app_icon_button.dart';
+import '../state/harness_attachments.dart';
+import 'desktop_chrome.dart';
+
+/// Reads picked or dropped files into attachments, and says what was left out.
+Future<void> _attach(
+ BuildContext context,
+ HarnessAttachments attachments,
+ Iterable<XFile> files,
+) async {
+ final read = [
+ for (final file in files)
+ HarnessAttachment(file.name, await file.readAsBytes()),
+ ];
+ final problem = attachments.add(read);
+ if (problem == null || !context.mounted) return;
+ ScaffoldMessenger.maybeOf(context)
+ ?.showSnackBar(SnackBar(content: Text(problem)));
+}
+
+/// 📎 beside New Harness: opens the system's file chooser.
+class NewHarnessAttachButton extends StatelessWidget {
+ const NewHarnessAttachButton({
+ super.key,
+ required this.attachments,
+ required this.enabled,
+ });
+
+ final HarnessAttachments attachments;
+ final bool enabled;
+
+ @override
+ Widget build(BuildContext context) => AppIconButton(
+ key: const ValueKey('new-harness-attach'),
+ icon: AppIcons.paperclip,
+ tooltip: 'Attach files',
+ size: 16,
+ onPressed: !enabled
+ ? null
+ : () async {
+ final files = await openFiles();
+ if (files.isEmpty || !context.mounted) return;
+ await _attach(context, attachments, files);
+ },
+ );
+}
+
+/// The attached files, each a chip its × takes back out.
+class NewHarnessAttachmentChips extends StatelessWidget {
+ const NewHarnessAttachmentChips({
+ super.key,
+ required this.attachments,
+ required this.enabled,
+ });
+
+ final HarnessAttachments attachments;
+ final bool enabled;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: attachments,
+ builder: (context, _) => Wrap(
+ spacing: 6,
+ runSpacing: 6,
+ children: [
+ for (final file in attachments.files)
+ _AttachmentChip(
+ file: file,
+ onRemove: enabled ? () => attachments.remove(file) : null,
+ ),
+ ],
+ ),
+ );
+}
+
+class _AttachmentChip extends StatelessWidget {
+ const _AttachmentChip({required this.file, required this.onRemove});
+
+ final HarnessAttachment file;
+ final VoidCallback? onRemove;
+
+ @override
+ Widget build(BuildContext context) => Container(
+ key: ValueKey('new-harness-attachment:${file.name}'),
+ constraints: const BoxConstraints(maxWidth: 220),
+ padding: const EdgeInsets.only(left: 10, right: 2),
+ height: DesktopChrome.compactControlHeight,
+ decoration: BoxDecoration(
+ color: DesktopChrome.foreground.withValues(alpha: .055),
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(AppIcons.file, size: 13, color: DesktopChrome.muted),
+ const SizedBox(width: 6),
+ Flexible(
+ child: Text(
+ file.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(),
+ ),
+ ),
+ AppIconButton(
+ icon: AppIcons.close,
+ tooltip: 'Remove ${file.name}',
+ size: AppIcons.closeSize,
+ onPressed: onRemove,
+ ),
+ ],
+ ),
+ );
+}
+
+/// Files dropped anywhere on [child] are attached; while a drag is over it,
+/// it says so.
+class NewHarnessDropZone extends StatefulWidget {
+ const NewHarnessDropZone({
+ super.key,
+ required this.attachments,
+ required this.enabled,
+ required this.child,
+ });
+
+ final HarnessAttachments attachments;
+ final bool enabled;
+ final Widget child;
+
+ @override
+ State<NewHarnessDropZone> createState() => _NewHarnessDropZoneState();
+}
+
+class _NewHarnessDropZoneState extends State<NewHarnessDropZone> {
+ bool _hovering = false;
+
+ void _hover(bool value) {
+ if (mounted && _hovering != value) setState(() => _hovering = value);
+ }
+
+ @override
+ Widget build(BuildContext context) => DropTarget(
+ key: const ValueKey('new-harness-drop'),
+ enable: widget.enabled,
+ onDragEntered: (_) => _hover(true),
+ onDragExited: (_) => _hover(false),
+ onDragDone: (details) {
+ _hover(false);
+ unawaited(_attach(context, widget.attachments, details.files));
+ },
+ child: Stack(
+ children: [
+ widget.child,
+ if (_hovering)
+ Positioned.fill(
+ child: IgnorePointer(
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: DesktopChrome.accent.withValues(alpha: .1),
+ border: Border.all(color: DesktopChrome.accent, width: 1.5),
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Center(
+ child: Text(
+ 'Drop files to attach',
+ style: DesktopChrome.control(
+ color: DesktopChrome.accent,
+ medium: true,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index 435f8ed18..8d578fbbe 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -20,6 +20,7 @@ import '../state/device_form.dart';
import 'box_chrome.dart' show kTerminalCornerRadius, terminalPaneBorder;
import 'dsh_install_panel.dart' show describeInstallFailure;
import 'desktop_chrome.dart';
+import 'new_harness_attachments.dart';
import 'engine_identity.dart';
/// Desktop composer and legacy terminal launch form sharing the same draft.
@@ -1823,7 +1824,43 @@ class NewHarnessFormState extends State<NewHarnessForm> {
visualDensity: VisualDensity.compact,
);
- Widget _desktopTaskEditor() => ListenableBuilder(
+ /// The task box, taking dropped files when the host attaches them.
+ Widget _desktopTaskEditor() => switch (box.attachments) {
+ final attachments? when box.takesTask => NewHarnessDropZone(
+ attachments: attachments,
+ enabled: !box.locked,
+ child: _desktopTaskBox(),
+ ),
+ _ => _desktopTaskBox(),
+ };
+
+ /// 📎 and the attached files, then New Harness — or New Harness alone.
+ Widget _desktopTaskActions() {
+ final attachments = box.takesTask ? box.attachments : null;
+ if (attachments == null) {
+ return Align(
+ alignment: Alignment.centerRight,
+ child: _desktopStartButton(),
+ );
+ }
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: [
+ NewHarnessAttachButton(attachments: attachments, enabled: !box.locked),
+ const SizedBox(width: 6),
+ Expanded(
+ child: NewHarnessAttachmentChips(
+ attachments: attachments,
+ enabled: !box.locked,
+ ),
+ ),
+ const SizedBox(width: 12),
+ _desktopStartButton(),
+ ],
+ );
+ }
+
+ Widget _desktopTaskBox() => ListenableBuilder(
listenable: _taskFocus,
builder: (context, _) => Material(
key: const ValueKey('new-harness-composer'),
@@ -1877,10 +1914,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
),
),
const SizedBox(height: 12),
- Align(
- alignment: Alignment.centerRight,
- child: _desktopStartButton(),
- ),
+ _desktopTaskActions(),
],
),
),
diff --git a/desktop/test/harness_attachments_test.dart b/desktop/test/harness_attachments_test.dart
new file mode 100644
index 000000000..adf5c1835
--- /dev/null
+++ b/desktop/test/harness_attachments_test.dart
@@ -0,0 +1,195 @@
+import 'dart:async';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/attached_task_delivery.dart';
+import 'package:harness/state/harness_attachments.dart';
+import 'package:harness/terminal/terminal_session.dart';
+
+HarnessAttachment _file(String name, [int size = 4]) =>
+ HarnessAttachment(name, Uint8List(size));
+
+/// Records what a harness's terminal was handed, in order.
+class _RecordingSession extends TerminalSession {
+ _RecordingSession()
+ : super(
+ machineId: 'box',
+ agentId: 'a1',
+ agentName: 'Weather',
+ engineId: 'claude',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ ) {
+ status = TerminalSessionStatus.controlling;
+ streamId = 's1';
+ }
+
+ final calls = <String>[];
+
+ @override
+ Future<bool> pasteFile(String filename, Uint8List content) async {
+ calls.add('file:$filename');
+ return true;
+ }
+
+ @override
+ Future<bool> pasteText(String text, {String? tabId}) async {
+ calls.add('paste:$text');
+ return true;
+ }
+
+ @override
+ Future<bool> sendComposerText(String text, {String? tabId}) async {
+ calls.add('send:$text');
+ return true;
+ }
+
+ /// "Take control": the daemon answers by handing this window the lease.
+ @override
+ Future<void> reopen({bool force = false}) async {
+ calls.add('reopen:$force');
+ watching = false;
+ notifyListeners();
+ }
+}
+
+AppNotifier _app({String launch = 'ready', bool canPasteFiles = true}) {
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession());
+ app.machineStates['box'] =
+ MachineState(
+ const Machine(
+ machineId: 'box',
+ name: 'Box',
+ authMode: MachineAuthMode.remote,
+ ),
+ )
+ ..terminalPasteFileAvailable = canPasteFiles
+ ..terminalPasteRawAvailable = true
+ ..agents = [Agent(id: 'a1', name: 'Weather', launchState: launch)];
+ return app;
+}
+
+void main() {
+ group('HarnessAttachments', () {
+ test('keeps one file per name and refuses what is over the limit', () {
+ final files = HarnessAttachments();
+ expect(files.add([_file('a.png'), _file('b.txt')]), isNull);
+ expect(files.add([_file('a.png', 8)]), isNull);
+ expect(files.files.map((f) => f.name), ['b.txt', 'a.png']);
+ expect(files.files.last.bytes.length, 8);
+ final problem = files.add([
+ _file('huge.mov', HarnessAttachments.maxBytes + 1),
+ ]);
+ expect(problem, contains('huge.mov'));
+ expect(files.files, hasLength(2));
+ files.remove(files.files.first);
+ expect(files.files.map((f) => f.name), ['a.png']);
+ });
+ });
+
+ group('deliverAttachedTask', () {
+ test('files first, each followed by a space, then the task', () async {
+ final app = _app();
+ addTearDown(app.dispose);
+ final session = _RecordingSession();
+ app.adoptSessionForTest(session);
+ final problem = await deliverAttachedTask(
+ app,
+ machineId: 'box',
+ agentId: 'a1',
+ files: [_file('shot.png'), _file('notes.md')],
+ task: 'Summarise these',
+ );
+ expect(problem, isNull);
+ expect(session.calls, [
+ 'file:shot.png',
+ 'paste: ',
+ 'file:notes.md',
+ 'paste: ',
+ 'send:Summarise these',
+ ]);
+ });
+
+ testWidgets('waits for the engine to be ready before handing anything', (
+ tester,
+ ) async {
+ final app = _app(launch: 'starting');
+ addTearDown(app.dispose);
+ final session = _RecordingSession();
+ app.adoptSessionForTest(session);
+ String? problem = 'pending';
+ unawaited(
+ deliverAttachedTask(
+ app,
+ machineId: 'box',
+ agentId: 'a1',
+ files: [_file('shot.png')],
+ task: 'Look',
+ ).then((value) => problem = value),
+ );
+ await tester.pump(const Duration(seconds: 5));
+ expect(session.calls, isEmpty);
+ app.machineStates['box']!.agents = [
+ const Agent(id: 'a1', name: 'Weather'),
+ ];
+ app.notifyListeners();
+ await tester.pump(kAttachedTaskSettle + const Duration(milliseconds: 10));
+ await tester.pump();
+ expect(problem, isNull);
+ expect(session.calls.first, 'file:shot.png');
+ });
+
+ test('takes control of a pane that opened as a watcher', () async {
+ final app = _app();
+ addTearDown(app.dispose);
+ // Another window on the account (the Mac's own app) holds the terminal.
+ final session = _RecordingSession()..watching = true;
+ app.adoptSessionForTest(session);
+ final problem = await deliverAttachedTask(
+ app,
+ machineId: 'box',
+ agentId: 'a1',
+ files: [_file('shot.png')],
+ task: 'Look',
+ );
+ expect(problem, isNull);
+ expect(session.calls, [
+ 'reopen:true',
+ 'file:shot.png',
+ 'paste: ',
+ 'send:Look',
+ ]);
+ });
+
+ testWidgets('gives up with a message when the harness never opens', (
+ tester,
+ ) async {
+ final app = _app(launch: 'starting');
+ addTearDown(app.dispose);
+ String? problem;
+ unawaited(
+ deliverAttachedTask(
+ app,
+ machineId: 'box',
+ agentId: 'a1',
+ files: [_file('shot.png')],
+ task: 'Look',
+ ).then((value) => problem = value),
+ );
+ await tester.pump(kAttachedTaskOpenTimeout + const Duration(seconds: 1));
+ await tester.pump();
+ expect(problem, contains('did not open in time'));
+ });
+ });
+
+ test('a machine whose CLI cannot paste files cannot take attachments', () {
+ final app = _app(canPasteFiles: false);
+ addTearDown(app.dispose);
+ expect(canAttachFiles(app, 'box'), isFalse);
+ expect(canAttachFiles(app, 'nowhere'), isFalse);
+ });
+}
diff --git a/desktop/test/new_harness_attachments_test.dart b/desktop/test/new_harness_attachments_test.dart
new file mode 100644
index 000000000..0ed92604e
--- /dev/null
+++ b/desktop/test/new_harness_attachments_test.dart
@@ -0,0 +1,151 @@
+// New Harness with files: the task waits for them, and the files still follow
+// a harness whose box closed while it was being created.
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/engine_availability.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_attachments.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/pane_arrangement.dart';
+
+class _Notifier extends AppNotifier {
+ _Notifier()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+
+ final prompts = <String?>[];
+
+ /// Runs while the machine is creating, the way a new pane replacing the
+ /// start page disposes its box.
+ void Function()? duringCreate;
+
+ @override
+ Future<Map<String, dynamic>> readGitProject(
+ String machineId,
+ String path, {
+ bool refresh = false,
+ }) async => {'isGit': false};
+
+ @override
+ Future<void> probeEngines(String machineId, {bool force = false}) async {}
+
+ @override
+ Future<void> probeDsh(String machineId, {bool force = false}) async {}
+
+ @override
+ Future<Map<String, dynamic>> listCodexProfiles(
+ String machineId, {
+ Set<String> observedPaths = const {},
+ }) async => {'profiles': <dynamic>[]};
+
+ @override
+ Future<String?> createAgent(
+ String machineId, {
+ required String engine,
+ required String? folder,
+ bool bypassPermission = false,
+ String? permissionMode,
+ String? codexHome,
+ String? dsh,
+ GridModel? model,
+ String? prompt,
+ String? name,
+ String? agent,
+ ProjectFolderRequest? projectFolder,
+ String? swarmId,
+ PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
+ }) async {
+ prompts.add(prompt);
+ duringCreate?.call();
+ return null;
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ _Notifier app({bool canPasteFiles = true}) {
+ final notifier = _Notifier();
+ addTearDown(notifier.dispose);
+ notifier.machineStates['box'] =
+ MachineState(
+ const Machine(
+ machineId: 'box',
+ name: 'Box',
+ authMode: MachineAuthMode.remote,
+ ),
+ )
+ ..localOnly = true
+ ..terminalPasteFileAvailable = canPasteFiles
+ ..terminalPasteRawAvailable = true;
+ notifier.machineStates['box']!.engines.replace(const [
+ EngineAvailability(engine: 'claude', installed: true),
+ ]);
+ return notifier;
+ }
+
+ test('a box closed mid-create still hands its files on', () async {
+ final notifier = app();
+ final problems = <String>[];
+ final files = HarnessAttachments(onDeliveryProblem: problems.add)
+ ..add([HarnessAttachment('shot.png', Uint8List(4))]);
+ final box = NewHarnessController(
+ notifier,
+ machineId: 'box',
+ engine: 'claude',
+ folder: '/work/desk',
+ task: 'đọc ảnh',
+ attachments: files,
+ );
+ notifier.duringCreate = box.dispose;
+ await box.create();
+ // The task waits for the files instead of launching with the engine.
+ expect(notifier.prompts, [null]);
+ // Past the disposed box, the files step ran: this fake reports no agent
+ // id, which is the one outcome a test can see without a machine.
+ expect(problems.single, contains('without its files'));
+ });
+
+ test('without files the task still launches with the engine', () async {
+ final notifier = app();
+ final box = NewHarnessController(
+ notifier,
+ machineId: 'box',
+ engine: 'claude',
+ folder: '/work/desk',
+ task: 'đọc ảnh',
+ attachments: HarnessAttachments(),
+ );
+ addTearDown(box.dispose);
+ await box.create();
+ expect(notifier.prompts, ['đọc ảnh']);
+ });
+
+ test('a machine that cannot paste files refuses before creating', () async {
+ final notifier = app(canPasteFiles: false);
+ final box = NewHarnessController(
+ notifier,
+ machineId: 'box',
+ engine: 'claude',
+ folder: '/work/desk',
+ task: 'đọc ảnh',
+ attachments: HarnessAttachments()
+ ..add([HarnessAttachment('shot.png', Uint8List(4))]),
+ );
+ addTearDown(box.dispose);
+ await box.create();
+ expect(notifier.prompts, isEmpty);
+ expect(box.error, contains('to attach files'));
+ });
+}
diff --git a/desktop/test/web/web_app_menu_test.dart b/desktop/test/web/web_app_menu_test.dart
index 67d781824..8c0d5c3ba 100644
--- a/desktop/test/web/web_app_menu_test.dart
+++ b/desktop/test/web/web_app_menu_test.dart
@@ -16,6 +16,7 @@ import 'package:harness/web/shell/web_workspace.dart';
import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_switcher.dart';
import 'package:harness/widgets/workspace_bar_control.dart';
+import 'package:harness/widgets/workspace_machine_prompt.dart';
Future<AppNotifier> _mount(
WidgetTester tester, {
@@ -75,21 +76,25 @@ void main() {
app.dispose();
});
- testWidgets('New harness opens the form on a connected machine', (
+ testWidgets('an empty tab opens New harness on a connected machine', (
tester,
) async {
// The app opens New Harness in the box; tests default to the old form.
newHarnessOpensInBox = true;
addTearDown(() => newHarnessOpensInBox = false);
final app = await _mount(tester, connectedMachine: 'remote-box');
- // New work starts where a new tab opens: its "Start an agent" row.
- await tester.tap(find.byKey(const ValueKey('welcome-agent.new')));
+ // A browser is never a machine: the connected one is where it starts,
+ // with no "Choose a machine" step in between.
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 200)),
);
await tester.pump(const Duration(milliseconds: 400));
+ await tester.pump();
+ expect(find.byType(WorkspaceMachinePrompt), findsNothing);
expect(find.byType(NewHarnessForm), findsOneWidget);
- expect(find.byType(SwarmSearchResults), findsNothing);
+ // The browser attaches files to a new harness; desktop's box has no 📎.
+ expect(find.byKey(const ValueKey('new-harness-attach')), findsOneWidget);
+ expect(find.byKey(const ValueKey('new-harness-drop')), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink());
app.dispose();