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(mobile): fork a harness from its terminal menu, under a receipt as desktop does

tony543e13a91b81
diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dart
index cf7033df7..4687444e0 100644
--- a/mobile/lib/core/models.dart
+++ b/mobile/lib/core/models.dart
@@ -226,6 +226,10 @@ class Agent {
/// agent, so the new agent is given the same freedom when its engine has that mode.
final String? permissionMode;
+ /// Whether its machine can fork it (`agent_fork`), as the frame says; null from a daemon older
+ /// than the field — then [forkableEngines] decides. The desktop's `Agent.forkable`.
+ final bool? forkable;
+
const Agent({
required this.id,
this.sessionId,
@@ -258,6 +262,7 @@ class Agent {
this.createdAt,
this.closeSupported = false,
this.permissionMode,
+ this.forkable,
});
factory Agent.fromJson(Map<String, dynamic> j) {
@@ -330,6 +335,7 @@ class Agent {
createdAt: _safeTime(j['createdAt']),
closeSupported: j['closeSupported'] == true,
permissionMode: _safePermissionMode(j['permissionMode']),
+ forkable: j['forkable'] is bool ? j['forkable'] as bool : null,
);
}
@@ -365,8 +371,19 @@ class Agent {
createdAt: createdAt,
closeSupported: closeSupported,
permissionMode: permissionMode,
+ forkable: forkable,
);
+ /// The engines whose sessions can be forked — natively (Claude Code's `--fork-session`,
+ /// `codex fork`) or by a handoff message (OpenCode takes a first prompt). The answer for a
+ /// daemon that does not say ([forkable]); the desktop's list.
+ static const forkableEngines = {'claude', 'codex', 'opencode'};
+
+ /// Whether to offer Fork for this agent at all — the desktop's rule. Devin, Cursor, a terminal
+ /// and the rest can neither fork nor open with a message, so the row is not drawn rather than
+ /// drawn and refused.
+ bool get canFork => forkable ?? forkableEngines.contains(engine);
+
/// Saved work the daemon is no longer running, as the desktop's [Agent] reads
/// it. Its conversation is on disk; `agent_resume` brings it back.
///
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 8050f23a0..e5c462651 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -38,6 +38,7 @@ import 'package:harness_mobile/core/agent_handoff.dart'
show supportsAgentHandoff;
import 'package:harness_mobile/widgets/engine_identity.dart'
show engineIdentity;
+import 'package:harness_mobile/widgets/fork_agent_dialog.dart';
import 'package:harness_mobile/widgets/rename_agent_dialog.dart';
import 'package:harness_mobile/widgets/terminal_panel.dart';
@@ -2929,6 +2930,16 @@ class _TerminalPageState extends State<TerminalPage>
chevron: !_changing,
onTap: () => unawaited(_changeAgent(agent)),
),
+ // A second harness that starts with this one's conversation, in the same folder — the
+ // desktop's Fork Harness. Only where the machine can fork it, and not on saved work: a stopped
+ // harness is reopened, not forked.
+ if (agent.canFork && !agent.isStopped)
+ PhoneSheetAction(
+ icon: LucideIcons.gitFork300,
+ label: 'Fork…',
+ value: _forking ? 'forking…' : null,
+ onTap: () => unawaited(_fork()),
+ ),
PhoneSheetAction(
icon: LucideIcons.pencil300,
label: 'Rename…',
@@ -2962,6 +2973,63 @@ class _TerminalPageState extends State<TerminalPage>
bool get _changing =>
widget.notifier.agentChanging(widget.machineId, widget.agentId);
+ /// Whether a fork of this agent is on its way — see [AppNotifier.agentForking].
+ bool get _forking =>
+ widget.notifier.agentForking(widget.machineId, widget.agentId);
+
+ /// Fork: the form, then the fork opens — the source stays as it is, in the same tab.
+ ///
+ /// ⚠️ **A fork outlives its form.** Closed while the fork is still out, the form says it carries
+ /// on, so its answer is still said here when it lands — and the fork offered to open rather
+ /// than opened over whatever the person went on to.
+ Future<void> _fork() async {
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ final shell = PhoneShellScope.maybeOf(context);
+ final notifier = widget.notifier;
+ final machineId = widget.machineId;
+ final result = await showForkAgentDialog(
+ context,
+ notifier,
+ machineId,
+ widget.agentId,
+ );
+ if (result == null) {
+ final pending = notifier.forkPending(machineId, widget.agentId);
+ if (pending == null) return;
+ final landed = await pending;
+ final opened = landed.agentId;
+ // A menu opened in the wait would cover the answer — see [_putMenuAway].
+ if (mounted) _putMenuAway();
+ messenger?.showSnackBar(
+ SnackBar(
+ content: Text(landed.error ?? landed.notice ?? 'Fork created.'),
+ action: landed.error != null || opened == null
+ ? null
+ : SnackBarAction(
+ label: 'Open',
+ onPressed: () => mounted
+ ? openAgent(context, notifier, machineId, opened)
+ : shell?.onOpenAgent(machineId, opened),
+ ),
+ ),
+ );
+ return;
+ }
+ final said =
+ result.notice ??
+ (result.level == 'handoff'
+ ? 'Fork opened with a handoff summary of the source conversation.'
+ : null);
+ if (said != null) messenger?.showSnackBar(SnackBar(content: Text(said)));
+ final next = result.agentId;
+ if (next == null) return;
+ if (mounted) {
+ openAgent(context, notifier, machineId, next);
+ } else {
+ shell?.onOpenAgent(machineId, next);
+ }
+ }
+
/// Change agent: pick the engine, and the harness goes on there with the conversation handed
/// over — then the new one opens in place of this one. See [AppNotifier.changeAgent].
///
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 910d4215c..6bf25cd85 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -13,6 +13,8 @@ import 'dart:math' show Random;
import 'package:dio/dio.dart';
import 'package:xterm/xterm.dart' show RemoteScrollMemory, Terminal;
import 'package:flutter/foundation.dart';
+// The 80-character limit on a fork's name counts what a person sees, as the desktop's does.
+import 'package:flutter/widgets.dart' show StringCharacters;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/api_client.dart';
@@ -112,6 +114,67 @@ class AgentChangeResult {
const AgentChangeResult({this.error, this.agentId, this.notice});
}
+/// What became of a Fork ([AppNotifier.forkAgent]) — the desktop's `ForkAgentResult`.
+///
+/// [error] is a sentence to show as it is. Without it [agentId] is the fork to open now, and
+/// [level] says what it got: `native` (the engine's own fork, the whole context) or `handoff` (a
+/// first message composed from what the machine remembers of the source, for an engine that cannot
+/// fork). [notice], when set, is a line to say once it is open.
+class ForkAgentResult {
+ final String? error;
+ final String level;
+ final String? agentId;
+ final String? notice;
+
+ const ForkAgentResult({
+ this.error,
+ this.level = 'native',
+ this.agentId,
+ this.notice,
+ });
+}
+
+/// The Fork form's draft and its one deliberate fork — the desktop's `AgentForkAttempt`.
+///
+/// ⚠️ **Kept while the form is closed, receipt and all.** A fork starts a process, and its reply can
+/// be lost: then the attempt is locked on its choices until Check status asks `agent_create_status`
+/// about the SAME `creationId`, or the person explicitly starts another
+/// ([AppNotifier.discardForkAttempt]). Reopening the form while it is on its way joins it.
+class AgentForkAttempt {
+ AgentForkAttempt._(
+ this._machine,
+ this.source,
+ this._authRevision, {
+ this.name = '',
+ this.prompt = '',
+ });
+
+ /// The machine as it was when the form opened: a fork belongs to that connection.
+ final MachineState? _machine;
+
+ /// The agent as it was when the form opened. A fork is sent only while the machine still lists
+ /// this one — same id, same conversation.
+ final Agent? source;
+ final int _authRevision;
+
+ /// What the form holds: the fork's name and its first task.
+ String name, prompt;
+ String? _id;
+ bool _awaitingConfirmation = false;
+ Future<ForkAgentResult>? _inFlight;
+
+ /// The last answer, so the form opened again says what the last one ended on.
+ ForkAgentResult? result;
+
+ /// The fork was sent and its outcome is not known: Check status, not Fork.
+ bool get awaitingConfirmation => _awaitingConfirmation;
+ bool get busy => _inFlight != null;
+
+ /// The form's choices are held — while it is on its way, and while its outcome is unknown.
+ bool get locked => busy || awaitingConfirmation;
+ Future<ForkAgentResult>? get pending => _inFlight;
+}
+
/// One deliberate creation, retained by the form if its reply is lost. Reusing
/// it checks the original request; opening New agent starts a fresh intent.
/// The id a lifecycle request is checked by when its reply is lost — see `agent_create_status`.
@@ -7316,6 +7379,291 @@ class AppNotifier extends ChangeNotifier {
_ => 'Restart failed: $code',
};
+ /// Fork's attempts, by machine and source agent — see [AgentForkAttempt] for why one outlives
+ /// its form.
+ final Map<(String, String), AgentForkAttempt> _agentForks = {};
+
+ /// Whether a fork of this agent is on its way: the terminal menu's Fork row says so, as Restart
+ /// does.
+ bool agentForking(String machineId, String agentId) =>
+ forkPending(machineId, agentId) != null;
+
+ /// The fork of this agent on its way, if one is — what the terminal page waits on once the
+ /// form closed before it landed.
+ Future<ForkAgentResult>? forkPending(String machineId, String agentId) =>
+ _agentForks[(machineId, agentId)]?.pending;
+
+ /// Whether the attempt's source is still the agent its machine lists — the same connection, the
+ /// same id and the same conversation.
+ bool _forkSourceCurrent(AgentForkAttempt attempt) {
+ final machine = attempt._machine;
+ final source = attempt.source;
+ if (machine == null ||
+ source == null ||
+ !_machineWorkCurrent(machine, attempt._authRevision)) {
+ return false;
+ }
+ final current = machine.agents
+ .where((agent) => agent.id == source.id)
+ .firstOrNull;
+ return current != null && current.sessionId == source.sessionId;
+ }
+
+ /// The Fork form's attempt for [agentId]: the one already held while its source is unchanged or
+ /// its outcome is still to be checked, else a new one starting from [name] and [prompt].
+ AgentForkAttempt forkAttempt(
+ String machineId,
+ String agentId, {
+ String name = '',
+ String prompt = '',
+ }) {
+ final existing = _agentForks[(machineId, agentId)];
+ if (existing != null &&
+ (_forkSourceCurrent(existing) ||
+ (existing.locked &&
+ existing._machine != null &&
+ _machineWorkCurrent(
+ existing._machine,
+ existing._authRevision,
+ )))) {
+ return existing;
+ }
+ final machine = machineStates[machineId];
+ final source = machine?.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ return _agentForks[(machineId, agentId)] = AgentForkAttempt._(
+ machine,
+ source,
+ _authRevision,
+ name: name,
+ prompt: prompt,
+ );
+ }
+
+ /// Lets an unconfirmed fork go — only the form's explicit Start another fork does this, and
+ /// never while it is on its way. False when [attempt] is not the one held.
+ bool discardForkAttempt(
+ String machineId,
+ String agentId,
+ AgentForkAttempt attempt,
+ ) {
+ if (attempt.busy ||
+ !identical(_agentForks[(machineId, agentId)], attempt)) {
+ return false;
+ }
+ _agentForks.remove((machineId, agentId));
+ return true;
+ }
+
+ /// Fork: a NEW harness that starts with everything [agentId]'s conversation has, in the same
+ /// project folder — the desktop's `forkAgent`. The source is not touched, not even paused, which
+ /// is why it has to be idle (`cli/src/core/agents/fork.ts`).
+ ///
+ /// One fork per agent at a time: asking again while one is on its way joins it, and once its
+ /// outcome is unknown the same attempt checks it (`agent_create_status`) rather than sending a
+ /// second `agent_fork`.
+ Future<ForkAgentResult> forkAgent(
+ String machineId,
+ String agentId, {
+ AgentForkAttempt? attempt,
+ }) {
+ final operation = attempt ?? forkAttempt(machineId, agentId);
+ if (operation.result case final result?
+ when result.error == null && result.agentId != null) {
+ return Future.value(result);
+ }
+ if (operation.pending case final pending?) return pending;
+ late final Future<ForkAgentResult> request;
+ request = _runAgentFork(machineId, agentId, operation)
+ .then((result) {
+ operation.result = result;
+ return result;
+ })
+ .whenComplete(() {
+ if (identical(operation._inFlight, request)) {
+ operation._inFlight = null;
+ }
+ if (!_disposed && _authWorkCurrent(operation._authRevision)) {
+ notifyListeners();
+ }
+ });
+ operation._inFlight = request;
+ notifyListeners();
+ return request;
+ }
+
+ /// The steps of [forkAgent], in the desktop's order and words.
+ Future<ForkAgentResult> _runAgentFork(
+ String machineId,
+ String agentId,
+ AgentForkAttempt attempt,
+ ) async {
+ final machine = attempt._machine;
+ if (machine == null) {
+ return const ForkAgentResult(error: 'Machine not found');
+ }
+ if (machine.machine.machineId != machineId ||
+ attempt.source?.id != agentId) {
+ return const ForkAgentResult(
+ error: 'The source harness is no longer available.',
+ );
+ }
+ if (!_machineWorkCurrent(machine, attempt._authRevision)) {
+ return const ForkAgentResult(
+ error: 'This fork is no longer active. Reopen Fork Harness.',
+ );
+ }
+ if (!attempt.awaitingConfirmation) {
+ if (!_forkSourceCurrent(attempt)) {
+ return const ForkAgentResult(
+ error: 'The source harness changed. Close this prompt and reopen Fork Harness.',
+ );
+ }
+ if (attempt.source?.canFork != true) {
+ return const ForkAgentResult(
+ error: 'This harness does not support forking.',
+ );
+ }
+ if (agentIsProcessing(machineId, agentId)) {
+ return const ForkAgentResult(
+ error: 'This harness is working. Wait for its turn to finish, then fork.',
+ );
+ }
+ if (attempt.name.characters.length > 80) {
+ return const ForkAgentResult(
+ error: 'Use at most 80 characters for the name.',
+ );
+ }
+ if (attempt.prompt.length > 2000) {
+ return const ForkAgentResult(
+ error: 'Use at most 2000 characters for the first task.',
+ );
+ }
+ attempt._id = _newReceiptId();
+ }
+ final checking = attempt.awaitingConfirmation;
+ attempt._awaitingConfirmation = true;
+ const unknown = ForkAgentResult(
+ error: 'The fork is not confirmed yet. Check status, or look for it in Find before starting another.',
+ );
+ Map<String, dynamic> result;
+ try {
+ result = await _conn(machineId).request(
+ checking ? 'agent_create_status' : 'agent_fork',
+ payload: {
+ 'creationId': attempt._id,
+ if (!checking) ...{
+ 'agentId': agentId,
+ if (attempt.name.trim().isNotEmpty) 'name': attempt.name.trim(),
+ if (attempt.prompt.trim().isNotEmpty) 'prompt': attempt.prompt,
+ },
+ },
+ timeout: checking
+ ? const Duration(seconds: 10)
+ : const Duration(seconds: 20),
+ );
+ } on WsRequestFailure catch (failure) {
+ // Refusals before anything started are safe to correct. These cannot prove nothing did, and
+ // no answer to a status check can.
+ if (checking ||
+ const {
+ 'INTERNAL',
+ 'CREATION_STORAGE_FAILED',
+ 'SPAWN_FAILED',
+ 'REGISTRATION_FAILED',
+ }.contains(failure.code)) {
+ return unknown;
+ }
+ attempt._awaitingConfirmation = false;
+ return ForkAgentResult(error: _forkFailure(failure.code, failure.detail));
+ } catch (_) {
+ // Disconnects, timeouts and malformed replies: not evidence that the machine did nothing.
+ return unknown;
+ }
+ if (_disposed || !_machineWorkCurrent(machine, attempt._authRevision)) {
+ return const ForkAgentResult(
+ error: 'The machine changed while forking. Check its harnesses after reconnecting.',
+ );
+ }
+ if ((checking ||
+ result.containsKey('creationId') ||
+ result.containsKey('state')) &&
+ result['creationId'] != attempt._id) {
+ return unknown;
+ }
+ switch (result['state']) {
+ case 'pending':
+ return const ForkAgentResult(
+ error: 'The machine is still starting the fork. Check again in a moment.',
+ );
+ case 'missing':
+ case 'unconfirmed':
+ return unknown;
+ case 'unavailable':
+ attempt._awaitingConfirmation = false;
+ return const ForkAgentResult(
+ error: 'The fork was created but is no longer available. You can start another.',
+ );
+ case 'failed':
+ final failure = result['failure'];
+ if (failure is! Map || failure['code'] is! String) return unknown;
+ attempt._awaitingConfirmation = false;
+ return ForkAgentResult(
+ error: _forkFailure(failure['code'] as String, failure['detail']),
+ );
+ case 'created':
+ case null: // A first answer from a machine predating receipts.
+ break;
+ default:
+ return unknown;
+ }
+ final raw = result['agent'];
+ if (raw is! Map ||
+ raw['id'] is! String ||
+ (raw['id'] as String).isEmpty ||
+ raw['id'] == agentId) {
+ return unknown;
+ }
+ final Map<String, dynamic> json;
+ final Agent fork;
+ try {
+ json = Map<String, dynamic>.from(raw);
+ fork = Agent.fromJson(json);
+ } catch (_) {
+ return unknown;
+ }
+ attempt._awaitingConfirmation = false;
+ if (identical(_agentForks[(machineId, agentId)], attempt)) {
+ _agentForks.remove((machineId, agentId));
+ }
+ _upsertAgent(machine, fork, json: json);
+ // Into the tab the phone is in — the source's, since Fork is asked from its terminal — the way
+ // the desktop places a fork beside its source.
+ _desk.adopt((
+ machineId: machineId,
+ agentId: fork.id,
+ ), name: fork.displayName);
+ notifyListeners();
+ return ForkAgentResult(
+ level: result['level'] == 'handoff' ? 'handoff' : 'native',
+ agentId: fork.id,
+ );
+ }
+
+ /// The desktop's `_forkFailure`: the machine's own [detail] when it sends one, else a sentence
+ /// for the code.
+ String _forkFailure(String code, Object? detail) =>
+ detail is String && detail.isNotEmpty
+ ? detail
+ : switch (code) {
+ 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
+ 'Update the harness CLI on this machine to fork a harness.',
+ 'AGENT_BUSY' =>
+ 'This harness is working. Wait for its turn to finish, then fork.',
+ _ => 'Fork failed: $code',
+ };
+
/// Change agent's switches, by machine and agent — see [_AgentChange] for why one outlives a
/// failed step.
final Map<(String, String), _AgentChange> _agentChanges = {};
diff --git a/mobile/lib/widgets/fork_agent_dialog.dart b/mobile/lib/widgets/fork_agent_dialog.dart
new file mode 100644
index 000000000..6e6de01df
--- /dev/null
+++ b/mobile/lib/widgets/fork_agent_dialog.dart
@@ -0,0 +1,418 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../state/app_state.dart';
+import 'engine_identity.dart';
+
+/// The name a fork is offered: the source's, marked as a fork — the desktop's `forkNameFor`.
+String forkNameFor(String name) =>
+ '${name.trim().isEmpty ? 'Harness' : name.trim()} - fork';
+
+/// Fork Harness: the desktop's prompt, laid out as the phone's rename card — a name, an optional
+/// first task, and Fork.
+///
+/// Returns the fork once it exists, to open; null when the dialog was closed first. A fork still on
+/// its way when it closes carries on — [AppNotifier.forkAgent] holds it, and the same attempt's
+/// [AgentForkAttempt.pending] says when it lands.
+Future<ForkAgentResult?> showForkAgentDialog(
+ BuildContext context,
+ AppNotifier notifier,
+ String machineId,
+ String agentId,
+) => showAppDialog<ForkAgentResult>(
+ context: context,
+ builder: (_) =>
+ _ForkDialog(notifier: notifier, machineId: machineId, agentId: agentId),
+);
+
+class _ForkDialog extends StatefulWidget {
+ const _ForkDialog({
+ required this.notifier,
+ required this.machineId,
+ required this.agentId,
+ });
+
+ final AppNotifier notifier;
+ final String machineId, agentId;
+
+ @override
+ State<_ForkDialog> createState() => _ForkDialogState();
+}
+
+class _ForkDialogState extends State<_ForkDialog> {
+ late AgentForkAttempt _attempt;
+ final _name = TextEditingController();
+ final _task = TextEditingController();
+ final _nameFocus = FocusNode(debugLabel: 'Fork name');
+ final _taskFocus = FocusNode(debugLabel: 'Fork task');
+
+ /// A fork is on its way: Fork spins, and nothing sends a second one behind it.
+ bool _busy = false;
+ String? _error;
+
+ /// The fields are held while the fork is out or its outcome unknown: an edit then would be a
+ /// fork nobody sent.
+ bool get _locked => _busy || _attempt.awaitingConfirmation;
+
+ @override
+ void initState() {
+ super.initState();
+ final source = widget.notifier
+ .stateOf(widget.machineId)
+ ?.agents
+ .where((agent) => agent.id == widget.agentId)
+ .firstOrNull;
+ _attempt = widget.notifier.forkAttempt(
+ widget.machineId,
+ widget.agentId,
+ name: forkNameFor(source?.displayName ?? ''),
+ );
+ _name.text = _attempt.name;
+ _task.text = _attempt.prompt;
+ _error = _attempt.result?.error;
+ _nameFocus.addListener(_refocus);
+ _taskFocus.addListener(_refocus);
+ // Reopened while the fork is still out: wait for that one, never send another.
+ if (_attempt.pending case final pending?) {
+ _busy = true;
+ unawaited(_finish(pending));
+ }
+ }
+
+ @override
+ void dispose() {
+ _nameFocus.removeListener(_refocus);
+ _taskFocus.removeListener(_refocus);
+ _nameFocus.dispose();
+ _taskFocus.dispose();
+ _name.dispose();
+ _task.dispose();
+ super.dispose();
+ }
+
+ void _refocus() {
+ if (mounted) setState(() {});
+ }
+
+ /// An edit is the draft, kept on the attempt so the form opened again still has it, and it takes
+ /// back the last refusal — that was about choices no longer there.
+ void _changed(String _) {
+ if (_locked) return;
+ _attempt.name = _name.text;
+ _attempt.prompt = _task.text;
+ _attempt.result = null;
+ setState(() => _error = null);
+ }
+
+ void _submit() {
+ if (_busy) return;
+ if (!_attempt.awaitingConfirmation) {
+ if (_name.text.trim().isEmpty) {
+ setState(() => _error = 'Name cannot be empty');
+ _nameFocus.requestFocus();
+ return;
+ }
+ if (_name.text.characters.length > 80) {
+ setState(() => _error = 'Use at most 80 characters for the name.');
+ _nameFocus.requestFocus();
+ return;
+ }
+ }
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ unawaited(
+ _finish(
+ widget.notifier.forkAgent(
+ widget.machineId,
+ widget.agentId,
+ attempt: _attempt,
+ ),
+ ),
+ );
+ }
+
+ Future<void> _finish(Future<ForkAgentResult> request) async {
+ ForkAgentResult result;
+ try {
+ result = await request;
+ } catch (_) {
+ result = const ForkAgentResult(
+ error: 'Could not confirm the fork. Check harnesses before starting another.',
+ );
+ }
+ // Only a route still in the navigator is this dialog's to close — see the rename dialog's
+ // `_submit` for the fade that made `mounted` alone pop the page under it.
+ if (!mounted || !(ModalRoute.of(context)?.isActive ?? false)) return;
+ if (result.error == null) {
+ Navigator.of(context).pop(result);
+ return;
+ }
+ setState(() {
+ _busy = false;
+ _error = result.error;
+ });
+ }
+
+ /// The explicit way past an unconfirmed fork: a new attempt with the same draft, said to be one.
+ void _startAnother() {
+ if (!widget.notifier.discardForkAttempt(
+ widget.machineId,
+ widget.agentId,
+ _attempt,
+ )) {
+ return;
+ }
+ _attempt = widget.notifier.forkAttempt(
+ widget.machineId,
+ widget.agentId,
+ name: _name.text,
+ prompt: _task.text,
+ );
+ setState(
+ () => _error =
+ 'The previous fork may already exist. Confirm to start another.',
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final danger = Theme.of(context).colorScheme.error;
+ final uncertain = _attempt.awaitingConfirmation;
+ final source = _attempt.source;
+ final machine = widget.notifier
+ .stateOf(widget.machineId)
+ ?.machine
+ .displayName;
+ final error = _error;
+ return Dialog(
+ insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
+ child: Semantics(
+ scopesRoute: true,
+ namesRoute: true,
+ explicitChildNodes: true,
+ label: 'Fork Harness',
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 360),
+ // Scrolls rather than overflows: with the keyboard up a short phone has less room than
+ // two fields and their lines ask for.
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(20),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ if (source != null) ...[
+ SizedBox.square(
+ dimension: 32,
+ child: Center(
+ child: EngineMark(
+ engine: source.engine,
+ displayName: source.engineDisplayName,
+ size: 32,
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ ],
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'Fork Harness',
+ style: TextStyle(
+ color: grid.AppPalette.textPrimary,
+ fontSize: 17,
+ fontWeight: grid.AppFont.semibold,
+ ),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ [
+ 'From ${source?.displayName ?? 'harness'}',
+ ?machine,
+ ].join(' · '),
+ key: const Key('fork-source'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: _muted,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 10),
+ Text(
+ source?.engine == 'opencode'
+ ? 'Starts from a handoff summary, in the same project folder.'
+ : 'Continues the conversation in the same project folder.',
+ style: _muted,
+ ),
+ const SizedBox(height: 16),
+ _field(
+ key: const Key('fork-name'),
+ controller: _name,
+ focus: _nameFocus,
+ hint: 'Name',
+ autofocus: true,
+ action: TextInputAction.next,
+ onSubmitted: (_) => _taskFocus.requestFocus(),
+ danger: error != null && !uncertain ? danger : null,
+ ),
+ const SizedBox(height: 10),
+ _field(
+ key: const Key('fork-task'),
+ controller: _task,
+ focus: _taskFocus,
+ hint: 'First task (optional)',
+ maxLines: 4,
+ action: TextInputAction.newline,
+ ),
+ if (error != null)
+ Semantics(
+ liveRegion: true,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(2, 10, 2, 0),
+ child: Text(
+ error,
+ key: const Key('fork-error'),
+ style: TextStyle(
+ color: uncertain ? grid.AppPalette.warn : danger,
+ fontSize: 13,
+ height: 1.35,
+ ),
+ ),
+ ),
+ ),
+ if (uncertain && !_busy)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton(
+ key: const Key('fork-start-another'),
+ onPressed: _startAnother,
+ child: const Text('Start another fork'),
+ ),
+ ),
+ if (_busy)
+ Padding(
+ padding: const EdgeInsets.only(top: 10),
+ child: Text(
+ 'Forking continues if you close this dialog.',
+ style: _muted,
+ ),
+ ),
+ const SizedBox(height: 20),
+ _actions(uncertain: uncertain),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ TextStyle get _muted =>
+ TextStyle(color: grid.AppPalette.textSecondary, fontSize: 13);
+
+ Widget _field({
+ required Key key,
+ required TextEditingController controller,
+ required FocusNode focus,
+ required String hint,
+ required TextInputAction action,
+ bool autofocus = false,
+ int maxLines = 1,
+ ValueChanged<String>? onSubmitted,
+ Color? danger,
+ }) {
+ final accent = grid.AppPalette.accent;
+ OutlineInputBorder border(Color color, {double width = 1}) =>
+ OutlineInputBorder(
+ borderRadius: BorderRadius.circular(kDialogControlRadius),
+ borderSide: BorderSide(color: color, width: width),
+ );
+ return TextField(
+ key: key,
+ controller: controller,
+ focusNode: focus,
+ autofocus: autofocus,
+ readOnly: _locked,
+ minLines: 1,
+ maxLines: maxLines,
+ textInputAction: action,
+ inputFormatters: [LengthLimitingTextInputFormatter(2000)],
+ style: grid.kFieldTextStyle.copyWith(fontSize: 16),
+ onChanged: _changed,
+ onSubmitted: onSubmitted,
+ decoration: InputDecoration(
+ hintText: hint,
+ hintStyle: TextStyle(color: grid.AppPalette.textFaint, fontSize: 16),
+ filled: true,
+ fillColor: grid.AppPalette.panelBg,
+ isDense: true,
+ contentPadding: const EdgeInsets.fromLTRB(14, 14, 14, 14),
+ border: border(danger ?? grid.AppGlass.hair),
+ enabledBorder: border(danger ?? grid.AppGlass.hair),
+ focusedBorder: border(danger ?? accent, width: 1.5),
+ ),
+ );
+ }
+
+ /// Cancel (Close once a fork is out) and Fork (Check status once its outcome is unknown), half
+ /// the width each — the rename card's pair.
+ Widget _actions({required bool uncertain}) {
+ final accent = grid.AppPalette.accent;
+ return Row(
+ children: [
+ Expanded(
+ child: FilledButton(
+ key: const Key('fork-cancel'),
+ style: appDialogButtonStyle(
+ background: grid.AppSurface.recess,
+ foreground: grid.AppPalette.textPrimary,
+ ),
+ onPressed: () => Navigator.of(context).pop(),
+ child: Text(_locked ? 'Close' : 'Cancel'),
+ ),
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: FilledButton(
+ key: const Key('fork-confirm'),
+ style: appDialogButtonStyle(
+ background: accent,
+ foreground: Colors.white,
+ // Full colour while it spins: the press was taken.
+ disabledBackground: accent,
+ disabledForeground: Colors.white,
+ ),
+ onPressed: _busy ? null : _submit,
+ child: _busy
+ ? Semantics(
+ label: 'Waiting for fork…',
+ child: SizedBox.square(
+ dimension: 18,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: Colors.white,
+ backgroundColor: Colors.white.withValues(alpha: 0.35),
+ ),
+ ),
+ )
+ : Text(uncertain ? 'Check status' : 'Fork'),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dart
index 37a1d0e94..8a7c5a881 100644
--- a/mobile/test/phone_edge/focus_behavior_test.dart
+++ b/mobile/test/phone_edge/focus_behavior_test.dart
@@ -451,6 +451,198 @@ void main() {
await focus.close();
});
+ /// A machine that forks what it is asked to, as `f`, echoing the receipt — or, with [failure],
+ /// records the fork as refused for that reason.
+ EdgeConn forking({Map<String, dynamic>? failure}) => EdgeConn(
+ const {},
+ (type, payload) => type != 'agent_fork'
+ ? null
+ : failure != null
+ ? {
+ 'creationId': payload['creationId'],
+ 'state': 'failed',
+ 'failure': failure,
+ }
+ : {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'level': 'native',
+ 'agent': {
+ 'id': 'f',
+ 'name': payload['name'] ?? 'f',
+ 'engine': 'claude',
+ 'terminal': {'available': true},
+ },
+ },
+ )..handshaken = true;
+
+ testWidgets('Fork is offered where the machine can fork, and not on a '
+ 'terminal', (tester) async {
+ var focus = await openMenu(tester);
+ expect(find.text('Fork…'), findsOneWidget);
+ await focus.close();
+
+ focus = await openMenu(tester, engine: 'terminal');
+ expect(find.text('Fork…'), findsNothing);
+ await focus.close();
+ });
+
+ testWidgets('Fork: the desktop’s form, named after the source, then the '
+ 'fork opens and the source is left as it was', (tester) async {
+ final conn = forking();
+ final focus = await openMenu(tester, connection: conn);
+ await tapInView(tester, find.text('Fork…'));
+ await frames(tester);
+
+ expect(find.text('Fork Harness'), findsOneWidget);
+ expect(
+ find.text('Continues the conversation in the same project folder.'),
+ findsOneWidget,
+ );
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const Key('fork-name')))
+ .controller!
+ .text,
+ 'a - fork',
+ );
+ await tester.enterText(
+ find.byKey(const Key('fork-task')),
+ 'Try the other approach',
+ );
+ await tester.tap(find.byKey(const Key('fork-confirm')));
+ for (var i = 0; i < 40 && focus.opened.isEmpty; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+
+ final [sent] = conn.payloads['agent_fork']!;
+ expect(sent['agentId'], 'a');
+ expect(sent['name'], 'a - fork');
+ expect(sent['prompt'], 'Try the other approach');
+ expect(focus.opened, [('m', 'f')]);
+ await frames(tester);
+ expect(find.text('Fork Harness'), findsNothing, reason: 'the form went');
+ expect(
+ conn.requests,
+ isNot(contains('agent_close')),
+ reason: 'the source is not touched',
+ );
+ await focus.close();
+ });
+
+ testWidgets('Fork the machine refuses says why in the form, and opens '
+ 'nothing', (tester) async {
+ final conn = forking(
+ failure: {
+ 'code': 'AGENT_BUSY',
+ 'detail': 'a is in the middle of a turn.',
+ },
+ );
+ final focus = await openMenu(tester, connection: conn);
+ await tapInView(tester, find.text('Fork…'));
+ await frames(tester);
+ await tester.tap(find.byKey(const Key('fork-confirm')));
+ await frames(tester);
+
+ expect(find.text('a is in the middle of a turn.'), findsOneWidget);
+ expect(find.text('Fork'), findsOneWidget, reason: 'can be sent again');
+ expect(focus.opened, isEmpty);
+ await focus.close();
+ });
+
+ testWidgets('Fork with no name is not sent', (tester) async {
+ final conn = forking();
+ final focus = await openMenu(tester, connection: conn);
+ await tapInView(tester, find.text('Fork…'));
+ await frames(tester);
+ await tester.enterText(find.byKey(const Key('fork-name')), ' ');
+ await tester.tap(find.byKey(const Key('fork-confirm')));
+ await frames(tester);
+
+ expect(find.text('Name cannot be empty'), findsOneWidget);
+ expect(conn.payloads['agent_fork'], isNull);
+ await focus.close();
+ });
+
+ // The form's own fields raise the keyboard, and on a small phone it takes most of the screen:
+ // the form scrolls inside what is left rather than overflowing, and Fork stays in reach.
+ testWidgets('Fork’s form under the keyboard on a small phone still reaches '
+ 'Fork', (tester) async {
+ final conn = forking();
+ final focus = await openMenu(tester, connection: conn);
+ setPhone(tester, smallPhone);
+ await frames(tester);
+ await tapInView(tester, find.text('Fork…'));
+ await frames(tester);
+ raiseKeyboard(tester);
+ await frames(tester);
+ expect(tester.takeException(), isNull, reason: 'no overflow');
+
+ final confirm = find.byKey(const Key('fork-confirm'));
+ await tester.ensureVisible(confirm);
+ await tester.pump();
+ final bottom = tester.getRect(confirm).bottom;
+ expect(
+ bottom,
+ lessThanOrEqualTo(smallPhone.size.height - smallPhone.keyboard),
+ reason: 'above the keyboard',
+ );
+ await tester.tap(confirm);
+ for (var i = 0; i < 40 && focus.opened.isEmpty; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ expect(focus.opened, [('m', 'f')]);
+ lowerKeyboard(tester);
+ await frames(tester);
+ await focus.close();
+ });
+
+ testWidgets('Fork closed while it is on its way carries on, says so when '
+ 'it lands, and offers the fork', (tester) async {
+ final reply = Completer<Map<String, dynamic>>();
+ final forkConn = _HeldForkConn(reply.future)..handshaken = true;
+ final focus = await openMenu(tester, connection: forkConn);
+ await tapInView(tester, find.text('Fork…'));
+ await frames(tester);
+ await tester.tap(find.byKey(const Key('fork-confirm')));
+ await frames(tester);
+ expect(
+ find.text('Forking continues if you close this dialog.'),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('fork-cancel')));
+ await frames(tester);
+ expect(find.text('Fork Harness'), findsNothing);
+
+ // The menu says so while it is out, and goes when the answer lands under it.
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ expect(find.text('forking…'), findsOneWidget);
+
+ reply.complete({
+ 'creationId': forkConn.receipt,
+ 'state': 'created',
+ 'agent': {
+ 'id': 'f',
+ 'name': 'a - fork',
+ 'engine': 'claude',
+ 'terminal': {'available': true},
+ },
+ });
+ await frames(tester);
+ expect(find.text('forking…'), findsNothing, reason: 'the menu went');
+ expect(find.text('Fork created.'), findsOneWidget);
+ expect(
+ focus.opened,
+ isEmpty,
+ reason: 'offered, not opened over the page',
+ );
+ await tester.tap(find.text('Open'));
+ await frames(tester);
+ expect(focus.opened, [('m', 'f')]);
+ await focus.close();
+ });
+
/// A harness its machine can save and stop — what Change agent needs of one.
Agent switchable() => Agent(
id: 'a',
@@ -2293,6 +2485,31 @@ class _SwitchConn extends EdgeConn {
}
}
+/// A machine whose `agent_fork` answers only when [reply] does — a fork still on its way.
+class _HeldForkConn extends EdgeConn {
+ _HeldForkConn(this.reply);
+
+ final Future<Map<String, dynamic>> reply;
+
+ /// The receipt the fork was sent under, for the answer to echo.
+ String? get receipt =>
+ payloads['agent_fork']?.single['creationId'] as String?;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type != 'agent_fork') {
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+ requests.add(type);
+ (payloads[type] ??= []).add(payload);
+ return reply;
+ }
+}
+
class _Pushes extends NavigatorObserver {
_Pushes(this.pushed);
diff --git a/mobile/test/state/fork_agent_test.dart b/mobile/test/state/fork_agent_test.dart
new file mode 100644
index 000000000..31c353f6c
--- /dev/null
+++ b/mobile/test/state/fork_agent_test.dart
@@ -0,0 +1,311 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+import '../viewer_app_fixture.dart';
+
+/// Fork from the phone: a second harness that starts with another one's conversation, in the
+/// same folder — the desktop's Fork Harness. What the machine is asked, and that a lost reply is
+/// checked under the same receipt rather than answered with a second fork.
+void main() {
+ /// A signed-in phone whose machine `m` lists [agents] and forks the way a current machine does.
+ Future<ViewerRig> rigWith(List<Map<String, dynamic>> agents) async {
+ final rig = viewerApp();
+ rig.api.onMachines = () async => [remoteMachine('m')];
+ final answers = rig.conn('m').answers;
+ answers['agents_list'] = (_) => {'agents': agents};
+ answers['terminal_capabilities'] = (_) => capabilities();
+ answers['agent_fork'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'created',
+ 'level': 'native',
+ 'agent': agentJson('f', name: p['name'] as String?),
+ };
+ await rig.app.bootstrap();
+ await settle();
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+ await settle();
+ addTearDown(rig.app.dispose);
+ return rig;
+ }
+
+ Agent? agentOf(ViewerRig rig, String id) =>
+ rig.app.stateOf('m')?.agents.where((a) => a.id == id).firstOrNull;
+
+ group('what can be forked', () {
+ test('the machine says; an older one leaves it to the engine', () {
+ Agent agent(String engine, [Object? forkable]) => Agent.fromJson(
+ agentJson('a', engine: engine, extra: {'forkable': ?forkable}),
+ );
+ expect(agent('claude').canFork, isTrue);
+ expect(agent('codex').canFork, isTrue);
+ expect(agent('opencode').canFork, isTrue);
+ expect(agent('terminal').canFork, isFalse);
+ expect(agent('cursor').canFork, isFalse);
+ expect(agent('claude', false).canFork, isFalse, reason: 'it said no');
+ expect(agent('devin', true).canFork, isTrue, reason: 'it said yes');
+ expect(agent('claude', 'yes').canFork, isTrue, reason: 'not a bool');
+ });
+ });
+
+ test('forks under a receipt with the name and first task, and the fork '
+ 'joins the machine’s list', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ final attempt = rig.app.forkAttempt('m', 'a', name: 'a - fork');
+ attempt.prompt = 'Try the other approach';
+
+ final result = await rig.app.forkAgent('m', 'a', attempt: attempt);
+
+ expect(result.error, isNull);
+ expect(result.agentId, 'f');
+ expect(result.level, 'native');
+ final [sent] = rig.conn('m').payloadsOf('agent_fork');
+ expect(sent['agentId'], 'a');
+ expect(sent['name'], 'a - fork');
+ expect(sent['prompt'], 'Try the other approach');
+ expect(sent['creationId'], isA<String>());
+ expect((sent['creationId'] as String).length, 32);
+ expect(agentOf(rig, 'f')?.name, 'a - fork');
+ expect(rig.app.agentForking('m', 'a'), isFalse);
+ });
+
+ test('an empty first task and a blank name are left out', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ final attempt = rig.app.forkAttempt('m', 'a', name: ' ');
+ attempt.prompt = ' ';
+
+ await rig.app.forkAgent('m', 'a', attempt: attempt);
+
+ final [sent] = rig.conn('m').payloadsOf('agent_fork');
+ expect(sent.keys.toSet(), {'creationId', 'agentId'});
+ });
+
+ test('a handoff fork says so', () async {
+ final rig = await rigWith([agentJson('a', engine: 'opencode')]);
+ rig.conn('m').answers['agent_fork'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'created',
+ 'level': 'handoff',
+ 'agent': agentJson('f', engine: 'opencode'),
+ };
+
+ final result = await rig.app.forkAgent('m', 'a');
+
+ expect(result.level, 'handoff');
+ expect(result.agentId, 'f');
+ });
+
+ test('asking again while one is on its way joins it', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ final reply = Completer<Map<String, dynamic>>();
+ rig.conn('m').answers['agent_fork'] = (_) => reply.future;
+
+ final first = rig.app.forkAgent('m', 'a');
+ final second = rig.app.forkAgent('m', 'a');
+ expect(rig.app.agentForking('m', 'a'), isTrue);
+ expect(rig.app.forkPending('m', 'a'), isNotNull);
+ final [sent] = rig.conn('m').payloadsOf('agent_fork');
+ reply.complete({
+ 'creationId': sent['creationId'],
+ 'state': 'created',
+ 'agent': agentJson('f'),
+ });
+
+ expect((await first).agentId, 'f');
+ expect((await second).agentId, 'f');
+ expect(rig.conn('m').payloadsOf('agent_fork'), hasLength(1));
+ expect(rig.app.agentForking('m', 'a'), isFalse);
+ });
+
+ test('a lost reply is checked under the same receipt, never forked '
+ 'again', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ final conn = rig.conn('m');
+ conn.answers['agent_fork'] = (_) =>
+ throw const WsRequestTimeout('agent_fork');
+ final attempt = rig.app.forkAttempt('m', 'a');
+
+ final lost = await rig.app.forkAgent('m', 'a', attempt: attempt);
+ expect(lost.error, contains('not confirmed yet'));
+ expect(attempt.awaitingConfirmation, isTrue);
+ expect(attempt.locked, isTrue);
+ expect(
+ identical(rig.app.forkAttempt('m', 'a'), attempt),
+ isTrue,
+ reason: 'the form opened again holds the same fork',
+ );
+
+ final receipt = conn.payloadsOf('agent_fork').single['creationId'];
+ conn.answers['agent_create_status'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'created',
+ 'agent': agentJson('f'),
+ };
+ final checked = await rig.app.forkAgent('m', 'a', attempt: attempt);
+
+ expect(checked.error, isNull);
+ expect(checked.agentId, 'f');
+ expect(conn.payloadsOf('agent_fork'), hasLength(1));
+ expect(conn.payloadsOf('agent_create_status'), [
+ {'creationId': receipt},
+ ]);
+ expect(agentOf(rig, 'f'), isNotNull);
+ });
+
+ test('a refusal before anything started can be corrected and sent '
+ 'again', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ final conn = rig.conn('m');
+ conn.answers['agent_fork'] = (_) => throw refusal('PROMPT_TOO_LONG');
+ final attempt = rig.app.forkAttempt('m', 'a');
+
+ final refused = await rig.app.forkAgent('m', 'a', attempt: attempt);
+ expect(refused.error, 'Fork failed: PROMPT_TOO_LONG');
+ expect(attempt.awaitingConfirmation, isFalse);
+
+ conn.answers['agent_fork'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'created',
+ 'agent': agentJson('f'),
+ };
+ final sent = await rig.app.forkAgent('m', 'a', attempt: attempt);
+ expect(sent.agentId, 'f');
+ expect(conn.payloadsOf('agent_fork'), hasLength(2));
+ });
+
+ test('a refusal that cannot prove nothing started stays to be '
+ 'checked', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ rig.conn('m').answers['agent_fork'] = (_) => throw refusal('INTERNAL');
+ final attempt = rig.app.forkAttempt('m', 'a');
+
+ final result = await rig.app.forkAgent('m', 'a', attempt: attempt);
+
+ expect(result.error, contains('not confirmed yet'));
+ expect(attempt.awaitingConfirmation, isTrue);
+ });
+
+ test('the machine’s own sentence wins, and a recorded failure ends the '
+ 'attempt', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ rig.conn('m').answers['agent_fork'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'AGENT_BUSY',
+ 'detail': 'a is in the middle of a turn.',
+ },
+ };
+ final attempt = rig.app.forkAttempt('m', 'a');
+
+ final result = await rig.app.forkAgent('m', 'a', attempt: attempt);
+
+ expect(result.error, 'a is in the middle of a turn.');
+ expect(attempt.awaitingConfirmation, isFalse);
+ });
+
+ test('an answer for another receipt is not taken as this fork', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ rig.conn('m').answers['agent_fork'] = (_) => {
+ 'creationId': 'someone-else',
+ 'state': 'created',
+ 'agent': agentJson('f'),
+ };
+
+ final result = await rig.app.forkAgent('m', 'a');
+
+ expect(result.error, contains('not confirmed yet'));
+ expect(agentOf(rig, 'f'), isNull);
+ });
+
+ test('a fork that names its source back is not a fork', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ rig.conn('m').answers['agent_fork'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'created',
+ 'agent': agentJson('a'),
+ };
+
+ final result = await rig.app.forkAgent('m', 'a');
+
+ expect(result.agentId, isNull);
+ expect(result.error, contains('not confirmed yet'));
+ });
+
+ test('a harness mid-turn is not forked, and nothing is sent', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ await push(rig, 'm', 'turn_started', {'agentId': 'a'});
+
+ final result = await rig.app.forkAgent('m', 'a');
+
+ expect(
+ result.error,
+ 'This harness is working. Wait for its turn to finish, then fork.',
+ );
+ expect(rig.conn('m').payloadsOf('agent_fork'), isEmpty);
+ });
+
+ test('an engine that cannot fork is refused here', () async {
+ final rig = await rigWith([agentJson('a', engine: 'terminal')]);
+
+ final result = await rig.app.forkAgent('m', 'a');
+
+ expect(result.error, 'This harness does not support forking.');
+ expect(rig.conn('m').payloadsOf('agent_fork'), isEmpty);
+ });
+
+ test('a source that changed conversation since the form opened is not '
+ 'forked', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ final attempt = rig.app.forkAttempt('m', 'a');
+ rig.conn('m').answers['agents_list'] = (_) => {
+ 'agents': [agentJson('a', sessionId: 's2')],
+ };
+ await rig.app.syncAgentsForTest('m');
+ await settle();
+
+ final result = await rig.app.forkAgent('m', 'a', attempt: attempt);
+
+ expect(result.error, contains('The source harness changed.'));
+ expect(rig.conn('m').payloadsOf('agent_fork'), isEmpty);
+ });
+
+ test('names and first tasks over the limits are refused before '
+ 'sending', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ final named = rig.app.forkAttempt('m', 'a', name: 'n' * 81);
+ expect(
+ (await rig.app.forkAgent('m', 'a', attempt: named)).error,
+ 'Use at most 80 characters for the name.',
+ );
+ named.name = 'ok';
+ named.prompt = 'p' * 2001;
+ expect(
+ (await rig.app.forkAgent('m', 'a', attempt: named)).error,
+ 'Use at most 2000 characters for the first task.',
+ );
+ expect(rig.conn('m').payloadsOf('agent_fork'), isEmpty);
+ });
+
+ test('only an idle, held attempt can be let go', () async {
+ final rig = await rigWith([agentJson('a', sessionId: 's1')]);
+ final reply = Completer<Map<String, dynamic>>();
+ rig.conn('m').answers['agent_fork'] = (_) => reply.future;
+ final attempt = rig.app.forkAttempt('m', 'a');
+
+ final pending = rig.app.forkAgent('m', 'a', attempt: attempt);
+ expect(rig.app.discardForkAttempt('m', 'a', attempt), isFalse);
+ reply.completeError(const WsRequestTimeout('agent_fork'));
+ await pending;
+
+ expect(rig.app.discardForkAttempt('m', 'a', attempt), isTrue);
+ expect(identical(rig.app.forkAttempt('m', 'a'), attempt), isFalse);
+ expect(
+ rig.app.discardForkAttempt('m', 'a', attempt),
+ isFalse,
+ reason: 'no longer the one held',
+ );
+ });
+}