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): stop a harness once it finishes its task, or keep it running

tony3f4809a6df6b
diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dart
index 9bddcbcaa..89febe194 100644
--- a/mobile/lib/core/models.dart
+++ b/mobile/lib/core/models.dart
@@ -238,6 +238,15 @@ class Agent {
/// frame), or null for a general session. Read by Clone, so another opens as the same one.
final String? namedAgent;
+ /// A Stop its machine holds until the agent finishes what it is doing (`agent_close` with
+ /// `after_task`): `waiting` while it waits, `failed` when the close it then tried did not go
+ /// through. Null with no Stop queued, or from a daemon older than the field. The desktop's
+ /// `Agent.closePlanState`; opening the agent again calls the queued Stop off (CLI agents/update.ts).
+ final String? closePlanState;
+
+ /// What the machine said about a queued Stop that failed — already a sentence.
+ final String? closePlanDetail;
+
const Agent({
required this.id,
this.sessionId,
@@ -273,6 +282,8 @@ class Agent {
this.forkable,
this.bypassPermission,
this.namedAgent,
+ this.closePlanState,
+ this.closePlanDetail,
});
factory Agent.fromJson(Map<String, dynamic> j) {
@@ -350,10 +361,23 @@ class Agent {
? j['bypassPermission'] as bool
: null,
namedAgent: _safeNamedAgent(j['namedAgent']),
+ closePlanState:
+ j['closePlan'] is Map &&
+ const {'waiting', 'failed'}.contains(j['closePlan']['state'])
+ ? j['closePlan']['state'] as String
+ : null,
+ closePlanDetail: j['closePlan'] is Map
+ ? _safeDetail(j['closePlan']['detail'])
+ : null,
);
}
- Agent copyWith({String? name, AgentGitContext? gitContext}) => Agent(
+ Agent copyWith({
+ String? name,
+ AgentGitContext? gitContext,
+ String? closePlanState,
+ bool clearClosePlan = false,
+ }) => Agent(
id: id,
sessionId: sessionId,
name: name ?? this.name,
@@ -388,6 +412,12 @@ class Agent {
forkable: forkable,
bypassPermission: bypassPermission,
namedAgent: namedAgent,
+ closePlanState: clearClosePlan
+ ? null
+ : closePlanState ?? this.closePlanState,
+ closePlanDetail: clearClosePlan || closePlanState != null
+ ? null
+ : closePlanDetail,
);
/// The engines whose sessions can be forked — natively (Claude Code's `--fork-session`,
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 3fd340b76..f61a9afac 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -2658,11 +2658,21 @@ class _TerminalPageState extends State<TerminalPage>
away:
machineAway && (session?.hasScreen ?? false),
onTap: () {
- if (agent == null) return;
+ // The agent as it is NOW, not as this build read it: a fact the
+ // page does not rebuild for (a Stop queued for after it finishes)
+ // still has to be right in the menu that opens.
+ final current =
+ widget.notifier
+ .stateOf(widget.machineId)
+ ?.agents
+ .where((a) => a.id == widget.agentId)
+ .firstOrNull ??
+ agent;
+ if (current == null) return;
_showActions(
machineName:
machine?.machine.displayName ?? '',
- agent: agent,
+ agent: current,
session: session,
);
},
@@ -2926,6 +2936,11 @@ class _TerminalPageState extends State<TerminalPage>
),
PhoneSheetSection(
actions: [
+ // Above Stop while it works: stopping once it is done, rather than mid-task — and,
+ // once queued, the way to call it off.
+ if (AppNotifier.canStopAfterTask(agent) &&
+ (agent.closePlanState == 'waiting' || _agentWorking))
+ _stopAfterAction(agent),
_stopAction(agent),
// Stop's harder sibling, under it: the conversation goes too. Not for a terminal,
// which keeps none.
@@ -3316,6 +3331,44 @@ class _TerminalPageState extends State<TerminalPage>
),
);
+ /// Stop after it finishes, or — with one queued — Keep running. See [AppNotifier.stopAfterTask].
+ /// Quiet at the foot like Stop; a queued Stop is said in the row itself, the desktop's words
+ /// for it, since a quiet row draws no value.
+ PhoneSheetAction _stopAfterAction(Agent agent) {
+ final queued = agent.closePlanState == 'waiting';
+ final pending = widget.notifier.agentClosePlanPending(
+ widget.machineId,
+ widget.agentId,
+ );
+ return PhoneSheetAction(
+ icon: queued ? LucideIcons.play300 : LucideIcons.timerOff300,
+ label: queued
+ ? 'Stops after finishing · Keep running'
+ : 'Stop after it finishes',
+ enabled: !pending,
+ destructive: !queued,
+ quiet: true,
+ onTap: () => unawaited(_stopAfter(queued: queued)),
+ );
+ }
+
+ /// What the queued Stop came to, said once its machine has answered — on the snackbar, as
+ /// Restart's answer is.
+ Future<void> _stopAfter({required bool queued}) async {
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ final error = queued
+ ? await widget.notifier.keepRunning(widget.machineId, widget.agentId)
+ : await widget.notifier.stopAfterTask(widget.machineId, widget.agentId);
+ if (mounted) _putMenuAway();
+ messenger?.showSnackBar(
+ SnackBar(
+ content: Text(
+ error ?? (queued ? 'Keeps running.' : 'Stops after it finishes.'),
+ ),
+ ),
+ );
+ }
+
/// Delete Harness — see [confirmPurgeAgent]. Small at the foot beside Stop, and saying so while a
/// delete is out, as Restart does: the review and the delete can take a while. In its label, in
/// the desktop's word for it — a quiet row draws no value.
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index a4088abe1..e2ea71d69 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -7148,6 +7148,116 @@ class AppNotifier extends ChangeNotifier {
return null;
}
+ /// Queued Stops on their way to the machine, by machine and agent — what a second press joins.
+ final Map<(String, String), Future<String?>> _closePlanRequests = {};
+
+ /// Whether a Stop after it finishes, or calling one off, is on its way for this agent.
+ bool agentClosePlanPending(String machineId, String agentId) =>
+ _closePlanRequests.containsKey((machineId, agentId));
+
+ /// Whether this agent can be stopped once it finishes: its machine closes harnesses on request
+ /// (`agent_close`), and it has a conversation to finish — a shell never reads as idle, so its
+ /// Stop would wait forever.
+ static bool canStopAfterTask(Agent agent) =>
+ agent.closeSupported &&
+ agent.createdAt != null &&
+ agent.engine != 'terminal' &&
+ !agent.isStopped;
+
+ /// Stop after it finishes: the machine waits for the agent to be idle, then saves and stops it
+ /// (`agent_close`, `after_task`) — what the desktop's close does with a session still working.
+ /// Its conversation is kept, as Stop's is. Null once the machine has queued it, else the
+ /// sentence to show.
+ Future<String?> stopAfterTask(String machineId, String agentId) =>
+ _requestClosePlan(machineId, agentId, 'after_task');
+
+ /// Keep running: the queued Stop called off (`agent_close`, `cancel`).
+ Future<String?> keepRunning(String machineId, String agentId) =>
+ _requestClosePlan(machineId, agentId, 'cancel');
+
+ Future<String?> _requestClosePlan(
+ String machineId,
+ String agentId,
+ String mode,
+ ) {
+ final key = (machineId, agentId);
+ if (_closePlanRequests[key] case final pending?) return pending;
+ final request = _sendClosePlan(machineId, agentId, mode).whenComplete(() {
+ _closePlanRequests.remove(key);
+ if (!_disposed) notifyListeners();
+ });
+ _closePlanRequests[key] = request;
+ notifyListeners();
+ return request;
+ }
+
+ Future<String?> _sendClosePlan(
+ String machineId,
+ String agentId,
+ String mode,
+ ) async {
+ final machine = machineStates[machineId];
+ final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
+ if (machine == null || agent == null) {
+ return 'This harness is no longer available.';
+ }
+ if (!canStopAfterTask(agent)) {
+ return 'Update the Harness CLI on this machine to stop a harness once it finishes.';
+ }
+ final revision = _authRevision;
+ final Map<String, dynamic> result;
+ try {
+ result = await _conn(machineId).request(
+ 'agent_close',
+ payload: {
+ 'agentId': agent.id,
+ 'sessionId': agent.sessionId ?? '',
+ 'createdAt': agent.createdAt!.toUtc().toIso8601String(),
+ 'mode': mode,
+ },
+ timeout: const Duration(seconds: 15),
+ );
+ } on WsRequestFailure catch (failure) {
+ if (failure.code == 'AGENT_CHANGED') {
+ return 'The harness changed. Open its menu again.';
+ }
+ final detail = failure.detail;
+ return detail != null && detail.isNotEmpty
+ ? detail
+ : mode == 'cancel'
+ ? 'Could not keep it running: ${failure.code}'
+ : 'Could not queue the stop: ${failure.code}';
+ } catch (_) {
+ // A lost reply is not a refusal: the machine may have queued it. Its frame says which once
+ // the agents are read again, and the row follows that.
+ unawaited(reloadMachineData(machineId));
+ return mode == 'cancel'
+ ? 'Could not confirm it keeps running. Check its menu again in a moment.'
+ : 'Could not confirm the stop is queued. Check its menu again in a moment.';
+ }
+ final done = mode == 'cancel'
+ ? result['cancelled'] == true
+ : result['deferred'] == true || result['closed'] == true;
+ if (!done) {
+ final detail = result['detail'];
+ return detail is String && detail.isNotEmpty
+ ? detail
+ : 'The machine did not confirm it. Check its menu again in a moment.';
+ }
+ // The machine's push says the same in a moment; the menu reads it now.
+ if (!_disposed && _machineWorkCurrent(machine, revision)) {
+ final index = machine.agents.indexWhere((a) => a.id == agentId);
+ if (index != -1 && result['closed'] != true) {
+ machine.agents = [...machine.agents]
+ ..[index] = mode == 'cancel'
+ ? machine.agents[index].copyWith(clearClosePlan: true)
+ : machine.agents[index].copyWith(closePlanState: 'waiting');
+ notifyListeners();
+ }
+ }
+ return null;
+ }
+
/// Tells the machine that owns an agent it was just opened here, so it can stamp
/// `lastOpenedAt` and every app — this phone, each desktop — sorts by the same
/// last use. Fire and forget: a daemon too old to keep the stamp answers
@@ -7161,7 +7271,14 @@ class AppNotifier extends ChangeNotifier {
final key = '$machineId/$agentId';
final now = DateTime.now();
final last = _touchedAt[key];
- if (last != null && now.difference(last) < _touchEvery) return;
+ // A Stop queued for after it finishes is called off by opening the agent again (CLI
+ // agents/update.ts), so that open is never coalesced away — the desktop's rule.
+ final queuedStop = machine.agents.any(
+ (agent) => agent.id == agentId && agent.closePlanState != null,
+ );
+ if (!queuedStop && last != null && now.difference(last) < _touchEvery) {
+ return;
+ }
_touchedAt[key] = now;
final revision = _authRevision;
unawaited(() async {
diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dart
index be2184867..7fad45f51 100644
--- a/mobile/test/phone_edge/focus_behavior_test.dart
+++ b/mobile/test/phone_edge/focus_behavior_test.dart
@@ -879,6 +879,62 @@ void main() {
_PurgeConn(review ?? Future.value({'reviewId': 'review-1'}))
..handshaken = true;
+ testWidgets('while it works: Stop after it finishes queues the stop, and '
+ 'the menu then offers to keep it running', (tester) async {
+ final conn = EdgeConn(const {}, (type, payload) {
+ if (type != 'agent_close') return null;
+ return payload['mode'] == 'cancel'
+ ? {'cancelled': true}
+ : {'deferred': true};
+ })..handshaken = true;
+ final focus = await _Focus.open(
+ tester,
+ agents: [switchable()],
+ connection: conn,
+ );
+ focus.app.stateOf('m')!.processingAgentIds.add('a');
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+
+ await tapInView(tester, find.text('Stop after it finishes'));
+ await frames(tester);
+ expect(conn.payloads['agent_close']!.single['mode'], 'after_task');
+ expect(find.text('Stops after it finishes.'), findsOneWidget);
+
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ expect(find.text('Stop after it finishes'), findsNothing);
+ await tapInView(
+ tester,
+ find.text('Stops after finishing · Keep running'),
+ );
+ await frames(tester);
+ expect(conn.payloads['agent_close']!.last['mode'], 'cancel');
+ // Behind the first answer's snackbar, which has its few seconds first.
+ await tester.pump(const Duration(seconds: 5));
+ await frames(tester);
+ expect(find.text('Keeps running.'), findsOneWidget);
+ await focus.close();
+ });
+
+ testWidgets('idle, or a shell, has no stop to queue — Stop is the '
+ 'answer', (tester) async {
+ var focus = await _Focus.open(tester, agents: [switchable()]);
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ expect(find.text('Stop after it finishes'), findsNothing);
+ expect(find.text('Stop this harness…'), findsOneWidget);
+ await focus.close();
+
+ focus = await openMenu(tester, working: true);
+ expect(
+ find.text('Stop after it finishes'),
+ findsNothing,
+ reason: 'its machine cannot close it',
+ );
+ await focus.close();
+ });
+
testWidgets('Delete is offered beside Stop, and not on a terminal', (
tester,
) async {
diff --git a/mobile/test/state/stop_after_task_test.dart b/mobile/test/state/stop_after_task_test.dart
new file mode 100644
index 000000000..3d7301ee3
--- /dev/null
+++ b/mobile/test/state/stop_after_task_test.dart
@@ -0,0 +1,204 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+import '../viewer_app_fixture.dart';
+
+/// Stop after it finishes, from the phone: the machine waits for the agent to be idle, then saves
+/// and stops it (`agent_close`, `after_task`) — and Keep running calls that off (`cancel`).
+void main() {
+ const created = '2026-10-16T01:00:00.000Z';
+
+ Map<String, dynamic> source({
+ String engine = 'claude',
+ bool closeSupported = true,
+ Object? closePlan,
+ }) => agentJson(
+ 'a',
+ engine: engine,
+ sessionId: 's1',
+ extra: {
+ 'createdAt': created,
+ 'closeSupported': closeSupported,
+ 'closePlan': ?closePlan,
+ },
+ );
+
+ 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_close'] = (p) =>
+ p['mode'] == 'cancel' ? {'cancelled': true} : {'deferred': true};
+ await rig.app.bootstrap();
+ await settle();
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+ await settle();
+ addTearDown(rig.app.dispose);
+ return rig;
+ }
+
+ Agent agent(ViewerRig rig) =>
+ rig.app.stateOf('m')!.agents.singleWhere((a) => a.id == 'a');
+
+ group('the frame', () {
+ test('says what became of a queued stop', () {
+ Agent read(Object? plan) =>
+ Agent.fromJson(agentJson('a', extra: {'closePlan': ?plan}));
+ expect(read(null).closePlanState, isNull);
+ expect(read({'state': 'waiting'}).closePlanState, 'waiting');
+ final failed = read({'state': 'failed', 'detail': 'Could not save.'});
+ expect(failed.closePlanState, 'failed');
+ expect(failed.closePlanDetail, 'Could not save.');
+ expect(read({'state': 'weird'}).closePlanState, isNull);
+ expect(read('waiting').closePlanState, isNull);
+ });
+
+ test('a shell, or an agent its machine cannot close, has no stop to '
+ 'queue', () {
+ Agent read({String engine = 'claude', bool closeSupported = true}) =>
+ Agent.fromJson(
+ source(engine: engine, closeSupported: closeSupported),
+ );
+ expect(AppNotifier.canStopAfterTask(read()), isTrue);
+ expect(AppNotifier.canStopAfterTask(read(engine: 'terminal')), isFalse);
+ expect(
+ AppNotifier.canStopAfterTask(read(closeSupported: false)),
+ isFalse,
+ );
+ });
+ });
+
+ test('queues the stop under the agent’s exact identity, and the agent '
+ 'reads it at once', () async {
+ final rig = await rigWith([source()]);
+
+ expect(await rig.app.stopAfterTask('m', 'a'), isNull);
+
+ expect(rig.conn('m').payloadsOf('agent_close'), [
+ {
+ 'agentId': 'a',
+ 'sessionId': 's1',
+ 'createdAt': created,
+ 'mode': 'after_task',
+ },
+ ]);
+ expect(agent(rig).closePlanState, 'waiting');
+ expect(rig.app.agentClosePlanPending('m', 'a'), isFalse);
+ });
+
+ test('Keep running calls it off', () async {
+ final rig = await rigWith([
+ source(closePlan: {'state': 'waiting'}),
+ ]);
+ expect(agent(rig).closePlanState, 'waiting');
+
+ expect(await rig.app.keepRunning('m', 'a'), isNull);
+
+ expect(rig.conn('m').payloadsOf('agent_close').single['mode'], 'cancel');
+ expect(agent(rig).closePlanState, isNull);
+ });
+
+ test('nothing is asked of a machine that cannot close it', () async {
+ final rig = await rigWith([source(closeSupported: false)]);
+
+ expect(
+ await rig.app.stopAfterTask('m', 'a'),
+ 'Update the Harness CLI on this machine to stop a harness once it '
+ 'finishes.',
+ );
+ expect(rig.conn('m').payloadsOf('agent_close'), isEmpty);
+ });
+
+ test('a refusal says why, in the machine’s words when it has them', () async {
+ final rig = await rigWith([source()]);
+ final conn = rig.conn('m');
+ conn.answers['agent_close'] = (_) =>
+ throw refusal('AGENT_CHANGED', detail: 'changed');
+ expect(
+ await rig.app.stopAfterTask('m', 'a'),
+ 'The harness changed. Open its menu again.',
+ );
+
+ conn.answers['agent_close'] = (_) =>
+ throw refusal('CLOSE_FAILED', detail: 'The session is busy.');
+ expect(await rig.app.stopAfterTask('m', 'a'), 'The session is busy.');
+ expect(agent(rig).closePlanState, isNull);
+ });
+
+ test('a lost reply is not taken for either answer, and the agents are '
+ 'read again', () async {
+ final rig = await rigWith([source()]);
+ final conn = rig.conn('m');
+ conn.answers['agent_close'] = (_) =>
+ throw const WsRequestTimeout('agent_close');
+ final listsBefore = conn.payloadsOf('agents_list').length;
+
+ expect(
+ await rig.app.stopAfterTask('m', 'a'),
+ 'Could not confirm the stop is queued. Check its menu again in a '
+ 'moment.',
+ );
+ await settle();
+
+ expect(agent(rig).closePlanState, isNull);
+ expect(conn.payloadsOf('agents_list').length, greaterThan(listsBefore));
+ });
+
+ test('an answer that confirms nothing is not taken for one', () async {
+ final rig = await rigWith([source()]);
+ rig.conn('m').answers['agent_close'] = (_) => <String, dynamic>{};
+
+ expect(
+ await rig.app.stopAfterTask('m', 'a'),
+ 'The machine did not confirm it. Check its menu again in a moment.',
+ );
+ expect(agent(rig).closePlanState, isNull);
+ });
+
+ test('pressed again while it is out joins the first', () async {
+ final rig = await rigWith([source()]);
+ final reply = Completer<Map<String, dynamic>>();
+ rig.conn('m').answers['agent_close'] = (_) => reply.future;
+
+ final first = rig.app.stopAfterTask('m', 'a');
+ final second = rig.app.stopAfterTask('m', 'a');
+ expect(rig.app.agentClosePlanPending('m', 'a'), isTrue);
+ reply.complete({'deferred': true});
+
+ expect(await first, isNull);
+ expect(await second, isNull);
+ expect(rig.conn('m').payloadsOf('agent_close'), hasLength(1));
+ });
+
+ test('opening an agent with a queued stop always tells its machine — that '
+ 'is what calls it off', () async {
+ final rig = await rigWith([
+ source(closePlan: {'state': 'waiting'}),
+ agentJson('b'),
+ ]);
+ final conn = rig.conn('m');
+ List<Object?> opened() => [
+ for (final p in conn.payloadsOf('agent_update'))
+ if (p['opened'] == true) p['agentId'],
+ ];
+
+ rig.app.touchAgent('m', 'a');
+ rig.app.touchAgent('m', 'a');
+ rig.app.touchAgent('m', 'b');
+ rig.app.touchAgent('m', 'b');
+ await settle();
+
+ expect(opened().where((id) => id == 'a'), hasLength(2));
+ expect(
+ opened().where((id) => id == 'b'),
+ hasLength(1),
+ reason: 'still coalesced with nothing queued',
+ );
+ });
+}