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): Focus shows a harness asking elsewhere, and a tap reopens a dead stream

dee2f7242ccd193
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 4b0842a46..ae407e65f 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -198,6 +198,7 @@ typedef _PageFacts = ({
bool redialling,
bool imagePaste,
String? machineName,
+ String? asking,
});
/// What a page has asked for back — see [_TerminalPageState._reclaiming].
@@ -693,6 +694,11 @@ class _TerminalPageState extends State<TerminalPage>
phoneMachineRedialling(machine),
imagePaste: machine?.terminalImagePasteAvailable ?? false,
machineName: machine?.machine.displayName,
+ // ⚠️ The title's `api-fix asking` is drawn from here too. Left out, a harness elsewhere
+ // that stopped to ask moved no fact this page compared, so the word never appeared — the
+ // one signal the title carries about the rest of the fleet, missing until something
+ // unrelated happened to rebuild the page.
+ asking: _askingElsewhere(),
);
}
@@ -1873,115 +1879,121 @@ class _TerminalPageState extends State<TerminalPage>
// listening for its notifications as they
// bubble past is what survives that, and costs
// the panel no knowledge of the page's chrome.
- child:
- NotificationListener<
- ScrollNotification
- >(
- // A scroll on a terminal held elsewhere takes it,
- // as a tap does: no button to find first.
- onNotification: (notification) {
- if (blocked &&
- notification
- is ScrollStartNotification &&
- notification.dragDetails !=
- null) {
- unawaited(_takeControl());
- }
- return _chrome.onNotification(
- notification,
- );
- },
- child: agentGone
- ? _AgentGone(
- name: _cachedAgentName,
- onPickAnother:
- _pickAnotherAgent,
- )
- : pane == null ||
- session == null
- ? _Attaching(
- key: _skeletonKey,
- )
- : TerminalPanel(
- key: ValueKey(pane.id),
- notifier: widget.notifier,
- session: session,
- // Only the page on screen takes the keyboard — see
- // [TerminalPage.isActive]. `visible` is the same answer for the
- // panel's other half: a page parked beside this one releases
- // focus, stops rendering and stops resizing its remote shell.
- //
- // Whether it also HOLDS one that is already
- // up is a separate question, and the pager asks
- // it on every swipe — see [_shouldFocus].
- focused: _shouldFocus,
- // Asks again when `focused` did
- // not move — coming back from
- // another app. See
- // [didChangeAppLifecycleState].
- focusRequest:
- _focusRequest,
- visible: widget.isActive,
- // Hold the remote resize while the keyboard
- // slides. Separate from `visible` because this
- // must NOT release focus — the animation being
- // waited on is the one that focus started.
- //
- // The keyboard is the only thing left that
- // moves this pane's height: the header slides
- // OVER the terminal rather than out of its
- // column — see [_SlideAway].
- //
- // ⚠️ Held for as long as search is open, too:
- // its keyboard is typing a query over a faded
- // terminal, and resizing the agent's shell for
- // it redrew the whole TUI on the way in and
- // again on the way out.
- settling:
- _keyboardSettling ||
- _heldForSearch,
- // ⚠️ The tap is taken in the panel, not by a
- // `Listener` over it. xterm's own `_onTapDown`
- // calls `requestKeyboard()`, so anything that
- // merely ALSO reacted to the tap would raise
- // the keyboard before the words said were typed
- // into the prompt — and a re-armed claim on top
- // of it was measured asking Android twice per
- // tap, which answers a show mid-animation by
- // cancelling and restarting it. Null while the
- // keyboard is up or coming, so the tap is
- // xterm's and the keyboard stays.
- //
- // ⚠️ A tap on a pane that cannot take input
- // takes the TERMINAL first, not the
- // keyboard: raising one over a read-only
- // pane offers a prompt that silently
- // swallows every letter.
- onInputTap: blocked
- ? () => unawaited(
- _takeControl(),
- )
- : _shouldFocus
- ? null
- : () => unawaited(
- _raiseKeyboard(
- session,
- ),
- ),
- onLineTap: _onLineTap,
- showHeader: false,
- // tmux's copy-mode position while
- // reading back — see [_CopyModePosition].
- scrollback: _scrollback,
- jumpToEndRequest:
- _jumpToEnd,
- // No composer, and so no grip above it: the
- // page hands the pane its full height and the
- // software keyboard drives the terminal
- // directly. The mic's send is what kept the
- // composer's batched turn.
- ),
- ),
+ child: NotificationListener<ScrollNotification>(
+ // A scroll on a terminal held elsewhere takes it,
+ // as a tap does: no button to find first.
+ onNotification: (notification) {
+ if (blocked &&
+ notification
+ is ScrollStartNotification &&
+ notification.dragDetails !=
+ null) {
+ unawaited(_takeControl());
+ }
+ return _chrome.onNotification(
+ notification,
+ );
+ },
+ child: agentGone
+ ? _AgentGone(
+ name: _cachedAgentName,
+ onPickAnother:
+ _pickAnotherAgent,
+ )
+ : pane == null || session == null
+ ? _Attaching(key: _skeletonKey)
+ : TerminalPanel(
+ key: ValueKey(pane.id),
+ notifier: widget.notifier,
+ session: session,
+ // Only the page on screen takes the keyboard — see
+ // [TerminalPage.isActive]. `visible` is the same answer for the
+ // panel's other half: a page parked beside this one releases
+ // focus, stops rendering and stops resizing its remote shell.
+ //
+ // Whether it also HOLDS one that is already
+ // up is a separate question, and the pager asks
+ // it on every swipe — see [_shouldFocus].
+ focused: _shouldFocus,
+ // Asks again when `focused` did
+ // not move — coming back from
+ // another app. See
+ // [didChangeAppLifecycleState].
+ focusRequest: _focusRequest,
+ visible: widget.isActive,
+ // Hold the remote resize while the keyboard
+ // slides. Separate from `visible` because this
+ // must NOT release focus — the animation being
+ // waited on is the one that focus started.
+ //
+ // The keyboard is the only thing left that
+ // moves this pane's height: the header slides
+ // OVER the terminal rather than out of its
+ // column — see [_SlideAway].
+ //
+ // ⚠️ Held for as long as search is open, too:
+ // its keyboard is typing a query over a faded
+ // terminal, and resizing the agent's shell for
+ // it redrew the whole TUI on the way in and
+ // again on the way out.
+ settling:
+ _keyboardSettling ||
+ _heldForSearch,
+ // ⚠️ The tap is taken in the panel, not by a
+ // `Listener` over it. xterm's own `_onTapDown`
+ // calls `requestKeyboard()`, so anything that
+ // merely ALSO reacted to the tap would raise
+ // the keyboard before the words said were typed
+ // into the prompt — and a re-armed claim on top
+ // of it was measured asking Android twice per
+ // tap, which answers a show mid-animation by
+ // cancelling and restarting it. Null while the
+ // keyboard is up or coming, so the tap is
+ // xterm's and the keyboard stays.
+ //
+ // ⚠️ A tap on a pane that cannot take input
+ // takes the TERMINAL first, not the
+ // keyboard: raising one over a read-only
+ // pane offers a prompt that silently
+ // swallows every letter.
+ //
+ // ⚠️ **A stream that died is one of those
+ // panes.** Held to [blocked] alone, a tap on
+ // a closed or failed stream raised the
+ // keyboard over it — keys dimmed, letters
+ // dropped — and nothing on the page offered
+ // the reconnect instead. The take reopens it.
+ onInputTap:
+ blocked ||
+ session.status ==
+ TerminalSessionStatus
+ .closed ||
+ session.status ==
+ TerminalSessionStatus
+ .error
+ ? () => unawaited(
+ _takeControl(),
+ )
+ : _shouldFocus
+ ? null
+ : () => unawaited(
+ _raiseKeyboard(
+ session,
+ ),
+ ),
+ onLineTap: _onLineTap,
+ showHeader: false,
+ // tmux's copy-mode position while
+ // reading back — see [_CopyModePosition].
+ scrollback: _scrollback,
+ jumpToEndRequest: _jumpToEnd,
+ // No composer, and so no grip above it: the
+ // page hands the pane its full height and the
+ // software keyboard drives the terminal
+ // directly. The mic's send is what kept the
+ // composer's batched turn.
+ ),
+ ),
),
),
),
diff --git a/mobile/test/phone_edge/edge_fixture.dart b/mobile/test/phone_edge/edge_fixture.dart
index 1dda844a1..a3cfd47b9 100644
--- a/mobile/test/phone_edge/edge_fixture.dart
+++ b/mobile/test/phone_edge/edge_fixture.dart
@@ -4,8 +4,12 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/api/api_client.dart';
import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/auth/cli_link.dart';
+import 'package:harness_mobile/auth/peer_link_client.dart';
import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/harness_cli_runner.dart';
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/demo/sample_mode.dart';
import 'package:harness_mobile/phone/voice_input_controller.dart';
@@ -118,6 +122,9 @@ class EdgeConn extends WsConn {
final List<(String, Map<String, dynamic>)> frames = [];
final List<String> requests = [];
+ /// How many times a terminal was asked to open.
+ int get opens => frames.where((frame) => frame.$1 == 'terminal_open').length;
+
@override
Future<bool> sendTerminalFrame(
String type,
@@ -158,6 +165,11 @@ Agent edgeAgent(
/// An account with one machine, `m`, running [agents] — as a phone sees it when [online], or as it
/// sees a machine that has gone away when not.
+///
+/// ⚠️ **Every way out of the process is stubbed, not only the machine's socket.** A notifier left
+/// with its defaults reaches the local `harness` CLI's HTTP port through [ApiClient], and runs the
+/// `harness` binary itself to link a computer by password — the user's real harnesses, from a
+/// test. [EdgeApi], [EdgeLinks] and a CLI runner that refuses to start anything close all three.
AppNotifier edgeApp({
List<Agent>? agents,
String machineName = 'studio',
@@ -165,13 +177,18 @@ AppNotifier edgeApp({
AgentLoadStatus load = AgentLoadStatus.loaded,
EdgeConn? conn,
bool noMachines = false,
+ EdgeLinks? links,
}) {
+ final session = AuthSession();
final app = AppNotifier(
config: AppConfig.dev,
- authSession: AuthSession(),
+ authSession: session,
configStore: null,
connectionForTest: (_) => conn ?? EdgeConn(),
+ peerLinks: links ?? EdgeLinks(),
+ cliLink: CliLink(runner: _noCli()),
);
+ app.api = EdgeApi(app, session);
if (noMachines) return app;
final machine = Machine(
machineId: 'm',
@@ -190,6 +207,87 @@ AppNotifier edgeApp({
return app;
}
+/// The control plane, answered from the app's own list — never the local CLI's HTTP port, which
+/// is where a real [ApiClient] outside a viewer build sends everything.
+class EdgeApi extends ApiClient {
+ EdgeApi(this._app, AuthSession session)
+ : super(config: AppConfig.dev, session: session);
+
+ final AppNotifier _app;
+
+ @override
+ Future<Map<String, dynamic>?> me() async => null;
+
+ @override
+ Future<List<Machine>> machines() async => _app.machines;
+
+ @override
+ Future<String?> renameMachine({
+ required String machineId,
+ required String name,
+ }) async => name;
+
+ @override
+ Future<void> deleteMachine({required String machineId}) async {}
+
+ @override
+ Future<Map<String, dynamic>?> desk() async => null;
+
+ @override
+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> ops) async =>
+ null;
+
+ @override
+ Future<String> transcribeVoice(Uint8List wav, {required String lang}) async =>
+ '';
+}
+
+/// Linking a computer by password or by code, answered by the test: [error] when set, else
+/// success.
+class EdgeLinks implements PeerLinkClient {
+ String? error;
+ final List<String> passwords = [];
+
+ @override
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ }) async {
+ passwords.add(password);
+ onProgress?.call('connecting');
+ return error == null
+ ? CliLinkConnectResult(linkedMachineId: machineId)
+ : CliLinkConnectResult(error: error);
+ }
+
+ @override
+ Future<CliLinkConnectResult> connectWithCode(
+ String machineId,
+ String code, {
+ required String label,
+ String? displayName,
+ }) async => error == null
+ ? CliLinkConnectResult(linkedMachineId: machineId)
+ : CliLinkConnectResult(error: error);
+
+ @override
+ Future<CliLinkListResult> list() async => const CliLinkListResult();
+
+ @override
+ Future<String?> unlink(String machineId) async => null;
+}
+
+/// A `harness` CLI that is never there: every run fails as a binary that could not be started
+/// would, and nothing is spawned.
+HarnessCliRunner _noCli() => HarnessCliRunner(
+ runProcess: (executable, arguments, {environment}) =>
+ throw const ProcessException('harness', [], 'not in tests'),
+ startProcess: (executable, arguments, {environment}) =>
+ throw const ProcessException('harness', [], 'not in tests'),
+);
+
/// [count] agents, `a0`…, the first named [firstName] when given.
List<Agent> manyAgents(int count, {String? firstName}) => [
for (var i = 0; i < count; i++)
@@ -202,17 +300,23 @@ List<Agent> manyAgents(int count, {String? firstName}) => [
/// A live terminal for [agentId] on `m`: adopted as the pane and given its first keyframe, so the
/// page draws a screen rather than its skeleton.
+///
+/// [sent] collects every frame the session sends — a reopen, a resize.
Future<TerminalSession> liveTerminal(
AppNotifier app,
String agentId, {
String? name,
+ List<(String, Map<String, dynamic>)>? sent,
}) async {
final session = TerminalSession(
machineId: 'm',
agentId: agentId,
agentName: name ?? agentId,
engineId: 'claude',
- send: (_, _) async => true,
+ send: (type, payload) async {
+ sent?.add((type, payload));
+ return true;
+ },
sendBinary: (_) async => true,
);
app.adoptSessionForTest(session);
diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dart
new file mode 100644
index 000000000..266eaf7ad
--- /dev/null
+++ b/mobile/test/phone_edge/focus_behavior_test.dart
@@ -0,0 +1,608 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/phone/phone_search_catalog.dart'
+ show phoneAgentId;
+import 'package:harness_mobile/phone/phone_shell_scope.dart';
+import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/phone/terminal_search.dart';
+import 'package:harness_mobile/phone/new_agent_page.dart';
+import 'package:harness_mobile/phone/settings_page.dart';
+import 'package:harness_mobile/phone/voice_input_controller.dart';
+import 'package:harness_mobile/phone/voice_mic_button.dart';
+import 'package:harness_mobile/phone/voice_mic_face.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/pending_question.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:xterm/xterm.dart';
+
+import '../voice_fakes.dart';
+import 'edge_fixture.dart';
+
+/// Focus as somebody uses it: a keyboard raised mid-take, a machine that goes away under the
+/// agent on screen, taps that come twice, the menu's every row, a question answered by key, by
+/// line and by voice.
+void main() {
+ setUp(() {
+ // The sheet's own haptics and the clipboard are platform calls a test has no platform for.
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {
+ if (call.method == 'Clipboard.getData') return _clipboard;
+ return null;
+ });
+ });
+
+ tearDown(() {
+ _clipboard = null;
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(SystemChannels.platform, null);
+ });
+
+ testWidgets('a keyboard raised while the mic records puts the take away', (
+ tester,
+ ) async {
+ final focus = await _Focus.open(tester);
+
+ await tester.tap(find.byType(VoiceMicCore));
+ await frames(tester);
+ expect(focus.voice.status, VoiceInputStatus.listening);
+
+ // The keyboard comes up while the take is still recording.
+ raiseKeyboard(tester);
+ await frames(tester);
+
+ expect(focus.voice.status, VoiceInputStatus.idle);
+ expect(focus.recorder.cancels, 1, reason: 'the microphone is let go');
+ expect(
+ find.byType(VoiceMicButton),
+ findsNothing,
+ reason: 'the mic hides under the key bar rather than floating over it',
+ );
+ expect(find.byKey(const ValueKey('terminal-key-esc')), findsOneWidget);
+
+ // And the ▾ key puts the keyboard away again, bringing the mic back.
+ await tester.tap(find.byKey(const ValueKey('terminal-key-Hide keyboard')));
+ lowerKeyboard(tester);
+ await frames(tester);
+ expect(find.byType(VoiceMicButton), findsOneWidget);
+ await focus.close();
+ });
+
+ testWidgets('the machine goes offline under the agent on screen, and back', (
+ tester,
+ ) async {
+ final focus = await _Focus.open(tester);
+ expect(_micLive(tester), isTrue);
+
+ await focus.app.handleMachineEventForTest('m', {
+ 'type': 'node_status',
+ 'payload': {'online': false},
+ });
+ await frames(tester);
+
+ // The page stays on the agent: the name, the terminal it had — and a mic that cannot send.
+ expect(tester.takeException(), isNull);
+ expect(find.text('a'), findsOneWidget);
+ expect(find.byType(TerminalView), findsOneWidget);
+ expect(focus.session.acceptsInput, isFalse);
+ expect(_micLive(tester), isFalse);
+
+ // A tap on the dead terminal asks for it back rather than raising a keyboard over nothing.
+ await focus.tapPrompt();
+ await frames(tester);
+
+ await focus.app.handleMachineEventForTest('m', {
+ 'type': 'node_status',
+ 'payload': {'online': true},
+ });
+ await frames(tester);
+ expect(tester.takeException(), isNull);
+ await focus.close();
+ });
+
+ testWidgets(
+ 'a tap on a stream that died reopens it rather than raising a keyboard over nothing',
+ (tester) async {
+ final focus = await _Focus.open(tester);
+ focus.fill();
+ await frames(tester);
+ await focus.session.handleFrame('terminal_closed', {
+ 'streamId': focus.session.streamId,
+ 'code': 'TERMINAL_CLOSED',
+ 'reason': 'the daemon restarted',
+ });
+ await frames(tester);
+ expect(focus.session.status, TerminalSessionStatus.closed);
+ final opensBefore = focus.opens;
+
+ await focus.tapPrompt();
+ await frames(tester);
+
+ // Before: the keyboard came up, its keys dimmed, and every letter typed went nowhere.
+ expect(
+ find.byKey(const ValueKey('terminal-key-esc')),
+ findsNothing,
+ reason: 'no keyboard over a stream that cannot take a keystroke',
+ );
+ expect(focus.opens, greaterThan(opensBefore), reason: 'reopened');
+ await focus.close();
+ },
+ );
+
+ testWidgets(
+ 'the socket drops and redials: the page waits rather than leaving',
+ (tester) async {
+ final focus = await _Focus.open(tester);
+ focus.app.connectionStatusForTest('m', ConnectionStatus.reconnecting);
+ await frames(tester);
+ expect(find.byType(TerminalPage), findsOneWidget);
+ focus.app.connectionStatusForTest('m', ConnectionStatus.connected);
+ await frames(tester);
+ expect(find.byType(TerminalPage), findsOneWidget);
+ await focus.close();
+ },
+ );
+
+ testWidgets('a double tap on the title opens one menu, not two', (
+ tester,
+ ) async {
+ final focus = await _Focus.open(tester);
+ final routes = focus.pushed.length;
+
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await tester.pump(const Duration(milliseconds: 60));
+ await tester.tap(
+ find.byKey(const ValueKey('terminal-title')),
+ warnIfMissed: false,
+ );
+ await frames(tester);
+
+ expect(
+ focus.pushed.length - routes,
+ lessThanOrEqualTo(1),
+ reason: 'the second tap lands on the open menu, not on a second one',
+ );
+ await focus.close();
+ });
+
+ testWidgets('back and forth between Focus, Find and New, quickly', (
+ tester,
+ ) async {
+ final focus = await _Focus.open(tester);
+ final centre = tester.getCenter(find.byType(TerminalPage));
+ for (var round = 0; round < 3; round++) {
+ // Right: Find.
+ await tester.dragFrom(
+ centre - const Offset(120, 0),
+ const Offset(300, 0),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.byType(TerminalSearchOverlay), findsOneWidget);
+ // Left on Find: back to the terminal, before the open has even finished.
+ await tester.fling(
+ find.byType(TerminalSearchOverlay),
+ const Offset(-300, 0),
+ 1500,
+ );
+ await frames(tester);
+ expect(find.byType(TerminalSearchOverlay), findsNothing);
+ // Left on the terminal: New.
+ await tester.dragFrom(
+ centre + const Offset(120, 0),
+ const Offset(-300, 0),
+ );
+ await frames(tester);
+ expect(find.byType(NewAgentPage), findsOneWidget);
+ // Right on New: back.
+ await tester.dragFrom(
+ tester.getCenter(find.byType(NewAgentPage)),
+ const Offset(300, 0),
+ );
+ await frames(tester, count: 6);
+ expect(find.byType(NewAgentPage), findsNothing);
+ }
+ expect(tester.takeException(), isNull);
+ expect(find.byType(TerminalView), findsOneWidget);
+ await focus.close();
+ });
+
+ group('the title', () {
+ testWidgets('held, with no other harness: says so above the mic', (
+ tester,
+ ) async {
+ final focus = await _Focus.open(tester);
+ await tester.longPress(find.byKey(const ValueKey('terminal-title')));
+ await tester.pump();
+ expect(find.text('no other harness yet'), findsOneWidget);
+ await tester.pump(const Duration(seconds: 3));
+ expect(find.text('no other harness yet'), findsNothing);
+ await focus.close();
+ });
+
+ testWidgets('held: back to the harness used before this one', (
+ tester,
+ ) async {
+ final focus = await _Focus.open(
+ tester,
+ agents: [edgeAgent('a'), edgeAgent('b'), edgeAgent('c')],
+ );
+ focus.app.searchHistory.remember(phoneAgentId('m', 'c'));
+ await tester.longPress(find.byKey(const ValueKey('terminal-title')));
+ await tester.pump();
+ expect(focus.opened, [('m', 'c')]);
+
+ // With no visits on this phone, the account's last-used order decides.
+ final other = await _Focus.open(
+ tester,
+ agents: [edgeAgent('a'), edgeAgent('b', minutesAgo: 1)],
+ );
+ await tester.longPress(find.byKey(const ValueKey('terminal-title')));
+ await tester.pump();
+ expect(other.opened, [('m', 'b')]);
+ await other.close();
+ });
+
+ testWidgets(
+ 'another harness starts asking while this one is on screen: the title says so',
+ (tester) async {
+ final focus = await _Focus.open(
+ tester,
+ agents: [
+ edgeAgent('a'),
+ edgeAgent('b', name: 'api-fix'),
+ edgeAgent('c', name: 'docs'),
+ ],
+ );
+ expect(find.textContaining('asking'), findsNothing);
+
+ await focus.question('b');
+ await frames(tester);
+ expect(find.text('api-fix asking'), findsOneWidget);
+
+ // Two asking are counted, not named.
+ await focus.question('c');
+ await frames(tester);
+ expect(find.text('2 asking'), findsOneWidget);
+
+ // Answered elsewhere: the word goes.
+ await focus.answered('b');
+ await focus.answered('c');
+ await frames(tester);
+ expect(find.textContaining('asking'), findsNothing);
+ await focus.close();
+ },
+ );
+
+ testWidgets('another harness asking: its name opens Find', (tester) async {
+ final focus = await _Focus.open(
+ tester,
+ agents: [
+ edgeAgent('a'),
+ edgeAgent('b', name: 'api-fix'),
+ ],
+ );
+ await focus.question('b');
+ await frames(tester);
+ await tester.tap(find.text('api-fix asking'));
+ await frames(tester);
+ expect(find.byType(TerminalSearchOverlay), findsOneWidget);
+ await focus.close();
+ });
+ });
+
+ group('the menu', () {
+ Future<_Focus> openMenu(
+ WidgetTester tester, {
+ bool working = false,
+ bool raw = false,
+ }) async {
+ final focus = await _Focus.open(
+ tester,
+ agents: [edgeAgent('a', project: longProject, branch: longBranch)],
+ );
+ if (working) focus.app.stateOf('m')!.processingAgentIds.add('a');
+ focus.app.stateOf('m')!.terminalPasteRawAvailable = raw;
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ return focus;
+ }
+
+ testWidgets('Paste: the clipboard\'s text goes to the prompt', (
+ tester,
+ ) async {
+ final focus = await openMenu(tester);
+ _clipboard = {'text': 'git status'};
+ await tester.tap(find.text('Paste from clipboard'));
+ await frames(tester);
+ expect(focus.typed.join(), contains('git status'));
+ await focus.close();
+ });
+
+ testWidgets('Paste with nothing on the clipboard says so', (tester) async {
+ final focus = await openMenu(tester);
+ _clipboard = null;
+ await tester.tap(find.text('Paste from clipboard'));
+ await frames(tester, count: 1);
+ expect(find.text('the clipboard has no text'), findsOneWidget);
+ await focus.close();
+ });
+
+ testWidgets('Paste where the computer takes a raw paste', (tester) async {
+ final focus = await openMenu(tester, raw: true);
+ _clipboard = {'text': 'ls -la'};
+ await tester.tap(find.text('Paste from clipboard'));
+ await frames(tester);
+ expect(tester.takeException(), isNull);
+ await focus.close();
+ });
+
+ testWidgets('Interrupt, while it works, sends esc', (tester) async {
+ final focus = await openMenu(tester, working: true);
+ await tester.tap(find.text('Interrupt'));
+ await frames(tester);
+ expect(focus.typed, contains('\x1b'));
+ await focus.close();
+ });
+
+ testWidgets('Restart that the machine refuses says why', (tester) async {
+ final focus = await openMenu(tester);
+ await tester.tap(find.text('Restart'));
+ await frames(tester);
+ expect(focus.conn.requests, contains('agent_restart'));
+ await focus.close();
+ });
+
+ testWidgets('Rename, Stop and Settings open their own screens', (
+ tester,
+ ) async {
+ final focus = await openMenu(tester);
+ // Switched off everywhere for now (`kModelSheetEnabled`): no row that looks like a choice.
+ expect(find.text('Model'), findsNothing);
+ await tester.tap(find.text('Rename…'));
+ await frames(tester);
+ expect(find.byType(TextField), findsOneWidget);
+ await tester.tap(find.text('Cancel'));
+ await frames(tester);
+
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ await tapInView(tester, find.text('Stop this harness…'));
+ await frames(tester);
+ expect(find.text('Cancel'), findsOneWidget);
+ await tester.tap(find.text('Cancel'));
+ await frames(tester);
+
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ await tapInView(tester, find.text('Settings'));
+ await frames(tester);
+ expect(find.byType(SettingsPage), findsOneWidget);
+ await focus.close();
+ });
+ });
+
+ group('a question', () {
+ Future<_Focus> asked(WidgetTester tester) async {
+ final focus = await _Focus.open(tester);
+ focus.session.terminal.write(permissionDialog);
+ await frames(tester);
+ return focus;
+ }
+
+ testWidgets('its keys beside the mic press its first and last answers', (
+ tester,
+ ) async {
+ final focus = await asked(tester);
+ await tester.tap(find.bySemanticsLabel(RegExp('^Answer 1')));
+ await tester.tap(find.bySemanticsLabel(RegExp('^Answer 3')));
+ await frames(tester);
+ expect(focus.typed, containsAllInOrder(['1', '3']));
+ await focus.close();
+ });
+
+ testWidgets('a tap on an answer\'s own line presses it', (tester) async {
+ final focus = await asked(tester);
+ final line = find.textContaining("don't ask again", findRichText: true);
+ if (line.evaluate().isNotEmpty) {
+ await tester.tap(line.first);
+ }
+ await frames(tester);
+ expect(tester.takeException(), isNull);
+ await focus.close();
+ });
+
+ testWidgets('"yes" said to the mic answers it', (tester) async {
+ final focus = await asked(tester);
+ focus.stt.replies.add('Yes.');
+ await tester.tap(find.byType(VoiceMicCore));
+ await frames(tester);
+ await tester.tap(find.byType(VoiceMicCore));
+ await frames(tester);
+ expect(focus.typed, contains('1'));
+ await focus.close();
+ });
+
+ testWidgets('"no, …" presses no, and the rest follows once it closes', (
+ tester,
+ ) async {
+ final focus = await asked(tester);
+ focus.stt.replies.add('No, build it with the flag instead');
+ await tester.tap(find.byType(VoiceMicCore));
+ await frames(tester);
+ await tester.tap(find.byType(VoiceMicCore));
+ await frames(tester);
+ expect(focus.typed, contains('3'));
+ // The question closes; the rest goes to the agent's prompt.
+ focus.session.terminal.write('\x1b[2J\x1b[Hprompt> ');
+ await tester.pump(const Duration(seconds: 1));
+ await frames(tester);
+ await focus.close();
+ });
+ });
+}
+
+/// The clipboard's contents as `Clipboard.getData` reports them.
+Map<String, dynamic>? _clipboard;
+
+/// Whether the mic can be pressed.
+bool _micLive(WidgetTester tester) =>
+ tester.widget<VoiceMicButton>(find.byType(VoiceMicButton)).onPressed !=
+ null;
+
+/// One Focus page, on a live agent, pushed over a home route inside a shell that records what it
+/// is asked to open.
+class _Focus {
+ _Focus._(
+ this._widgetTester,
+ this.app,
+ this.conn,
+ this.session,
+ this.voice,
+ this.recorder,
+ this.stt,
+ this.opened,
+ this.pushed,
+ this.typed,
+ this.sent,
+ );
+
+ final WidgetTester _widgetTester;
+ final AppNotifier app;
+ final EdgeConn conn;
+ final TerminalSession session;
+ final VoiceInputController voice;
+ final FakeVoiceRecorder recorder;
+ final FakeTranscriber stt;
+ final List<(String, String)> opened;
+ final List<Route<dynamic>> pushed;
+
+ /// Everything the page typed into the terminal — keys, answers, pastes.
+ final List<String> typed;
+
+ /// Every frame the session sent — a reopen among them.
+ final List<(String, Map<String, dynamic>)> sent;
+
+ static Future<_Focus> open(WidgetTester tester, {List<Agent>? agents}) async {
+ setPhone(tester, largePhone);
+ final conn = EdgeConn();
+ final app = edgeApp(conn: conn, agents: agents ?? [edgeAgent('a')]);
+ final sent = <(String, Map<String, dynamic>)>[];
+ final session = await liveTerminal(app, 'a', sent: sent);
+ final typed = <String>[];
+ final forward = session.terminal.onOutput;
+ session.terminal.onOutput = (data) {
+ typed.add(data);
+ forward?.call(data);
+ };
+ final voice = edgeVoice();
+ final opened = <(String, String)>[];
+ final pushed = <Route<dynamic>>[];
+ await tester.pumpWidget(
+ PhoneShellScope(
+ onMachineLinked: (_) {},
+ onOpenAgent: (machineId, agentId) => opened.add((machineId, agentId)),
+ child: phoneApp(
+ TerminalPage(
+ notifier: app,
+ machineId: 'm',
+ agentId: 'a',
+ voice: voice.voice,
+ ),
+ observers: [_Pushes(pushed)],
+ ),
+ ),
+ );
+ await frames(tester);
+ return _Focus._(
+ tester,
+ app,
+ conn,
+ session,
+ voice.voice,
+ voice.recorder,
+ voice.stt,
+ opened,
+ pushed,
+ typed,
+ sent,
+ );
+ }
+
+ void ask(String agentId) =>
+ app.stateOf('m')!.blockedAgents[agentId] = PendingQuestion(
+ machineId: 'm',
+ agentId: agentId,
+ requestId: 'q-$agentId',
+ answerKey: '1',
+ prompt: 'Run the migration?',
+ options: const ['Yes', 'No'],
+ multi: false,
+ since: DateTime.now(),
+ );
+
+ /// How many times the terminal was asked to open — by the machine's socket or by the session.
+ int get opens =>
+ conn.opens + sent.where((frame) => frame.$1 == 'terminal_open').length;
+
+ /// A screenful of output, so the terminal fills the page rather than sitting anchored at its
+ /// foot — where a tap on its middle would land on nothing.
+ void fill() {
+ for (var line = 0; line < 80; line++) {
+ session.terminal.write('output line $line\r\n');
+ }
+ }
+
+ /// A tap on the terminal's prompt — its last row, at the left, clear of the mic: the one part of
+ /// the output a tap raises the keyboard from (`terminal_prompt_zone.dart`).
+ Future<void> tapPrompt() async {
+ final terminal = _widgetTester.getRect(find.byType(TerminalView));
+ final screen =
+ _widgetTester.view.physicalSize.height /
+ _widgetTester.view.devicePixelRatio;
+ final bottom = terminal.bottom < screen ? terminal.bottom : screen - 40;
+ await _widgetTester.tapAt(Offset(terminal.left + 30, bottom - 8));
+ }
+
+ /// [agentId] stops to ask something, as its machine announces it.
+ Future<void> question(String agentId) => app.handleMachineEventForTest('m', {
+ 'type': 'commander_question',
+ 'payload': {
+ 'agentId': agentId,
+ 'requestId': 'q-$agentId',
+ 'questions': [
+ {
+ 'q': 'Run the migration?',
+ 'options': ['Yes', 'No'],
+ },
+ ],
+ },
+ });
+
+ /// [agentId]'s question answered — here, elsewhere, or by hand.
+ Future<void> answered(String agentId) => app.handleMachineEventForTest('m', {
+ 'type': 'commander_question_close',
+ 'payload': {'agentId': agentId, 'requestId': 'q-$agentId'},
+ });
+
+ /// Takes the page down, runs its clocks out and lets the app go — inside the test, so no timer
+ /// the app started (an offline machine's retry) outlives it.
+ Future<void> close() async {
+ final tester = _widgetTester;
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 3));
+ app.dispose();
+ await tester.pump(const Duration(seconds: 30));
+ }
+}
+
+class _Pushes extends NavigatorObserver {
+ _Pushes(this.pushed);
+
+ final List<Route<dynamic>> pushed;
+
+ @override
+ void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) =>
+ pushed.add(route);
+}