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.

fix(mobile): restart once, and say how it came back

tony77001c8f0166
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 3276f6b98..8a5d2bba1 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -2866,13 +2866,24 @@ class _TerminalPageState extends State<TerminalPage>
agent.name,
),
),
+ // Still immediate, no question first — the desktop's rule too ("Restart is an immediate
+ // action"). While one runs it says so and takes no tap, the way Settings ▸ Computers' Try again
+ // reads `trying…`: a second press is a second restart (see `AppNotifier._agentRestarts`).
PhoneSheetAction(
icon: LucideIcons.refreshCw300,
label: 'Restart',
- onTap: () => unawaited(_restart()),
+ value: _restarting ? 'restarting…' : null,
+ enabled: !_restarting,
+ onTap: () => unawaited(_restart(agent)),
),
];
+ /// Whether this agent has a restart on its way — from this menu, or from Connectors. Read as the
+ /// menu opens, like the rest of its rows: a menu left open while the restart finishes still says
+ /// it, until it is opened again.
+ bool get _restarting =>
+ widget.notifier.agentRestarting(widget.machineId, widget.agentId);
+
/// Stopping the agent: the last card of its sheet, alone.
///
/// Alone and in red because everything above it is recoverable and this is not, so it does not
@@ -2945,15 +2956,26 @@ class _TerminalPageState extends State<TerminalPage>
/// Restarting is a round trip that can fail, and the phone has no status rail to fail into — so
/// the answer lands as a snackbar, which is the one surface a pushed page here always has.
- Future<void> _restart() async {
+ ///
+ /// Said only when there is something to say. A restart that came back on its own conversation
+ /// says nothing: the terminal shows it. One that came back on a NEW conversation says so, in the
+ /// desktop's words — the engine could not reopen the old one, which is kept as a stopped harness
+ /// (`cli/src/core/agents/restart.ts`), and an empty prompt is easily taken for the conversation
+ /// it replaced. Except on a terminal, which always restarts as a fresh shell (the desktop does not
+ /// say it there either). Anything else is [RestartAgentResult.error], already a sentence.
+ Future<void> _restart(Agent agent) async {
final messenger = ScaffoldMessenger.maybeOf(context);
final result = await widget.notifier.restartAgent(
widget.machineId,
widget.agentId,
);
- final error = result.error;
- if (error == null || messenger == null || !mounted) return;
- messenger.showSnackBar(SnackBar(content: Text(error)));
+ final said =
+ result.error ??
+ (result.resumed || agent.engine == 'terminal'
+ ? null
+ : 'Restarted with a new conversation.');
+ if (said == null || messenger == null || !mounted) return;
+ messenger.showSnackBar(SnackBar(content: Text(said)));
}
}
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 324f58e92..f5baa07f4 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -87,6 +87,9 @@ enum AgentLoadStatus { idle, needsLink, loading, loaded, error }
/// whether the daemon reattached the agent's prior session or fell back to a fresh one (e.g. the
/// engine's resume flag wasn't recognized) — worth telling the user about, since it's not a failure
/// but the conversation may not have continued the way "Restart" implies.
+///
+/// A non-null [error] is a sentence to show as it is, and not always a failure: a restart whose
+/// reply never came says it could not be confirmed (see `AppNotifier._restartUnconfirmed`).
class RestartAgentResult {
final String? error;
final bool resumed;
@@ -6922,13 +6925,6 @@ class AppNotifier extends ChangeNotifier {
return null;
}
- /// Restarts an agent via `agent_restart` — exits its current engine process and relaunches it
- /// daemon-side, resuming its session where possible.
- ///
- /// The reply carries the same fresh `Agent` shape `agent_synced` pushes once the new process is
- /// confirmed, so this upserts from the reply directly — idempotent on `agent.id`, same as
- /// [createAgent], and safe even if the CLI's own `agent_synced` push for the restart arrives
- /// separately (fire-and-forget on the CLI side, unordered relative to this reply).
/// Bring a stopped agent back, so something can be opened on it.
///
/// The desktop's `resumeAgent`: a thin guard over [restartAgent], which is the
@@ -7099,7 +7095,74 @@ class AppNotifier extends ChangeNotifier {
_ => 'Could not open this harness: $code',
};
- Future<RestartAgentResult> restartAgent(
+ /// Restarts on their way, by machine and agent ([restartAgent]) — the Restart row of the
+ /// terminal's menu says so while one runs ([agentRestarting]).
+ ///
+ /// ⚠️ **A second `agent_restart` is a second restart, not a duplicate.** The machine works
+ /// through what one connection sends in order, so a press that came while the first restart
+ /// ran — the menu opened again because nothing seemed to happen — waited behind it and then
+ /// replaced the engine that had only just come back, cutting it off as it started. So a restart
+ /// of an agent that already has one on its way joins that one and sends nothing; Connectors'
+ /// restart button guards itself the same way (`_restarting` in `connectors_page.dart`), and
+ /// joins here too.
+ final Map<(String, String), Future<RestartAgentResult>> _agentRestarts = {};
+
+ /// Whether a restart of this agent is on its way — see [_agentRestarts].
+ bool agentRestarting(String machineId, String agentId) =>
+ _agentRestarts.containsKey((machineId, agentId));
+
+ /// How long a restart's reply is waited for: longer than the machine can take to answer one.
+ ///
+ /// ⚠️ **Not the 20s every other request waits.** The machine answers once the new engine is up,
+ /// and getting there can take more than that: up to 5s asking the shell whether the engine is
+ /// still installed, up to 3s for the old process to go, up to 8s for the new one to show — and,
+ /// when the resumed one never shows, another 8s for a fresh one (`cli/src/core/agents/restart.ts`,
+ /// `swap.ts`). At 20s the phone gave up on a restart still running, said it had failed, and
+ /// offered Restart again — which would have restarted it a second time.
+ static const _restartReplyWait = Duration(seconds: 45);
+
+ /// What the phone says when it cannot know how a restart ended: the desktop's sentence for the
+ /// same case (`restart_agent_action.dart`), word for word.
+ ///
+ /// ⚠️ **Not knowing is not failing.** A reply that did not come in time, a socket that dropped
+ /// under the request, a machine that lost track of its own answer — in all of these the restart
+ /// may have happened, or may be happening still. "Restart failed" sent people to press Restart
+ /// again; this sends them to the terminal first, which shows what really happened.
+ static const _restartUnconfirmed =
+ 'Could not confirm the restart. Check the terminal before restarting again.';
+
+ /// Restarts an agent via `agent_restart` — exits its current engine process and relaunches it
+ /// daemon-side, resuming its session where possible.
+ ///
+ /// The reply carries the same fresh `Agent` shape `agent_synced` pushes once the new process is
+ /// confirmed, so this upserts from the reply directly — idempotent on `agent.id`, same as
+ /// [createAgent], and safe even if the CLI's own `agent_synced` push for the restart arrives
+ /// separately (fire-and-forget on the CLI side, unordered relative to this reply).
+ ///
+ /// A restart of an agent that already has one on its way returns that one's future and sends
+ /// nothing — see [_agentRestarts]. Listeners hear when one starts and when it ends.
+ ///
+ /// [RestartAgentResult.error] is a sentence to show as it is: why the machine refused, in the
+ /// desktop's words ([_restartRefused]), or [_restartUnconfirmed] when the outcome is not known.
+ Future<RestartAgentResult> restartAgent(String machineId, String agentId) {
+ final key = (machineId, agentId);
+ final inFlight = _agentRestarts[key];
+ if (inFlight != null) return inFlight;
+ // Answered before anything is held, so a machine that is not there never reads as restarting.
+ if (machineStates[machineId] == null) {
+ return Future.value(const RestartAgentResult(error: 'Machine not found'));
+ }
+ late final Future<RestartAgentResult> run;
+ run = _performRestartAgent(machineId, agentId).whenComplete(() {
+ if (identical(_agentRestarts[key], run)) _agentRestarts.remove(key);
+ if (!_disposed) notifyListeners();
+ });
+ _agentRestarts[key] = run;
+ notifyListeners();
+ return run;
+ }
+
+ Future<RestartAgentResult> _performRestartAgent(
String machineId,
String agentId,
) async {
@@ -7109,20 +7172,24 @@ class AppNotifier extends ChangeNotifier {
}
Map<String, dynamic> result;
try {
- result = await _conn(machineId)
- .request('agent_restart', payload: {'agentId': agentId});
- } catch (error) {
- return RestartAgentResult(error: 'Restart failed: $error');
- }
- final error = result['error'];
- if (error is String) {
- final detail = result['detail'];
- return RestartAgentResult(
- error: detail is String ? detail : 'Restart failed: $error',
+ result = await _conn(machineId).request(
+ 'agent_restart',
+ payload: {'agentId': agentId},
+ timeout: _restartReplyWait,
);
+ } on WsRequestFailure catch (failure) {
+ // How a refusal really arrives: the socket throws it rather than handing back the map.
+ return _restartRefused(failure.code, failure.detail);
+ } catch (_) {
+ // A timeout, a socket that dropped or could not send: no answer, so no outcome to report.
+ return const RestartAgentResult(error: _restartUnconfirmed);
}
+ final error = result['error'];
+ if (error is String) return _restartRefused(error, result['detail']);
final raw = result['agent'];
- if (raw is Map) {
+ // Not after the app let go of its state: with [_restartReplyWait] a reply can land long after
+ // the tap, and a disposed notifier cannot notify.
+ if (raw is Map && !_disposed) {
try {
final json = Map<String, dynamic>.from(raw);
_upsertAgent(machine, Agent.fromJson(json), json: json);
@@ -7137,6 +7204,41 @@ class AppNotifier extends ChangeNotifier {
return RestartAgentResult(resumed: resumed is bool ? resumed : true);
}
+ /// A restart the machine answered with an error code, as the desktop reads one
+ /// (`AppNotifier._runAgentRestart` there).
+ ///
+ /// ⚠️ **Three of the codes are not refusals.** `RESTART_FAILED` can follow a relaunch that did
+ /// happen but was not seen in time — the machine itself files it as "unconfirmed" when it keeps a
+ /// receipt (`cli/src/core/agents/launches.ts`) — and `INTERNAL` and `CREATION_STORAGE_FAILED`
+ /// say nothing about the pane at all. Telling those as a failure would invite the second restart
+ /// the terminal may not need; the desktop calls them unconfirmed, and so does this.
+ RestartAgentResult _restartRefused(String code, Object? detail) =>
+ const {
+ 'INTERNAL',
+ 'CREATION_STORAGE_FAILED',
+ 'RESTART_FAILED',
+ }.contains(code)
+ ? const RestartAgentResult(error: _restartUnconfirmed)
+ : RestartAgentResult(error: _restartFailure(code, detail));
+
+ /// The desktop's `_restartFailure` wording for a restart the machine refused: the machine's own
+ /// [detail] when it sends one — already a sentence (`That harness has already exited.`) — or a
+ /// sentence for the code.
+ ///
+ /// Not [_resumeFailure], which words the same codes for opening saved work.
+ String _restartFailure(String code, Object? detail) =>
+ detail is String && detail.isNotEmpty
+ ? detail
+ : switch (code) {
+ 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
+ 'Update the harness CLI on this machine to restart a harness.',
+ 'AGENT_BUSY' => 'Another operation is changing this harness. Wait for it to finish, then retry.',
+ 'RESUME_UNAVAILABLE' => 'The saved conversation is unavailable. The harness can still be started fresh.',
+ 'RESUME_SESSION_MISMATCH' => 'The harness came back on a different conversation. The saved one is still kept.',
+ 'RESUME_FAILED' => 'The harness did not come back. Its output and conversation are kept.',
+ _ => 'Restart failed: $code',
+ };
+
/// Live models on every harness grid this machine is signed into, for the
/// model sheet.
///
diff --git a/mobile/test/app_state_agent_rpcs_test.dart b/mobile/test/app_state_agent_rpcs_test.dart
index 5aaaeebce..426ef15cc 100644
--- a/mobile/test/app_state_agent_rpcs_test.dart
+++ b/mobile/test/app_state_agent_rpcs_test.dart
@@ -1002,6 +1002,10 @@ void main() {
});
group('stopping, renaming, restarting', () {
+ /// The desktop's sentence for a restart nobody can vouch for either way.
+ const restartUnconfirmed =
+ 'Could not confirm the restart. Check the terminal before restarting again.';
+
test('a stop takes the agent off the phone and out of its tab', () async {
final rig = await signedInWith({
'm': ['a', 'b'],
@@ -1154,11 +1158,9 @@ void main() {
(await rig.app.restartAgent('m', 'a')).error,
'Restart failed: NOPE',
);
+ // No answer is not a refusal: the restart may have happened (see the tests below).
rig.conn('m').answers['agent_restart'] = (_) => throw StateError('down');
- expect(
- (await rig.app.restartAgent('m', 'a')).error,
- startsWith('Restart failed'),
- );
+ expect((await rig.app.restartAgent('m', 'a')).error, restartUnconfirmed);
rig.conn('m').answers['agent_restart'] = (_) => {
'agent': {'bad': true},
};
@@ -1166,6 +1168,249 @@ void main() {
expect(odd.error, isNull);
expect(odd.resumed, isTrue, reason: 'absent reads as resumed');
});
+
+ // ⚠️ The machine works through one connection's requests in order, so a second
+ // `agent_restart` sent while the first runs is a second restart once the first is done — the
+ // engine that just came back is replaced again.
+ test('a second restart while one runs joins it, sending nothing', () async {
+ final rig = await signedInWith({
+ 'm': ['a'],
+ });
+ addTearDown(rig.app.dispose);
+ final reply = Completer<Map<String, dynamic>>();
+ rig.conn('m').answers['agent_restart'] = (_) => reply.future;
+
+ final first = rig.app.restartAgent('m', 'a');
+ final second = rig.app.restartAgent('m', 'a');
+ await settle();
+
+ expect(rig.conn('m').payloadsOf('agent_restart'), hasLength(1));
+ expect(identical(first, second), isTrue);
+
+ reply.complete({'agent': agentJson('a'), 'resumed': false});
+ final results = await Future.wait([first, second]);
+ expect([for (final result in results) result.resumed], [false, false]);
+ expect([for (final result in results) result.error], [null, null]);
+ expect(rig.conn('m').payloadsOf('agent_restart'), hasLength(1));
+ });
+
+ test('a restart on its way is told, and is over once it answers', () async {
+ final rig = await signedInWith({
+ 'm': ['a', 'b'],
+ });
+ addTearDown(rig.app.dispose);
+ final reply = Completer<Map<String, dynamic>>();
+ rig.conn('m').answers['agent_restart'] = (_) => reply.future;
+ var heard = 0;
+ rig.app.addListener(() => heard++);
+
+ final restart = rig.app.restartAgent('m', 'a');
+
+ expect(rig.app.agentRestarting('m', 'a'), isTrue);
+ expect(heard, isPositive, reason: 'the menu hears that it started');
+ expect(rig.app.agentRestarting('m', 'b'), isFalse);
+ expect(rig.app.agentRestarting('other', 'a'), isFalse);
+ final before = heard;
+
+ reply.complete({'resumed': true});
+ await restart;
+ await settle();
+
+ expect(rig.app.agentRestarting('m', 'a'), isFalse);
+ expect(heard, greaterThan(before), reason: 'and that it ended');
+ });
+
+ test('a machine that is not there is never restarting', () async {
+ final rig = await signedInWith({
+ 'm': ['a'],
+ });
+ addTearDown(rig.app.dispose);
+
+ final restart = rig.app.restartAgent('ghost', 'a');
+
+ expect(rig.app.agentRestarting('ghost', 'a'), isFalse);
+ expect((await restart).error, 'Machine not found');
+ });
+
+ test('a restart that ended — done, refused or unanswered — can be pressed '
+ 'again', () async {
+ final rig = await signedInWith({
+ 'm': ['a'],
+ });
+ addTearDown(rig.app.dispose);
+ final answers = rig.conn('m').answers;
+
+ answers['agent_restart'] = (_) => {'resumed': true};
+ expect((await rig.app.restartAgent('m', 'a')).error, isNull);
+ expect(rig.app.agentRestarting('m', 'a'), isFalse);
+
+ answers['agent_restart'] = (_) => throw refusal('AGENT_BUSY');
+ expect((await rig.app.restartAgent('m', 'a')).error, isNotNull);
+ expect(rig.app.agentRestarting('m', 'a'), isFalse);
+
+ answers['agent_restart'] = (_) =>
+ throw const WsRequestTimeout('agent_restart');
+ expect((await rig.app.restartAgent('m', 'a')).error, restartUnconfirmed);
+ expect(rig.app.agentRestarting('m', 'a'), isFalse);
+
+ answers['agent_restart'] = (_) => {'resumed': true};
+ expect((await rig.app.restartAgent('m', 'a')).error, isNull);
+ expect(
+ rig.conn('m').payloadsOf('agent_restart'),
+ hasLength(4),
+ reason: 'each one sent, none joined to one already over',
+ );
+ });
+
+ test('other agents, and the same agent on another machine, restart on '
+ 'their own', () async {
+ final rig = await signedInWith({
+ 'm': ['a', 'b'],
+ 'n': ['a'],
+ });
+ addTearDown(rig.app.dispose);
+ final reply = Completer<Map<String, dynamic>>();
+ rig.conn('m').answers['agent_restart'] = (_) => reply.future;
+ rig.conn('n').answers['agent_restart'] = (_) => reply.future;
+
+ final restarts = [
+ rig.app.restartAgent('m', 'a'),
+ rig.app.restartAgent('m', 'b'),
+ rig.app.restartAgent('n', 'a'),
+ ];
+ await settle();
+
+ expect(
+ [
+ for (final asked in rig.conn('m').payloadsOf('agent_restart'))
+ asked['agentId'],
+ ],
+ ['a', 'b'],
+ );
+ expect(rig.conn('n').payloadsOf('agent_restart'), hasLength(1));
+ expect(rig.app.agentRestarting('m', 'b'), isTrue);
+ expect(rig.app.agentRestarting('n', 'a'), isTrue);
+ reply.complete({'resumed': true});
+ await Future.wait(restarts);
+ });
+
+ test('a refused restart is told in the desktop\'s words, not as the '
+ 'socket\'s error', () async {
+ final rig = await signedInWith({
+ 'm': ['a'],
+ });
+ addTearDown(rig.app.dispose);
+ Future<String?> refusedWith(WsRequestFailure failure) async {
+ rig.conn('m').answers['agent_restart'] = (_) => throw failure;
+ return (await rig.app.restartAgent('m', 'a')).error;
+ }
+
+ expect(
+ await refusedWith(refusal('AGENT_BUSY')),
+ 'Another operation is changing this harness. Wait for it to finish, then retry.',
+ );
+ expect(
+ await refusedWith(refusal('UNSUPPORTED_ON_REMOTE')),
+ 'Update the harness CLI on this machine to restart a harness.',
+ );
+ expect(
+ await refusedWith(refusal('UNSUPPORTED')),
+ 'Update the harness CLI on this machine to restart a harness.',
+ );
+ // The machine's own sentence, when it sends one.
+ expect(
+ await refusedWith(
+ refusal(
+ 'CWD_NOT_FOUND',
+ detail: 'The saved project folder is no longer available.',
+ ),
+ ),
+ 'The saved project folder is no longer available.',
+ );
+ expect(
+ await refusedWith(refusal('NO_ACTIVE_PROCESS')),
+ 'Restart failed: NO_ACTIVE_PROCESS',
+ );
+ });
+
+ test('a restart whose outcome is unknown is not called a failure', () async {
+ final rig = await signedInWith({
+ 'm': ['a'],
+ });
+ addTearDown(rig.app.dispose);
+ Future<String?> answeredWith(
+ FutureOr<Map<String, dynamic>> Function(Map<String, dynamic>) answer,
+ ) async {
+ rig.conn('m').answers['agent_restart'] = answer;
+ return (await rig.app.restartAgent('m', 'a')).error;
+ }
+
+ // The reply did not come in time: the machine may be restarting it still.
+ expect(
+ await answeredWith(
+ (_) => throw const WsRequestTimeout('agent_restart'),
+ ),
+ restartUnconfirmed,
+ );
+ // The socket dropped under the request.
+ expect(
+ await answeredWith((_) => throw Exception('connection closed')),
+ restartUnconfirmed,
+ );
+ // A relaunch the machine did not see come up, which may still have — the desktop's reading.
+ expect(
+ await answeredWith(
+ (_) => throw refusal(
+ 'RESTART_FAILED',
+ detail: 'claude did not come back up after restart',
+ ),
+ ),
+ restartUnconfirmed,
+ );
+ expect(
+ await answeredWith((_) => throw refusal('INTERNAL')),
+ restartUnconfirmed,
+ );
+ expect(
+ await answeredWith((_) => throw refusal('CREATION_STORAGE_FAILED')),
+ restartUnconfirmed,
+ );
+ expect(
+ await answeredWith((_) => {'error': 'RESTART_FAILED'}),
+ restartUnconfirmed,
+ );
+ });
+
+ // Getting the new engine up can take the machine longer than the 20s a request waits by
+ // default — and a phone that gave up there said the restart had failed while it still ran.
+ test('a restart waits longer than a request usually does', () async {
+ final rig = await signedInWith({
+ 'm': ['a'],
+ });
+ addTearDown(rig.app.dispose);
+
+ await rig.app.restartAgent('m', 'a');
+
+ expect(
+ rig.conn('m').timeouts['agent_restart'],
+ greaterThan(const Duration(seconds: 30)),
+ );
+ });
+
+ test('a restart that answers after the app let go is harmless', () async {
+ final rig = await signedInWith({
+ 'm': ['a'],
+ });
+ final reply = Completer<Map<String, dynamic>>();
+ rig.conn('m').answers['agent_restart'] = (_) => reply.future;
+
+ final restart = rig.app.restartAgent('m', 'a');
+ await settle();
+ rig.app.dispose();
+ reply.complete({'agent': agentJson('a', name: 'late'), 'resumed': true});
+
+ expect((await restart).error, isNull);
+ });
});
group('resuming stopped work', () {
diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dart
index c37aec41b..2138c9e9f 100644
--- a/mobile/test/phone_edge/focus_behavior_test.dart
+++ b/mobile/test/phone_edge/focus_behavior_test.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
@@ -20,6 +21,7 @@ import 'package:harness_mobile/state/pending_question.dart';
import 'package:harness_mobile/terminal/terminal_binary.dart';
import 'package:harness_mobile/terminal/terminal_font_store.dart';
import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
import 'package:xterm/xterm.dart';
import '../voice_fakes.dart';
@@ -335,10 +337,20 @@ void main() {
WidgetTester tester, {
bool working = false,
bool raw = false,
+ String engine = 'claude',
+ EdgeConn? connection,
}) async {
final focus = await _Focus.open(
tester,
- agents: [edgeAgent('a', project: longProject, branch: longBranch)],
+ agents: [
+ edgeAgent(
+ 'a',
+ engine: engine,
+ project: longProject,
+ branch: longBranch,
+ ),
+ ],
+ connection: connection,
);
if (working) focus.app.stateOf('m')!.processingAgentIds.add('a');
focus.app.stateOf('m')!.terminalPasteRawAvailable = raw;
@@ -438,6 +450,172 @@ void main() {
await focus.close();
});
+ /// The menu again, over the terminal, as a second look at it opens it.
+ Future<void> reopen(WidgetTester tester) async {
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ }
+
+ /// The menu put away by a tap above it, on the veil.
+ Future<void> putAway(WidgetTester tester) async {
+ await tester.tapAt(const Offset(200, 40));
+ await frames(tester);
+ }
+
+ // ⚠️ A second press is a second restart: the machine runs it once the first is done, and the
+ // engine that just came back is replaced again.
+ testWidgets('Restart, while it runs, says so and cannot be pressed again', (
+ tester,
+ ) async {
+ final reply = Completer<Map<String, dynamic>>();
+ final conn = _RestartConn(() => reply.future);
+ final focus = await openMenu(tester, connection: conn);
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(conn.restarts, 1);
+
+ // Nothing seemed to happen: the menu opened again, Restart pressed again.
+ await reopen(tester);
+ expect(find.text('restarting…'), findsOneWidget);
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(conn.restarts, 1);
+ expect(
+ find.text('restarting…'),
+ findsOneWidget,
+ reason: 'the row took no tap, so the menu is still up',
+ );
+
+ await putAway(tester);
+ reply.complete({'resumed': true});
+ await frames(tester);
+ await reopen(tester);
+ expect(find.text('restarting…'), findsNothing);
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(
+ conn.restarts,
+ 2,
+ reason: 'once it is over, it can be asked again',
+ );
+ await focus.close();
+ });
+
+ testWidgets('Restart that came back on a new conversation says so', (
+ tester,
+ ) async {
+ final focus = await openMenu(
+ tester,
+ connection: EdgeConn(const {
+ 'agent_restart': {'resumed': false},
+ }),
+ );
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(find.text('Restarted with a new conversation.'), findsOneWidget);
+ await focus.close();
+ });
+
+ testWidgets('Restart that came back where it was says nothing', (
+ tester,
+ ) async {
+ final focus = await openMenu(
+ tester,
+ connection: EdgeConn(const {
+ 'agent_restart': {'resumed': true},
+ }),
+ );
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(find.byType(SnackBar), findsNothing);
+ await focus.close();
+ });
+
+ testWidgets('Restart from a machine too old to say how it came back says '
+ 'nothing', (tester) async {
+ final focus = await openMenu(tester);
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(focus.conn.requests, contains('agent_restart'));
+ expect(find.byType(SnackBar), findsNothing);
+ await focus.close();
+ });
+
+ // A terminal always restarts as a fresh shell, which is what its Restart promised.
+ testWidgets('Restart of a terminal, a fresh shell, says nothing', (
+ tester,
+ ) async {
+ final focus = await openMenu(
+ tester,
+ engine: 'terminal',
+ connection: EdgeConn(const {
+ 'agent_restart': {'resumed': false},
+ }),
+ );
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(focus.conn.requests, contains('agent_restart'));
+ expect(find.byType(SnackBar), findsNothing);
+ await focus.close();
+ });
+
+ testWidgets('Restart the machine refuses says why in a sentence, not as '
+ 'the socket\'s error', (tester) async {
+ final conn = _RestartConn(
+ () async => throw const WsRequestFailure(
+ responseType: 'agent_restart_result',
+ code: 'AGENT_BUSY',
+ ),
+ );
+ final focus = await openMenu(tester, connection: conn);
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(
+ find.text(
+ 'Another operation is changing this harness. Wait for it to finish, then retry.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.textContaining('agent_restart_result'), findsNothing);
+ await putAway(tester);
+ await reopen(tester);
+ expect(find.text('restarting…'), findsNothing);
+ await focus.close();
+ });
+
+ // The machine may be restarting it still: "failed" would send the person to press Restart
+ // again, over a restart that is about to finish.
+ testWidgets('Restart whose reply never came does not say it failed', (
+ tester,
+ ) async {
+ final conn = _RestartConn(
+ () async => throw const WsRequestTimeout('agent_restart'),
+ );
+ final focus = await openMenu(tester, connection: conn);
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(
+ find.text(
+ 'Could not confirm the restart. Check the terminal before restarting again.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.textContaining('failed'), findsNothing);
+ expect(find.textContaining('timed out'), findsNothing);
+
+ await putAway(tester);
+ await reopen(tester);
+ expect(find.text('restarting…'), findsNothing);
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(
+ conn.restarts,
+ 2,
+ reason: 'not held for good by a reply that never came',
+ );
+ await focus.close();
+ });
+
testWidgets('Rename, Stop and Settings open their own screens', (
tester,
) async {
@@ -1613,13 +1791,15 @@ class _Focus {
/// Every frame the session sent — a reopen among them.
final List<(String, Map<String, dynamic>)> sent;
+ /// [connection], when given, is the machine instead of one answering from [answers].
static Future<_Focus> open(
WidgetTester tester, {
List<Agent>? agents,
Map<String, Map<String, dynamic>> answers = const {},
+ EdgeConn? connection,
}) async {
setPhone(tester, largePhone);
- final conn = EdgeConn(answers);
+ final conn = connection ?? EdgeConn(answers);
final app = edgeApp(conn: conn, agents: agents ?? [edgeAgent('a')]);
final sent = <(String, Map<String, dynamic>)>[];
final session = await liveTerminal(app, 'a', sent: sent);
@@ -1809,6 +1989,33 @@ class _Focus {
}
}
+/// A machine whose answer to `agent_restart` the test writes: held until the test gives it, or
+/// thrown — the way a real socket hands the page a refusal ([WsRequestFailure]) and a reply that
+/// never came ([WsRequestTimeout]).
+class _RestartConn extends EdgeConn {
+ _RestartConn(this.restart);
+
+ /// What every `agent_restart` gets back.
+ final Future<Map<String, dynamic>> Function() restart;
+
+ /// How many restarts were sent.
+ int get restarts => payloads['agent_restart']?.length ?? 0;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type != 'agent_restart') {
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+ requests.add(type);
+ (payloads[type] ??= []).add(payload);
+ return restart();
+ }
+}
+
class _Pushes extends NavigatorObserver {
_Pushes(this.pushed);
diff --git a/mobile/test/viewer_app_fixture.dart b/mobile/test/viewer_app_fixture.dart
index b95a659e7..5e22c0ac6 100644
--- a/mobile/test/viewer_app_fixture.dart
+++ b/mobile/test/viewer_app_fixture.dart
@@ -70,6 +70,9 @@ class ScriptedConn extends PagerConn {
final List<Uint8List> binaries = [];
int redials = 0;
+ /// Request type → how long its last request was willing to wait for the reply.
+ final Map<String, Duration> timeouts = {};
+
/// The request types asked, in order.
List<String> get asked => [for (final (type, _) in requests) type];
@@ -97,6 +100,7 @@ class ScriptedConn extends PagerConn {
Duration timeout = const Duration(seconds: 20),
}) async {
requests.add((type, payload));
+ timeouts[type] = timeout;
final answer = answers[type];
if (answer == null) return {};
return await answer(payload);