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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
WIP: merge the phone-screens engineer's pass (4 welcome tests still pin the old set-up page copy)
dee20c04ce64be1
diff --cc mobile/lib/phone/new_agent_page.dartindex a3c2acdef,b8675ac26..4bfcc35e6--- a/mobile/lib/phone/new_agent_page.dart+++ b/mobile/lib/phone/new_agent_page.dart@@@ -766,190 -763,233 +766,238 @@@ class _NewAgentPageState extends State<label: 'harness',value: summary.isEmpty ? 'Choose an agent' : summary,onTap: () => FocusManager.instance.primaryFocus?.unfocus(),- )- else- Expanded(- child: ListView(- keyboardDismissBehavior:- ScrollViewKeyboardDismissBehavior.onDrag,- padding: EdgeInsets.zero,- children: [- TtyFormRow(- label: 'agent',- value: _engine == null- ? 'Choose an agent'- : _engineName(_engine!),- valueColor: _engine == null ? tty.green : null,- detail: _engine == null- ? null- : _engineNote(_engine!),- onTap: _creating- ? null- : () => unawaited(_chooseAgent()),- ),- TtyFormRow(- label: 'project',- value: _folder == null && _project == null- ? 'Choose a project'- : _projectValue,- valueColor: _folder == null && _project == null- ? tty.green- : null,- detail: null,- onTap: _creating- ? null- : () => unawaited(_chooseProject()),- ),- // Options, folded as the desktop folds them: branch, approvals and profile- // sit on their defaults until asked for.- TtyFormRow(- label: 'options',- // Left as it is nearly every time: folded to `[+]`.- value: _optionsOpen ? '[−]' : '[+]',- chevron: false,- onTap: () =>- setState(() => _optionsOpen = !_optionsOpen),- ),- if (_optionsOpen &&- (info != null || _gitLoading || _gitFailed))- TtyFormRow(- label: 'branch',- valueColor: info == null && !_gitLoading- ? tty.faint- : null,- value: _gitLoading- ? 'Reading…'- : info == null- ? 'No answer from the computer'- : _worktree- ? 'New worktree'- : _branchTitle,- detail: info == null- ? null- : _worktree- ? 'from $_branchTitle, in its own folder'- : _branchNote,- onTap: info == null || _creating- ? null- : () => unawaited(_chooseBranch(info)),- ),- if (_optionsOpen && _permissionModes.isNotEmpty)- TtyFormRow(- label: 'approvals',- value: mode?.label ?? 'Auto-approve',- detail: mode?.detail,- valueColor: (mode?.risky ?? false) ? tty.red : null,- onTap: _creating- ? null- : () => unawaited(_chooseApprovals()),- ),- if (_optionsOpen && _showsCodexProfile)- TtyFormRow(- label: 'profile',- value: _codexProfile?.label ?? 'Default',- onTap: _creating- ? null- : () => unawaited(_chooseProfile()),- ),- ],- ),),- if (typing) const Spacer(),- // The dock: the task, then Start. It rides the keyboard.- Padding(- padding: const EdgeInsets.fromLTRB(- Tty.origin,- 20,- Tty.origin,- 12,- ),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- // A first harness has nothing to go on: three first tasks to tap, the kind- // that shows what an agent does in a minute. Only then — once something is- // running, somebody knows what to ask, and the chips were filler over it.- if (nothingRunning &&- _task.text.trim().isEmpty &&- !_creating)- Padding(- padding: const EdgeInsets.only(bottom: 8),- child: Wrap(- spacing: 8,- runSpacing: 8,- children: [- for (final idea in const [- 'Explain this project to me',- 'Find a bug and fix it',- 'Run the tests',- ])- _Suggestion(- text: idea,- onTap: () => setState(() {- _task.value = TextEditingValue(- text: idea,- selection: TextSelection.collapsed(- offset: idea.length,- ),- );- }),- ),- ],- ),- ),- Row(- children: [+ // ⚠️ **The dock scrolls once nothing else can give way.** The rows above it go first,+ // as they always have; with none left, a dock taller than what is left used to+ // overflow — an SE typing its task at the largest text size lost the foot of the+ // field and Start with it. Held to the height below the header, it scrolls instead,+ // pinned to its foot, so the field being typed into and Start stay on the keys.+ Expanded(+ child: LayoutBuilder(+ builder: (context, box) => Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (typing)+ const Spacer()+ elseExpanded(- child: TtyText(- 'task (optional)',- color: tty.faint,- size: TtySize.meta,- ),- ),- if (count > 1800)- TtyText(- '$count/$kFirstTaskMaxLength',- color: count > kFirstTaskMaxLength- ? tty.red- : tty.faint,- size: TtySize.meta,- ),- ],- ),- const SizedBox(height: 6),- TtyField(- controller: _task,- hint: 'What should it do?',- lines: 6,- maxLength: kFirstTaskMaxLength,- action: TextInputAction.newline,- onChanged: (_) => setState(() {}),- trailing: [- Align(- alignment: Alignment.bottomRight,- child: ListenableBuilder(- listenable: _voiceIfAny ?? const _Silent(),- builder: (context, _) {- final status = _voiceIfAny?.status;- return TtyFieldMic(- live:- status == VoiceInputStatus.listening ||- status == VoiceInputStatus.starting,- onTap: _creating ? null : _talk,- );- },+ child: ListView(+ keyboardDismissBehavior:+ ScrollViewKeyboardDismissBehavior.onDrag,+ padding: EdgeInsets.zero,+ children: [+ TtyFormRow(+ label: 'agent',+ value: _engine == null+ ? 'Choose an agent'+ : _engineName(_engine!),+ valueColor: _engine == null+ ? tty.green+ : null,+ detail: _engine == null+ ? null+ : _engineNote(_engine!),+ onTap: _creating+ ? null+ : () => unawaited(_chooseAgent()),+ ),+ TtyFormRow(+ label: 'project',+ value: _folder == null && _project == null+ ? 'Choose a project'+ : _projectValue,+ valueColor:+ _folder == null && _project == null+ ? tty.green+ : null,+ detail: null,+ onTap: _creating+ ? null+ : () => unawaited(_chooseProject()),+ ),+ // Options, folded as the desktop folds them: branch, approvals and profile+ // sit on their defaults until asked for.+ TtyFormRow(+ label: 'options',+ // Left as it is nearly every time: folded to `[+]`.+ value: _optionsOpen ? '[−]' : '[+]',+ chevron: false,+ onTap: () => setState(+ () => _optionsOpen = !_optionsOpen,+ ),+ ),+ if (_optionsOpen &&+ (info != null || _gitLoading || _gitFailed))+ TtyFormRow(+ label: 'branch',+ valueColor: info == null && !_gitLoading+ ? tty.faint+ : null,+ value: _gitLoading+ ? 'Reading…'+ : info == null+ ? 'No answer from the computer'+ : _worktree+ ? 'New worktree'+ : _branchTitle,+ detail: info == null+ ? null+ : _worktree+ ? 'from $_branchTitle, in its own folder'+ : _branchNote,+ onTap: info == null || _creating+ ? null+ : () => unawaited(_chooseBranch(info)),+ ),+ if (_optionsOpen && _permissionModes.isNotEmpty)+ TtyFormRow(+ label: 'approvals',+ value: mode?.label ?? 'Auto-approve',+ detail: mode?.detail,+ valueColor: (mode?.risky ?? false)+ ? tty.red+ : null,+ onTap: _creating+ ? null+ : () => unawaited(_chooseApprovals()),+ ),+ if (_optionsOpen && _showsCodexProfile)+ TtyFormRow(+ label: 'profile',+ value: _codexProfile?.label ?? 'Default',+ onTap: _creating+ ? null+ : () => unawaited(_chooseProfile()),+ ),+ ],),),- ],- ),- if (_error != null)- Padding(- padding: const EdgeInsets.only(top: 8),- child: Text(- '✗ ${_error!}',- style: tty.style(- color: tty.red,- size: TtySize.meta,+ // The dock: the task, then Start. It rides the keyboard.+ ConstrainedBox(+ constraints: BoxConstraints(maxHeight: box.maxHeight),+ child: SingleChildScrollView(+ reverse: true,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ Tty.origin,+ 20,+ Tty.origin,+ 12,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // A first harness has nothing to go on: three first tasks to tap, the kind+ // that shows what an agent does in a minute.- if (_task.text.trim().isEmpty && !_creating)++ // Only for a first harness — once something is++ // running, somebody knows what to ask, and the++ // chips were filler over the form.++ if (nothingRunning &&++ _task.text.trim().isEmpty &&++ !_creating)+ Padding(+ padding: const EdgeInsets.only(bottom: 8),+ child: Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ for (final idea in const [+ 'Explain this project to me',+ 'Find a bug and fix it',+ 'Run the tests',+ ])+ _Suggestion(+ text: idea,+ onTap: () => setState(() {+ _task.value = TextEditingValue(+ text: idea,+ selection:+ TextSelection.collapsed(+ offset: idea.length,+ ),+ );+ }),+ ),+ ],+ ),+ ),+ Row(+ children: [+ Expanded(+ child: TtyText(+ 'task (optional)',+ color: tty.faint,+ size: TtySize.meta,+ ),+ ),+ if (count > 1800)+ TtyText(+ '$count/$kFirstTaskMaxLength',+ color: count > kFirstTaskMaxLength+ ? tty.red+ : tty.faint,+ size: TtySize.meta,+ ),+ ],+ ),+ const SizedBox(height: 6),+ TtyField(+ controller: _task,+ hint: 'What should it do?',+ lines: 6,+ maxLength: kFirstTaskMaxLength,+ action: TextInputAction.newline,+ onChanged: (_) => setState(() {}),+ trailing: [+ Align(+ alignment: Alignment.bottomRight,+ child: ListenableBuilder(+ listenable:+ _voiceIfAny ?? const _Silent(),+ builder: (context, _) {+ final status = _voiceIfAny?.status;+ return TtyFieldMic(+ live:+ status ==+ VoiceInputStatus+ .listening ||+ status ==+ VoiceInputStatus.starting,+ onTap: _creating ? null : _talk,+ );+ },+ ),+ ),+ ],+ ),+ if (_error != null)+ Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Text(+ '✗ ${_error!}',+ style: tty.style(+ color: tty.red,+ size: TtySize.meta,+ ),+ ),+ ),+ const SizedBox(height: 10),+ TtyPrimaryButton(+ // Says what it will do: start, or choose what is still missing first.+ label: _failed+ ? 'Try Again'+ : ready+ ? 'Start'+ : _engine == null+ ? 'Choose an agent'+ : 'Choose a project',+ busy: _creating,+ busyLabel: 'Starting…',+ // Never a dead button: with a choice missing, Start opens its chooser.+ onPressed: () => unawaited(_start()),+ ),+ ],+ ),),),),diff --cc mobile/lib/phone/terminal_page.dartindex 0c7d32bdc,1a18de1d7..cc676c529--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@@ -196,10 -195,21 +196,11 @@@ typedef _PageFacts = (AgentLoadStatus? agentLoadStatus,bool machinePresent,PhoneMachineStatus? machineStatus,- bool redialling,bool imagePaste,String? machineName,+ String? asking,});-/// What a page has asked for back — see [_TerminalPageState._reclaiming].-enum _Reclaim {- /// The keyboard, off another app that holds the terminal or is driving it.- control,-- /// A dead stream, reopened.- reconnect,-}-class _TerminalPageState extends State<TerminalPage>with WidgetsBindingObserver, TickerProviderStateMixin {/// Whether this page's pane ever existed.@@@ -658,8 -684,21 +659,13 @@@agentLoadStatus: machine?.agentLoadStatus,machinePresent: machine != null,machineStatus: machine == null ? null : phoneMachineStatusOf(machine),- // Only while the stream is dead — the one state it changes how the- // header reads. A live page has no reason to rebuild each time the agent- // list refreshes underneath it.- redialling:- machine != null &&- (session?.status == TerminalSessionStatus.error ||- session?.status == TerminalSessionStatus.closed) &&- 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(),);}@@@ -1027,13 -1100,21 +1038,19 @@@false;/// A window name the way tmux shortens one: the first dozen characters.- static String _windowName(String name) =>- name.length <= 12 ? name : name.substring(0, 12);+ ///+ /// ⚠️ Characters as a person counts them, not UTF-16 units: cut by `substring`, a name with an+ /// emoji near the twelfth unit kept half a surrogate pair, and the text engine throws on a string+ /// like that — the title, and the page under it, went with it.+ static String _windowName(String name) {+ final characters = name.characters;+ return characters.length <= 12 ? name : characters.take(12).toString();+ }- /// Where the reader is while scrolled up in the history — see [_CopyModePosition].+ /// Where the reader is while scrolled up in the history, or null at the end — what holds the+ /// terminal still under a reader ([_AnchoredTerminal.reading]).final _scrollback = ValueNotifier<({int above, int total})?>(null);- /// Bumped by the position's tap to take the terminal back to the end.- int _jumpToEnd = 0;-/// How far left a drag has gone, for the swipe that opens a new agent.double _swipedLeft = 0;@@@ -1816,112 -1884,121 +1833,126 @@@// 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.- //- // ⚠️ **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.- ),- ),+ 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++ //++ // ⚠️ **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,+ // Where the reader is in the history —+ // what holds the view still under them.+ scrollback: _scrollback,+ // 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 --cc mobile/test/focus_swipes_test.dartindex e932f4da9,1548a9a0c..be5c90269--- a/mobile/test/focus_swipes_test.dart+++ b/mobile/test/focus_swipes_test.dart@@@ -147,60 -146,6 +147,61 @@@ void main()expect(pushed, hasLength(1));expect(find.byType(TerminalSearchOverlay), findsNothing);});++ group('VoiceOver', () {+ // VoiceOver keeps one-finger swipes for itself, and xterm draws no semantics: the terminal+ // node is the only way it reaches the agent's words, Find and a new harness.+ SemanticsNode terminalNode(WidgetTester tester) =>+ tester.getSemantics(find.bySemanticsLabel(RegExp(r', terminal$')));++ testWidgets('reads the agent\'s name and its last lines', (tester) async {+ final handle = tester.ensureSemantics();+ await pumpFocus(tester);+ final node = terminalNode(tester);+ expect(node.label, 'a, terminal');+ expect(node.value, endsWith('output line 399'));+ expect(node.value.split('\n'), hasLength(6));+ handle.dispose();+ });++ testWidgets('Find is an action, and it opens Find', (tester) async {+ final handle = tester.ensureSemantics();+ await pumpFocus(tester);+ final node = terminalNode(tester);+ final find_ = node.getSemanticsData().customSemanticsActionIds!.map(+ CustomSemanticsAction.getAction,+ );+ expect(find_.map((a) => a!.label), containsAll(['Find', 'New harness']));- tester.binding.pipelineOwner.semanticsOwner!.performAction(++ node.owner!.performAction(+ node.id,+ SemanticsAction.customAction,+ CustomSemanticsAction.getIdentifier(+ const CustomSemanticsAction(label: 'Find'),+ ),+ );+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 400));+ expect(find.byType(TerminalSearchOverlay), findsOneWidget);+ handle.dispose();+ });++ testWidgets('New harness is an action, and it opens the form', (+ tester,+ ) async {+ final handle = tester.ensureSemantics();+ final pushed = await pumpFocus(tester);- tester.binding.pipelineOwner.semanticsOwner!.performAction(- terminalNode(tester).id,++ final node = terminalNode(tester);++ node.owner!.performAction(++ node.id,+ SemanticsAction.customAction,+ CustomSemanticsAction.getIdentifier(+ const CustomSemanticsAction(label: 'New harness'),+ ),+ );+ expect(pushed, hasLength(1));+ handle.dispose();+ });+ });}class _Pushes extends NavigatorObserver {diff --cc mobile/test/phone_edge/edge_fixture.dartindex 000000000,e52fd1177..24cfe07d4mode 000000,100644..100644--- a/mobile/test/phone_edge/edge_fixture.dart+++ b/mobile/test/phone_edge/edge_fixture.dart@@@ -1,0 -1,556 +1,557 @@@+ import 'dart:async';+ 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/cli_login.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';+ import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+ import 'package:harness_mobile/state/app_state.dart';+ import 'package:harness_mobile/terminal/terminal_session.dart';+ import 'package:harness_mobile/ws/ws_conn.dart';++ import '../agent_pager_fixture.dart' show goLive;+ import '../voice_fakes.dart';++ /// The phone screens under the edge cases a real phone meets: a small one and a large one, the+ /// text scales a person can set, both brightnesses, names nobody would design for.+ ///+ /// Everything here is a fake — no daemon, no network, no disk outside memory. See the rules in+ /// `mobile/README.md` and the incident they came from.++ /// A phone as a layout meets it, in logical pixels: the screen, the status bar over its top, the+ /// home indicator under its foot, and how tall its keyboard stands (with the suggestion strip).+ typedef Phone = ({Size size, double top, double bottom, double keyboard});++ /// iPhone SE (2nd/3rd gen): a 20pt status bar, a home button rather than an indicator.+ const Phone smallPhone = (+ size: Size(375, 667),+ top: 20,+ bottom: 0,+ keyboard: 260,+ );++ /// iPhone 15 Pro Max.+ const Phone largePhone = (+ size: Size(430, 932),+ top: 59,+ bottom: 34,+ keyboard: 346,+ );++ const phones = {'SE': smallPhone, 'Pro Max': largePhone};++ /// The phone [setPhone] last set — what [raiseKeyboard] raises.+ Phone _current = largePhone;++ /// The software keyboard up, at the current phone's height.+ void raiseKeyboard(WidgetTester tester) =>+ tester.view.viewInsets = FakeViewPadding(bottom: _current.keyboard * 3);++ void lowerKeyboard(WidgetTester tester) =>+ tester.view.viewInsets = FakeViewPadding.zero;++ /// The scales the brief asks for, and the largest the app itself can reach: `HarnessApp` pins the+ /// text scale to Settings ▸ Text size, 11–19pt over a 14pt default.+ const textScales = [1.0, 19 / 14, 1.5, 2.0];++ /// A name nobody designs for.+ const longName =+ 'refactor-the-authentication-middleware-so-that-sessions-survive-a-relaunch-of-the-app';+ const emojiName = '🚀 ship it 👩💻🔥 fix 🐛 in 🇯🇵 build';+ const rtlName = 'مساعد البرمجة الذكي للمشروع الكبير';+ const longMachine = 'Ada’s MacBook Pro (16-inch, 2024) in the upstairs office';+ const longProject =+ 'an-extraordinarily-long-project-folder-name-that-keeps-going';+ const longBranch =+ 'feature/authentication-middleware-session-survival-across-relaunch';++ /// Claude Code's permission dialog, as it lands in the pane: three answers, the first and last of+ /// which Focus puts beside the mic.+ const permissionDialog =+ '\r\n\x1b[2m────────────────────────────────────────────\x1b[0m\r\n'+ ' \x1b[1mBash command\x1b[0m\r\n'+ ' rm -rf build/ && flutter build ios\r\n'+ ' Do you want to proceed?\r\n'+ ' \x1b[36m❯ 1. Yes\x1b[0m\r\n'+ " 2. Yes, and don't ask again for rm commands\r\n"+ ' 3. No, and tell Claude what to do differently\r\n'+ '\r\n'+ ' \x1b[2mEsc to cancel · Enter to confirm\x1b[0m';++ /// Sample mode around a screen, without the sample's own runtime.+ class FakeSample implements SampleSession {+ FakeSample(this.notifier);++ @override+ final AppNotifier notifier;++ @override+ bool endCardSeen = false;++ final List<String?> left = [];++ @override+ void leave([String? result]) => left.add(result);+ }++ /// A machine the fake conn answers every request for, and accepts every frame.+ class EdgeConn extends WsConn {+ EdgeConn([this.answers = const {}, this.respond])+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ /// What the machine answers, by request type; anything else is answered with nothing.+ final Map<String, Map<String, dynamic>> answers;++ /// An answer worked out from the request — one that has to echo what it was sent, as a+ /// creation's receipt does. Null falls through to [answers].+ final Map<String, dynamic>? Function(+ String type,+ Map<String, dynamic> payload,+ )?+ respond;++ final List<(String, Map<String, dynamic>)> frames = [];+ final List<String> requests = [];++ /// Every request's payload, by type, in order.+ final Map<String, List<Map<String, dynamic>>> payloads = {};++ /// 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,+ Map<String, dynamic> payload,+ ) async {+ frames.add((type, payload));+ return true;+ }++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ requests.add(type);+ (payloads[type] ??= []).add(payload);+ return respond?.call(type, payload) ??+ answers[type] ??+ (type == 'terminal_capabilities' ? capabilities : {});+ }++ /// What the machine's terminal can do, as `terminal_capabilities` reports it — a current CLI on+ /// tmux, making projects. Answered with nothing, a machine reads as having no terminal at all.+ Map<String, dynamic> capabilities = {+ 'protocolVersion': TerminalSession.protocolVersion,+ 'backend': 'tmux',+ 'available': true,+ 'features': {'projectFolder': true, 'pasteRaw': true},+ };+ }++ /// A machine that starts every agent it is asked for, as `new-<n>`, and echoes the receipt the+ /// notifier checks — anything less reads as unconfirmed.+ Map<String, dynamic>? startsAgents(String type, Map<String, dynamic> payload) {+ if (type != 'agent_create') return null;+ return {+ 'creationId': payload['creationId'],+ 'state': 'created',+ 'agent': {+ 'id': 'new-agent',+ 'name': 'new-agent',+ 'engine': payload['engine'],+ 'terminal': {'available': true},+ },+ };+ }++ Agent edgeAgent(+ String id, {+ String? name,+ String engine = 'claude',+ String project = 'web',+ String? branch = 'main',+ int minutesAgo = 5,+ }) => Agent(+ id: id,+ name: name ?? id,+ engine: engine,+ sessionId: 'session-$id',+ status: 'active',+ project: AgentProject(name: project, cwd: '/code/$project', branch: branch),+ updatedAt: DateTime.now().subtract(Duration(minutes: minutesAgo)),+ terminalAvailable: true,+ );++ /// 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',+ bool online = true,+ AgentLoadStatus load = AgentLoadStatus.loaded,+ EdgeConn? conn,+ bool noMachines = false,+ EdgeLinks? links,+ }) {+ final session = AuthSession();+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: session,+ configStore: null,+ connectionForTest: (_) => conn ?? EdgeConn(),+ peerLinks: links ?? EdgeLinks(),+ cliLink: CliLink(runner: _noCli()),+ cliLogin: CliLogin(runner: _noCli()),+ );+ app.api = EdgeApi(app, session);+ if (noMachines) return app;+ final machine = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: machineName,+ );+ app.machines = [machine];+ app.machineStates['m'] = MachineState(machine)+ ..nodeOnline = online+ ..connectionStatus = online+ ? ConnectionStatus.connected+ : ConnectionStatus.disconnected+ ..agentLoadStatus = load+ ..terminalCapabilityAvailable = true+ ..agents = agents ?? [edgeAgent('a')];+ 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,++ String? label,+ }) 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++)+ edgeAgent(+ 'a$i',+ name: i == 0 && firstName != null ? firstName : 'agent-$i',+ minutesAgo: i,+ ),+ ];++ /// 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: (type, payload) async {+ sent?.add((type, payload));+ return true;+ },+ sendBinary: (_) async => true,+ );+ app.adoptSessionForTest(session);+ await goLive(session);+ session.status = TerminalSessionStatus.controlling;+ return session;+ }++ /// A voice controller on fakes, disposed with the test.+ ({VoiceInputController voice, FakeVoiceRecorder recorder, FakeTranscriber stt})+ edgeVoice() {+ final language = ValueNotifier('en');+ final recorder = FakeVoiceRecorder();+ final stt = FakeTranscriber();+ final voice = VoiceInputController(+ transcriber: stt.call,+ recorder: recorder,+ language: language,+ );+ addTearDown(() {+ voice.dispose();+ language.dispose();+ });+ return (voice: voice, recorder: recorder, stt: stt);+ }++ /// Sizes the test's window as [phone] on a 3x screen, with its status bar and home indicator and+ /// no keyboard — reset when the test ends.+ void setPhone(WidgetTester tester, Phone phone) {+ _current = phone;+ final insets = FakeViewPadding(top: phone.top * 3, bottom: phone.bottom * 3);+ tester.view.physicalSize = phone.size * 3;+ tester.view.devicePixelRatio = 3;+ tester.view.padding = insets;+ tester.view.viewPadding = insets;+ tester.view.viewInsets = FakeViewPadding.zero;+ addTearDown(tester.view.reset);+ }++ /// Sets the app's brightness for the test, and puts the dark it ships with back afterwards.+ void setBrightness(Brightness brightness) {+ final before = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = before);+ }++ /// [home] as the phone app mounts a screen: its theme, and the text scale set in the builder the+ /// way `HarnessApp` sets it.+ Widget phoneApp(+ Widget home, {+ double textScale = 1.0,+ Brightness brightness = Brightness.dark,+ List<NavigatorObserver> observers = const [],+ }) => grid.BrightnessScope(+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ navigatorObservers: observers,+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(textScale)),+ child: child!,+ ),+ home: home,+ ),+ );++ /// Every error Flutter reports while [body] runs — an overflow, an exception in a build — rather+ /// than only the first, which is all `takeException` keeps.+ Future<List<String>> collectErrors(Future<void> Function() body) async {+ final errors = <String>[];+ final previous = FlutterError.onError;+ FlutterError.onError = (details) {+ final text = details.exceptionAsString().split('\n').first;+ errors.add(text);+ };+ try {+ await body();+ } finally {+ FlutterError.onError = previous;+ }+ return errors;+ }++ /// Runs [pump] at every phone, scale and brightness, and fails listing every combination that+ /// reported an error — so one run shows the whole picture rather than the first overflow.+ Future<void> expectNoLayoutErrors(+ WidgetTester tester,+ Future<void> Function(double scale, Brightness brightness) pump, {+ Map<String, Phone> sizes = phones,+ List<double> scales = textScales,+ List<Brightness> brightnesses = const [Brightness.dark, Brightness.light],+ }) async {+ final failures = <String>[];+ for (final MapEntry(key: name, value: phone) in sizes.entries) {+ for (final scale in scales) {+ for (final brightness in brightnesses) {+ setPhone(tester, phone);+ final before = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ final where = '$name ×${scale.toStringAsFixed(2)} ${brightness.name}';+ try {+ final errors = await collectErrors(() => pump(scale, brightness));+ for (final error in errors.toSet()) {+ failures.add('$where: $error');+ }+ } on Object catch (error) {+ // A step of the test that could not be taken — a control the layout pushed out of+ // reach — says which phone it was on.+ fail('$where: $error');+ } finally {+ grid.AppTheme.brightness.value = before;+ }+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 1));+ }+ }+ }+ // What the screens started — a machine being re-reached, a request's timeout — runs out here,+ // before the test's end checks for timers left behind.+ await tester.pump(const Duration(seconds: 30));+ expect(failures, isEmpty, reason: failures.join('\n'));+ }++ /// Lays the screens out in the phone's own faces rather than the test font, when+ /// `PHONE_EDGE_REAL_FONTS=1` asks for it — macOS only, from the SF Mono and SF Pro files the render+ /// test reads (`test/render/phone_screens_render_test.dart`).+ ///+ /// ⚠️ **Off by default, and the tests are written to pass either way.** The test font draws every+ /// glyph a full em wide — about two thirds wider than SF Mono — so text wraps sooner than on a+ /// phone and a layout that holds here holds there. The real faces are for telling a layout that+ /// is truly short of room from one only the test font crowds.+ Future<void> loadRealFontsIfAsked() async {+ if (Platform.environment['PHONE_EDGE_REAL_FONTS'] != '1' ||+ !Platform.isMacOS) {+ return;+ }+ Future<void> load(String family, List<String> files) async {+ final loader = FontLoader(family);+ for (final file in files) {+ final bytes = await File('/Library/Fonts/$file').readAsBytes();+ loader.addFont(Future.value(ByteData.view(bytes.buffer)));+ }+ await loader.load();+ }++ const weights = ['Regular', 'Medium', 'Semibold', 'Bold'];+ for (final family in ['.AppleSystemUIFontMonospaced', 'SF Mono']) {+ await load(family, [for (final w in weights) 'SF-Mono-$w.otf']);+ }+ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {+ await load(family, [for (final w in weights) 'SF-Pro-Text-$w.otf']);+ }+ }++ /// Taps [finder] once it is scrolled into view — on a small phone at a large text size, most of+ /// a screen is below the fold.+ Future<void> tapInView(WidgetTester tester, Finder finder) async {+ // Not even built yet: a list builds only a screen's worth past what it shows.+ if (finder.evaluate().isEmpty) {+ await tester.scrollUntilVisible(+ finder,+ 200,+ scrollable: find.byType(Scrollable).first,+ );+ }+ await tester.ensureVisible(finder);+ await tester.pump();+ await tester.tap(finder);+ }++ /// Takes the screen down and runs its clocks out, so no timer outlives the test.+ Future<void> unmount(WidgetTester tester) async {+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 30));+ }++ /// Pumps a few frames of [duration] each — enough for an entrance to finish without+ /// `pumpAndSettle`, which a breathing skeleton or a spinner would never let return.+ Future<void> frames(+ WidgetTester tester, {+ int count = 4,+ Duration duration = const Duration(milliseconds: 150),+ }) async {+ for (var i = 0; i < count; i++) {+ await tester.pump(duration);+ }+ }++ /// Resolves [future] inside the test's fake clock.+ Future<T> settle<T>(WidgetTester tester, Future<T> future) async {+ T? value;+ unawaited(future.then((v) => value = v));+ await tester.pump();+ return value as T;+ }diff --cc mobile/test/phone_edge/focus_behavior_test.dartindex 000000000,d85377420..d684482a1mode 000000,100644..100644--- a/mobile/test/phone_edge/focus_behavior_test.dart+++ b/mobile/test/phone_edge/focus_behavior_test.dart@@@ -1,0 -1,1187 +1,1184 @@@+ 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/demo/sample_mode.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_font_store.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(() {+ // Whether the keyboard is up is kept once for the whole screen, not per page — so it outlives+ // a test that raised one. A pager clears it as it opens (`AgentSwipeHost`); so does each test.+ resetKeyboardSession();+ // 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);+ await focus.tapRow("don't ask again");+ await frames(tester);+ expect(focus.typed, contains('2'));+ await focus.close();+ });++ testWidgets('a question with no words to spare: a voice that matches '+ 'nothing is not sent', (tester) async {+ final focus = await _Focus.open(tester);+ focus.session.terminal.write(+ '\r\n ─────────────────────────────\r\n'+ ' Which database?\r\n'+ ' ❯ 1. Postgres\r\n'+ ' 2. SQLite\r\n'+ '\r\n'+ ' Enter to select · Esc to cancel',+ );+ await frames(tester);+ focus.stt.replies.add('the fast one');+ await tester.tap(find.byType(VoiceMicCore));+ await frames(tester);+ await tester.tap(find.byType(VoiceMicCore));+ await frames(tester, count: 2);+ expect(find.text('✗ no match — tap an answer'), findsOneWidget);+ expect(focus.typed, isNot(contains('1')));+ // The words are kept: once the question has been answered on screen, a tap on the mic+ // sends them to the agent.+ expect(focus.voice.transcript, 'the fast one');+ await focus.close();+ });++ testWidgets('multi-select: answered on screen, with the keyboard\'s keys', (+ tester,+ ) async {+ final focus = await _Focus.open(tester);+ focus.session.terminal.write(+ '\r\n ─────────────────────────────\r\n'+ ' Which checks should run?\r\n'+ ' ❯ 1. [ ] Lint\r\n'+ ' 2. [ ] Tests\r\n'+ ' 3. [ ] Build\r\n'+ '\r\n'+ ' Enter to select · Esc to cancel',+ );+ await frames(tester);+ // No keys beside the mic for a dialog that takes several answers; the keyboard comes up for+ // it instead, with Enter on its strip.+ expect(find.bySemanticsLabel(RegExp('^Answer ')), findsNothing);+ expect(find.byKey(const ValueKey('terminal-key-Enter')), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('terminal-key-Enter')));+ await frames(tester);+ expect(focus.typed, contains('\r'));+ await focus.close();+ });+ });++ group('the app going away and coming back', () {+ testWidgets('the keyboard it left with is the keyboard it comes back to', (+ tester,+ ) async {+ final focus = await _Focus.open(tester);+ focus.fill();+ await frames(tester);+ await focus.tapPrompt();+ await tester.pump();+ raiseKeyboard(tester);+ await frames(tester);+ expect(find.byKey(const ValueKey('terminal-key-esc')), findsOneWidget);++ final binding = tester.binding;+ binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);+ // Android takes the keyboard on the way out.+ lowerKeyboard(tester);+ await frames(tester);+ binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);+ binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ await frames(tester);++ expect(+ find.byKey(const ValueKey('terminal-key-esc')),+ findsOneWidget,+ reason: 'asked for again on the way back',+ );+ await focus.close();+ });+ });++ group('a picture', () {+ testWidgets('where the computer takes one: the library, cancelled, '+ 'and a camera the phone refused', (tester) async {+ final calls = <String>[];+ Object? answer;+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(+ const MethodChannel('plugins.flutter.io/image_picker'),+ (call) async {+ calls.add('${call.method} ${call.arguments['source']}');+ if (answer case final PlatformException error) throw error;+ return answer;+ },+ );+ addTearDown(+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(+ const MethodChannel('plugins.flutter.io/image_picker'),+ null,+ ),+ );+ final focus = await _Focus.open(tester);+ focus.app.stateOf('m')!.terminalImagePasteAvailable = true;+ focus.fill();+ await frames(tester);+ await focus.tapPrompt();+ await tester.pump();+ raiseKeyboard(tester);+ await frames(tester);++ // Cancelled: nothing said about it.+ await tester.tap(find.byKey(const ValueKey('terminal-key-Send image')));+ await frames(tester);+ await tester.tap(find.text('Choose from library'));+ await frames(tester);+ expect(calls, hasLength(1));+ expect(find.byType(SnackBar), findsNothing);++ // The camera refused: the one failure somebody can do something about.+ answer = PlatformException(code: 'camera_access_denied');+ await tester.tap(find.byKey(const ValueKey('terminal-key-Send image')));+ await frames(tester);+ await tester.tap(find.text('Take a photo'));+ await frames(tester);+ expect(+ find.text('Allow camera access in Settings to send a photo.'),+ findsOneWidget,+ );+ await focus.close();+ });+ });++ group('the sample', () {+ testWidgets('its end card: set up a computer, or keep playing', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final app = edgeApp(agents: [edgeAgent('sample-new-1')]);+ await liveTerminal(app, 'sample-new-1');+ final sample = FakeSample(app);+ await tester.pumpWidget(+ phoneApp(+ SampleMode(+ session: sample,+ child: TerminalPage(+ notifier: app,+ machineId: 'm',+ agentId: 'sample-new-1',+ voice: edgeVoice().voice,+ ),+ ),+ ),+ );+ await frames(tester);+ expect(find.text('✓ yours is running'), findsOneWidget);+ await tester.pump(const Duration(seconds: 9));+ await frames(tester);+ await tester.tap(find.text('Set up my computer'));+ expect(sample.left, ['set-up']);+ await tester.tap(find.text('Keep playing'));+ await frames(tester);+ expect(find.text('That’s Harness.'), findsNothing);++ // And its menu has the way out.+ await tester.tap(find.byKey(const ValueKey('terminal-title')));+ await frames(tester);+ await tester.tap(find.text('Leave the sample'));+ expect(sample.left, ['set-up', null]);+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ });++ testWidgets('its guide line steps along with what has been done', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final app = edgeApp(+ agents: [+ edgeAgent('a'),+ edgeAgent('b', name: 'b'),+ ],+ );+ await liveTerminal(app, 'a');+ final sample = FakeSample(app);+ await tester.pumpWidget(+ phoneApp(+ SampleMode(+ session: sample,+ child: TerminalPage(+ notifier: app,+ machineId: 'm',+ agentId: 'a',+ voice: edgeVoice().voice,+ ),+ ),+ ),+ );+ await frames(tester);+ expect(find.text('← start one of your own'), findsOneWidget);+ await app.handleMachineEventForTest('m', {+ 'type': 'commander_question',+ 'payload': {+ 'agentId': 'b',+ 'requestId': 'q',+ 'questions': [+ {+ 'q': 'Go?',+ 'options': ['Yes', 'No'],+ },+ ],+ },+ });+ await frames(tester);+ expect(find.text('b needs you →'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ });+ });++ group('the agent going away', () {+ testWidgets('gone from the list it opened from: the way to another', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final app = edgeApp(agents: [edgeAgent('a', name: 'fix-login')]);+ app.stateOf('m')!.agentsFromCache = true;+ final pushed = <Route<dynamic>>[];+ await tester.pumpWidget(+ phoneApp(+ Builder(+ builder: (context) => TextButton(+ onPressed: () => Navigator.of(context).push(+ MaterialPageRoute<void>(+ builder: (_) => TerminalPage(+ notifier: app,+ machineId: 'm',+ agentId: 'a',+ voice: edgeVoice().voice,+ ),+ ),+ ),+ child: const Text('home'),+ ),+ ),+ observers: [_Pushes(pushed)],+ ),+ );+ await tester.tap(find.text('home'));+ await frames(tester);+ // The machine's own list lands, without it.+ app.stateOf('m')!+ ..agentsFromCache = false+ ..agents = [edgeAgent('other')];+ await app.syncAgentsForTest('m');+ await frames(tester);+ expect(find.text('fix-login is gone'), findsOneWidget);++ await tester.tap(find.text('Open another harness'));+ await frames(tester, count: 10);+ expect(find.byType(TerminalPage), findsNothing);+ expect(find.text('home'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ });++ testWidgets('its pane closed while it is read: the page leaves', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final app = edgeApp();+ await liveTerminal(app, 'a');+ await tester.pumpWidget(+ phoneApp(+ Builder(+ builder: (context) => TextButton(+ onPressed: () => Navigator.of(context).push(+ MaterialPageRoute<void>(+ builder: (_) => TerminalPage(+ notifier: app,+ machineId: 'm',+ agentId: 'a',+ voice: edgeVoice().voice,+ ),+ ),+ ),+ child: const Text('home'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('home'));+ await frames(tester);+ expect(find.byType(TerminalPage), findsOneWidget);++ await app.closePane(app.panes.single.id);+ await frames(tester, count: 10);+ expect(find.byType(TerminalPage), findsNothing);+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ });+ });++ group('attaching', () {+ testWidgets('with animations off, the skeleton is drawn still', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final app = edgeApp();+ await tester.pumpWidget(+ phoneApp(+ MediaQuery(+ data: const MediaQueryData(disableAnimations: true),+ child: TerminalPage(+ notifier: app,+ machineId: 'm',+ agentId: 'a',+ voice: edgeVoice().voice,+ ),+ ),+ ),+ );+ await frames(tester);+ expect(find.bySemanticsLabel('Attaching to the harness'), findsOneWidget);+ // Nothing moves, so the tree settles — which a breathing skeleton never lets it do.+ await tester.pumpAndSettle();+ // ⚠️ And it is THERE: jumped to where the sweep would end. Before, a skeleton built with+ // animations already off never ran its sweep and never jumped it either — the reveal sat at+ // zero and the page waited on bare ground, which is the one thing the skeleton is for.+ expect(_skeletonReveal(tester), greaterThan(0.5));+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ });++ testWidgets('parked beside the page on screen, then brought back', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final app = edgeApp();+ final voice = edgeVoice().voice;+ Widget page({required bool ticking}) => phoneApp(+ TickerMode(+ enabled: ticking,+ child: TerminalPage(+ notifier: app,+ machineId: 'm',+ agentId: 'a',+ voice: voice,+ ),+ ),+ );+ await tester.pumpWidget(page(ticking: true));+ await tester.pump(const Duration(milliseconds: 300));+ await tester.pumpWidget(page(ticking: false));+ await tester.pump();+ expect(_skeletonReveal(tester), greaterThan(0.5));+ await tester.pumpWidget(page(ticking: true));+ await tester.pump(const Duration(milliseconds: 300));+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ });+ });++ group('more of what a thumb does', () {+ testWidgets('a restart the machine refuses says why', (tester) async {+ final focus = await _Focus.open(+ tester,+ answers: const {+ 'agent_restart': {+ 'error': 'TERMINAL_GONE',+ 'detail': 'That harness has already exited.',+ },+ },+ );+ await tester.tap(find.byKey(const ValueKey('terminal-title')));+ await frames(tester);+ await tester.tap(find.text('Restart'));+ await frames(tester);+ expect(find.text('That harness has already exited.'), findsOneWidget);+ await focus.close();+ });++ testWidgets('a tap on the prompt mid-take types what was heard, and the '+ 'keyboard picks up from there', (tester) async {+ final focus = await _Focus.open(tester);+ focus.fill();+ await frames(tester);+ focus.stt.replies.add('run the tests');+ await tester.tap(find.byType(VoiceMicCore));+ await frames(tester);+ expect(focus.voice.status, VoiceInputStatus.listening);+ await focus.tapPrompt();+ await frames(tester);+ expect(focus.typed.join(), contains('run the tests'));+ expect(focus.voice.status, VoiceInputStatus.idle);+ await focus.close();+ });++ testWidgets('a voice answer to a multi-select question is not sent', (+ tester,+ ) async {+ final focus = await _Focus.open(tester);+ focus.session.terminal.write(+ '\r\n ─────────────────────────────\r\n'+ ' Which checks should run?\r\n'+ ' ❯ 1. [ ] Lint\r\n'+ ' 2. [ ] Tests\r\n'+ '\r\n'+ ' Enter to select · Esc to cancel',+ );+ await frames(tester);+ // The keyboard came up for the dialog; down again, the mic is back.+ await tester.tap(+ find.byKey(const ValueKey('terminal-key-Hide keyboard')),+ );+ await frames(tester);+ focus.stt.replies.add('lint');+ await tester.tap(find.byType(VoiceMicCore));+ await frames(tester);+ await tester.tap(find.byType(VoiceMicCore));+ await frames(tester, count: 2);+ expect(find.text('✗ answer on screen'), findsOneWidget);+ expect(focus.typed, isNot(contains('1')));+ // Two seconds on, the take's own line takes over.+ await tester.pump(const Duration(seconds: 2));+ await frames(tester);+ expect(find.text('✗ answer on screen'), findsNothing);+ await focus.close();+ });++ testWidgets('a scroll on a terminal another app holds takes it back', (+ 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_TAKEN_OVER',+ 'reason': 'another client connected',+ 'takenBy': {'machineId': 'm', 'label': 'MacBook'},+ });+ await frames(tester);+ expect(focus.session.status, TerminalSessionStatus.takenOver);+ final before = focus.opens;+ await tester.drag(+ find.byType(TerminalPage),+ const Offset(0, 300),+ warnIfMissed: false,+ );+ await frames(tester);+ expect(focus.opens, greaterThan(before));+ await focus.close();+ });++ testWidgets('a drag toward Find that is cancelled lets Find go', (+ tester,+ ) async {+ final focus = await _Focus.open(tester);+ final centre = tester.getCenter(find.byType(TerminalPage));+ final gesture = await tester.startGesture(centre - const Offset(120, 0));+ await gesture.moveBy(const Offset(40, 0));+ await gesture.moveBy(const Offset(60, 0));+ await tester.pump();+ expect(find.byType(TerminalSearchOverlay), findsOneWidget);+ await gesture.cancel();+ await frames(tester);+ expect(find.byType(TerminalSearchOverlay), findsNothing);+ await focus.close();+ });++ testWidgets('closed twice in a row, Find goes down once', (tester) async {+ final focus = await _Focus.open(tester);+ await tester.tap(find.byKey(const ValueKey('terminal-title')));+ await frames(tester);+ await tester.binding.handlePopRoute();+ await frames(tester);+ final centre = tester.getCenter(find.byType(TerminalPage));+ await tester.dragFrom(+ centre - const Offset(120, 0),+ const Offset(300, 0),+ );+ await frames(tester);+ expect(find.byType(TerminalSearchOverlay), findsOneWidget);+ // Back, and a tap on the dimming while the first close is still running.+ await tester.binding.handlePopRoute();+ await tester.pump(const Duration(milliseconds: 50));+ await tester.binding.handlePopRoute();+ await frames(tester);+ expect(find.byType(TerminalSearchOverlay), findsNothing);+ await focus.close();+ });+ });++ group('reading back', () {- testWidgets('the copy-mode position, and one tap back to the end', (++ // The owner took the `[42/1380]` tag out: "we don't need the scrolling indicator".++ testWidgets('scrolled up, no position tag is drawn over the history', (+ tester,+ ) async {+ final focus = await _Focus.open(tester);+ focus.fill();+ await frames(tester);+ await tester.drag(+ find.byType(TerminalPage),+ const Offset(0, 500),+ warnIfMissed: false,+ );+ await frames(tester);- final position = find.bySemanticsLabel(RegExp('lines above the end'));- expect(position, findsOneWidget);- await tester.tap(position);- await frames(tester);+ expect(+ find.bySemanticsLabel(RegExp('lines above the end')),+ findsNothing,+ );+ await focus.close();+ });+ });++ group('a question, answered by voice', () {+ Future<_Focus> asked(WidgetTester tester) async {+ final focus = await _Focus.open(tester);+ focus.session.terminal.write(permissionDialog);+ await frames(tester);+ return focus;+ }++ 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;++ /// How far the attaching skeleton's sweep has come, 0 (nothing drawn) to its stop short of 1 —+ /// read off its painter, which is private to the page.+ double _skeletonReveal(WidgetTester tester) {+ final painters = [+ for (final paint in tester.widgetList<CustomPaint>(+ find.byType(CustomPaint),+ ))+ if (paint.painter.runtimeType.toString() == '_SkeletonPainter')+ paint.painter,+ ];+ expect(painters, hasLength(1));+ final dynamic painter = painters.single;+ return (painter.reveal as Animation<double>).value;+ }++ /// 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,+ Map<String, Map<String, dynamic>> answers = const {},+ }) async {+ setPhone(tester, largePhone);+ final conn = 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);+ 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));+ }++ /// A tap on the terminal row that reads [text], at its left edge.+ Future<void> tapRow(String text) async {+ final lines = session.terminal.buffer.lines;+ var row = -1;+ for (var i = 0; i < lines.length; i++) {+ if (lines[i].getText().contains(text)) row = i;+ }+ expect(row, isNot(-1), reason: '"$text" is on the screen');+ final view = _widgetTester.getRect(find.byType(TerminalView));+ final style = terminalFontStore.value;+ final cell = style.fontSize * style.height;+ final scrolled = lines.length - session.terminal.viewHeight;+ final y = view.top + (row - (scrolled < 0 ? 0 : scrolled) + 0.5) * cell;+ await _widgetTester.tapAt(Offset(view.left + 40, y));+ }++ /// [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);+ }diff --cc mobile/test/phone_edge/new_behavior_test.dartindex 000000000,a2487a6f0..566f7267fmode 000000,100644..100644--- a/mobile/test/phone_edge/new_behavior_test.dart+++ b/mobile/test/phone_edge/new_behavior_test.dart@@@ -1,0 -1,429 +1,426 @@@+ 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/agent_swipe.dart';+ import 'package:harness_mobile/phone/new_agent_draft.dart';+ import 'package:harness_mobile/phone/new_agent_page.dart';+ import 'package:harness_mobile/phone/tty_controls.dart' show TtyFieldMic;+ import 'package:harness_mobile/state/app_state.dart';++ import 'edge_fixture.dart';++ /// New as somebody fills it in: every chooser, every option, the draft kept on the way out, a+ /// double tap on Start, and a machine that goes away mid-form.+ void main() {+ tearDown(() => newAgentDraft = null);++ /// A second machine, and what each answers about its engines, profiles and repositories.+ const answers = {+ 'engines_probe': {+ 'engines': [+ {'engine': 'claude', 'installed': true},+ {'engine': 'codex', 'installed': true, 'supportsCodexHome': true},+ {'engine': 'opencode', 'installed': false, 'installable': false},+ ],+ },+ 'codex_profiles_list': {+ 'profiles': [+ {'path': '/home/ada/.codex-work', 'label': 'work'},+ {'path': '/home/ada/.codex-home', 'label': 'home'},+ ],+ },+ 'git_project_info': {+ 'isGit': true,+ 'branch': 'main',+ 'root': '/code/web',+ 'defaultRef': 'refs/heads/main',+ 'branches': [+ {'ref': 'refs/heads/main', 'name': 'main'},+ {'ref': 'refs/heads/fix/login', 'name': 'fix/login'},+ {+ 'ref': 'refs/remotes/origin/main',+ 'name': 'origin/main',+ 'remote': true,+ },+ ],+ },+ };++ Future<({AppNotifier app, EdgeConn conn})> openNew(+ WidgetTester tester, {+ bool twoMachines = false,+ bool makesProjects = true,+ List<Agent>? agents,+ }) async {+ setPhone(tester, largePhone);+ final conn = EdgeConn(answers, startsAgents);+ if (!makesProjects) {+ conn.capabilities = {...conn.capabilities, 'features': {}};+ }+ final app = edgeApp(conn: conn, agents: agents ?? [edgeAgent('a')]);+ app.stateOf('m')!+ ..projectFolderAvailable = makesProjects+ ..terminalCapabilityLoaded = true;+ if (twoMachines) {+ const other = Machine(+ machineId: 'mini',+ authMode: MachineAuthMode.remote,+ name: 'mini',+ );+ app.machines = [...app.machines, other];+ app.machineStates['mini'] = MachineState(other)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = [edgeAgent('x', project: 'api')];+ }+ await tester.pumpWidget(+ phoneApp(+ Builder(+ builder: (context) => TextButton(+ onPressed: () => Navigator.of(context).push(+ MaterialPageRoute<void>(+ builder: (_) => NewAgentPage(+ notifier: app,+ machineId: 'm',+ voice: edgeVoice().voice,+ ),+ ),+ ),+ child: const Text('focus'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('focus'));+ await frames(tester);+ return (app: app, conn: conn);+ }++ Future<void> close(WidgetTester tester, AppNotifier app) async {+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ }++ Future<void> choose(WidgetTester tester, String row, String item) async {+ await tapInView(tester, find.text(row));+ await frames(tester);+ await tapInView(tester, find.text(item, findRichText: true).last);+ await frames(tester);+ }++ testWidgets('a double tap on Start starts one harness, not two', (+ tester,+ ) async {+ final (:app, :conn) = await openNew(tester);+ final start = tester.getCenter(find.text('Start'));+ await tester.tapAt(start);+ await tester.pump(const Duration(milliseconds: 40));+ await tester.tapAt(start);+ await tester.pump(const Duration(milliseconds: 40));+ await tester.tapAt(start);+ await frames(tester, count: 20);+ expect(conn.payloads['agent_create'], hasLength(1));+ expect(find.byType(AgentSwipeHost), findsOneWidget);+ await close(tester, app);+ });++ testWidgets(+ 'a suggestion fills the task; a long one counts toward its limit',+ (tester) async {- final (:app, :conn) = await openNew(tester);++ // Nothing running: the first-task chips are a first harness's alone.++ final (:app, :conn) = await openNew(tester, agents: []);+ await tester.tap(find.text('Run the tests'));+ await tester.pump();+ expect(find.text('Run the tests'), findsOneWidget);+ expect(find.text('Explain this project to me'), findsNothing);++ await tester.enterText(find.byType(TextField), 'x' * 1900);+ await tester.pump();+ expect(find.textContaining('1900/'), findsOneWidget);-- await tester.tap(find.text('Start'));- await frames(tester, count: 20);- expect(- conn.payloads['agent_create']!.single['prompt'],- startsWith('xxx'),- );++ // Starting with a long task is the next test's; with no harness yet there is no project++ // chosen for this one to start in.++ expect(conn.payloads['agent_create'], isNull);+ await close(tester, app);+ },+ );++ testWidgets('the agent chooser: Codex, its profiles and its approvals', (+ tester,+ ) async {+ final (:app, :conn) = await openNew(tester);+ await choose(tester, 'agent', 'Codex');+ expect(find.text('Codex', findRichText: true), findsWidgets);++ // Options unfold: the approvals and the Codex profile.+ await tapInView(tester, find.text('options'));+ await frames(tester);+ await choose(tester, 'profile', 'work');+ await tapInView(tester, find.text('approvals'));+ await frames(tester);+ final modes = find.byType(ListView).last;+ expect(modes, findsOneWidget);+ await tester.tapAt(tester.getCenter(find.byType(ModalBarrier).last));+ await frames(tester);++ await tapInView(tester, find.text('Start'));+ await frames(tester, count: 20);+ final created = conn.payloads['agent_create']!.single;+ expect(created['engine'], 'codex');+ expect(created['codexHome'], '/home/ada/.codex-work');+ await close(tester, app);+ });++ testWidgets('an engine the machine cannot install is offered, and says so', (+ tester,+ ) async {+ final (:app, conn: _) = await openNew(tester);+ await tapInView(tester, find.text('agent'));+ await frames(tester);+ // Behind `more`: the rest, A to Z.+ final more = find.text('more');+ if (more.evaluate().isNotEmpty) {+ await tester.tap(more.first);+ await frames(tester);+ }+ await tester.scrollUntilVisible(+ find.text('not installed'),+ 200,+ scrollable: find.byType(Scrollable).last,+ );+ expect(find.text('not installed'), findsWidgets);+ await close(tester, app);+ });++ testWidgets('the branch: this folder, a new worktree, another branch, a '+ 'new name', (tester) async {+ final (:app, :conn) = await openNew(tester);+ await tapInView(tester, find.text('options'));+ await frames(tester);+ expect(find.text('branch'), findsOneWidget);++ await choose(tester, 'branch', 'New Worktree');+ expect(find.textContaining('in its own folder'), findsWidgets);+ await choose(tester, 'branch', 'main');++ await choose(tester, 'branch', '+ Other Branch');+ // The branch picker: pick an existing one.+ await tapInView(tester, find.text('fix/login', findRichText: true).last);+ await frames(tester);++ // And a new name, cleaned the way Git takes it.+ await choose(tester, 'branch', '+ Other Branch');+ final typeOne = find.textContaining('New branch', findRichText: true);+ if (typeOne.evaluate().isNotEmpty) {+ await tester.tap(typeOne.last);+ await frames(tester);+ await tester.enterText(find.byType(TextField).last, 'fix the login');+ await tester.pump();+ expect(find.text('Git will call it fix-the-login'), findsOneWidget);+ await tester.tap(find.text('Use'));+ await frames(tester);+ }++ await tapInView(tester, find.text('Start'));+ await frames(tester, count: 20);+ expect(conn.payloads['agent_create'], hasLength(1));+ await close(tester, app);+ });++ testWidgets('the project: a folder on another computer moves the harness '+ 'there', (tester) async {+ final (:app, :conn) = await openNew(tester, twoMachines: true);+ await choose(tester, 'project', 'api');+ expect(find.text('mini:api', findRichText: true), findsWidgets);+ await tapInView(tester, find.text('Start'));+ await frames(tester, count: 20);+ await close(tester, app);+ });++ testWidgets('the project: a new folder, and a repository by URL', (+ tester,+ ) async {+ final (:app, :conn) = await openNew(tester);+ await choose(tester, 'project', '+ New Folder');+ expect(find.text('studio:New folder', findRichText: true), findsWidgets);++ await choose(tester, 'project', '+ Clone Repository');+ await tester.enterText(find.byType(TextField).last, 'not a repository');+ await tester.tap(find.text('Select'));+ await tester.pump();+ expect(find.text('That is not a GitHub repository.'), findsOneWidget);+ await tester.enterText(+ find.byType(TextField).last,+ 'https://github.com/ada/engine',+ );+ await tester.tap(find.text('Select'));+ await frames(tester);+ expect(find.text('studio:engine', findRichText: true), findsWidgets);++ await tapInView(tester, find.text('Start'));+ await frames(tester, count: 20);+ expect(conn.payloads['agent_create'], hasLength(1));+ await close(tester, app);+ });++ testWidgets('a computer too old to make a project is not offered it', (+ tester,+ ) async {+ final (:app, conn: _) = await openNew(tester, makesProjects: false);+ await tapInView(tester, find.text('project'));+ await frames(tester);+ // Left out rather than drawn dead (see `new_agent_chooser.dart`).+ expect(find.text('+ Open Folder', findRichText: true), findsOneWidget);+ expect(find.text('+ Clone Repository', findRichText: true), findsNothing);+ expect(find.text('+ New Folder', findRichText: true), findsNothing);+ await close(tester, app);+ });++ testWidgets('no project yet: Start asks for one first', (tester) async {+ final (:app, :conn) = await openNew(tester, agents: []);+ expect(find.text('Choose a project', findRichText: true), findsWidgets);+ await tapInView(+ tester,+ find.text('Choose a project', findRichText: true).last,+ );+ await frames(tester);+ expect(find.text('+ Open Folder', findRichText: true), findsOneWidget);+ expect(conn.payloads['agent_create'], isNull);+ await close(tester, app);+ });++ testWidgets('the form is kept on the way out, and back on the way in', (+ tester,+ ) async {+ final (:app, conn: _) = await openNew(tester);+ await tester.enterText(find.byType(TextField), 'write the release notes');+ await tester.binding.handlePopRoute();+ await frames(tester, count: 6);+ expect(newAgentDraft?.task, 'write the release notes');++ await tester.tap(find.text('focus'));+ await frames(tester);+ expect(find.text('write the release notes'), findsOneWidget);++ // Nothing typed and nothing chosen is not a draft.+ await tester.enterText(find.byType(TextField), '');+ await tester.binding.handlePopRoute();+ await frames(tester, count: 6);+ await close(tester, app);+ });++ testWidgets('its computer goes offline mid-form: the form stays, and says so '+ 'on Start', (tester) async {+ final (:app, conn: _) = await openNew(tester);+ await app.handleMachineEventForTest('m', {+ 'type': 'node_status',+ 'payload': {'online': false},+ });+ await frames(tester);+ expect(find.byType(NewAgentPage), findsOneWidget);+ await tapInView(tester, find.text('Start'));+ await frames(tester, count: 20);+ expect(tester.takeException(), isNull);+ await close(tester, app);+ });++ testWidgets('said into the task: added to what was typed', (tester) async {+ setPhone(tester, largePhone);+ final app = edgeApp();+ final voice = edgeVoice();+ voice.stt.replies.add(' then deploy it ');+ await tester.pumpWidget(+ phoneApp(NewAgentPage(notifier: app, machineId: 'm', voice: voice.voice)),+ );+ await frames(tester);+ await tester.enterText(find.byType(TextField), 'fix the tests');+ await tester.tap(find.byType(TtyFieldMic));+ await frames(tester);+ await tester.tap(find.byType(TtyFieldMic));+ await frames(tester);+ expect(find.text('fix the tests then deploy it'), findsOneWidget);+ await close(tester, app);+ });++ testWidgets('Open Folder: the computer\'s folders, and back out', (+ tester,+ ) async {+ final (:app, conn: _) = await openNew(tester);+ await choose(tester, 'project', '+ Open Folder');+ expect(find.text('Cancel'), findsWidgets);+ await tester.tap(find.text('Cancel').last);+ await frames(tester);+ expect(find.text('studio:web', findRichText: true), findsWidgets);+ await close(tester, app);+ });++ testWidgets('a draft with no agent chosen: Start asks for one', (+ tester,+ ) async {+ newAgentDraft = const NewAgentDraft(+ machineId: 'm',+ engine: null,+ permissionMode: 'auto',+ folder: '/code/web/',+ task: 'pick up where I left off',+ );+ final (:app, :conn) = await openNew(tester);+ expect(find.text('Choose an agent', findRichText: true), findsWidgets);+ await tapInView(tester, find.text('Choose an agent').last);+ await frames(tester);+ expect(find.text('Agent'), findsOneWidget);+ expect(conn.payloads['agent_create'], isNull);+ await close(tester, app);+ });++ testWidgets('a repository the computer could not read says so', (+ tester,+ ) async {+ setPhone(tester, largePhone);+ final app = edgeApp(+ conn: EdgeConn(const {+ 'git_project_info': {'error': 'E2EE_REQUIRED'},+ }),+ );+ await tester.pumpWidget(+ phoneApp(NewAgentPage(notifier: app, machineId: 'm')),+ );+ await frames(tester);+ await tester.tap(find.text('options'));+ await frames(tester);+ expect(+ find.text('No answer from the computer', findRichText: true),+ findsOneWidget,+ );+ await close(tester, app);+ });++ testWidgets('the task\'s mic, with the page\'s own voice when none is given', (+ tester,+ ) async {+ // The microphone plugin's channel: permission refused, so nothing records.+ const record = MethodChannel('com.llfbandit.record/messages');+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(record, (call) async {+ if (call.method == 'hasPermission') return false;+ return null;+ });+ addTearDown(+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(record, null),+ );+ setPhone(tester, largePhone);+ final app = edgeApp();+ await tester.pumpWidget(+ phoneApp(NewAgentPage(notifier: app, machineId: 'm')),+ );+ await frames(tester);+ await tester.tap(find.byType(TtyFieldMic));+ await frames(tester);+ expect(tester.takeException(), isNull);+ await close(tester, app);+ });+ }diff --cc mobile/test/phone_edge/settings_behavior_test.dartindex 000000000,fe5cff9d4..a11937af3mode 000000,100644..100644--- a/mobile/test/phone_edge/settings_behavior_test.dart+++ b/mobile/test/phone_edge/settings_behavior_test.dart@@@ -1,0 -1,160 +1,160 @@@+ import 'package:flutter/material.dart';+ import 'package:flutter_test/flutter_test.dart';+ import 'package:harness_mobile/core/models.dart';+ import 'package:harness_mobile/demo/sample_mode.dart';+ import 'package:harness_mobile/phone/machines_tab.dart';+ import 'package:harness_mobile/phone/settings_page.dart';+ import 'package:harness_mobile/phone/welcome/how_it_works.dart';+ import 'package:harness_mobile/state/app_state.dart';+ import 'package:package_info_plus/package_info_plus.dart';++ import 'edge_fixture.dart';++ /// Settings as somebody goes through it: every row that opens something, opened and put away.+ ///+ /// ⚠️ **No choice is made in any of them.** Each preference here writes through a store whose+ /// default home is the real state file under `~/.harness` — a test that picked a font would write+ /// to the developer's own. Opening a sheet reads; only a tap on one of its rows writes.+ void main() {+ setUpAll(+ () => PackageInfo.setMockInitialValues(+ appName: 'Harness',+ packageName: 'ai.autonomous.harness',+ version: '1.2.3',+ buildNumber: '456',+ buildSignature: '',+ ),+ );++ Future<AppNotifier> openSettings(+ WidgetTester tester, {+ bool large = true,+ bool sample = false,+ CurrentUserProfile? user,+ }) async {+ setPhone(tester, largePhone);+ final app = edgeApp();+ app.currentUser =+ user ??+ const CurrentUserProfile(+ id: 'u',+ name: 'Ada Lovelace',+ email: '[email protected]',+ );+ final page = SettingsPage(notifier: app, large: large);+ await tester.pumpWidget(+ phoneApp(+ Builder(+ builder: (context) => TextButton(+ onPressed: () => Navigator.of(context).push(+ MaterialPageRoute<void>(+ builder: (_) => sample+ ? SampleMode(session: FakeSample(app), child: page)+ : page,+ ),+ ),+ child: const Text('focus'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('focus'));+ await frames(tester);+ return app;+ }++ Future<void> close(WidgetTester tester, AppNotifier app) async {+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ }++ /// Opens what [row] opens, checks [shows] is on screen, and puts it away with the barrier.+ Future<void> peek(WidgetTester tester, String row, String shows) async {+ await tapInView(tester, find.text(row));+ await frames(tester);+ expect(find.text(shows, findRichText: true), findsWidgets, reason: row);+ await tester.tapAt(const Offset(20, 80));+ await frames(tester);+ }++ testWidgets('the account, the sheets, the phone\'s name and the build', (+ tester,+ ) async {+ final app = await openSettings(tester);+ expect(find.text('A'), findsOneWidget, reason: 'the avatar\'s initial');++ await peek(tester, 'Ada Lovelace', 'Sign out');- await tapInView(tester, find.text('This phone'));++ await tapInView(tester, find.text('Phone name'));+ await frames(tester);+ expect(find.text('Leave empty to use the name above.'), findsOneWidget);+ await tester.tap(find.text('Cancel'));+ await frames(tester);+ await peek(tester, 'Font', 'Terminal font');+ await peek(tester, 'Colors', 'Terminal colors');+ await peek(tester, 'Language', 'Voice input language');- await peek(tester, 'Palette', 'Color palette');++ await peek(tester, 'App colors', 'App colors');++ // At the foot: the version and the build, read from the bundle.+ await tester.scrollUntilVisible(+ find.text('456'),+ 200,+ scrollable: find.byType(Scrollable).last,+ );+ expect(find.text('1.2.3'), findsOneWidget);+ await close(tester, app);+ });++ testWidgets('Computers and How Harness works open their pages', (+ tester,+ ) async {+ final app = await openSettings(tester, large: false);+ await tapInView(tester, find.text('Computers'));+ await frames(tester, count: 6);+ expect(find.byType(MachinesTab), findsOneWidget);+ await tester.binding.handlePopRoute();+ await frames(tester, count: 6);++ await tapInView(tester, find.text('How Harness works'));+ await frames(tester, count: 6);+ expect(find.byType(HowItWorksPage), findsOneWidget);+ await tester.binding.handlePopRoute();+ await frames(tester, count: 6);++ // Pushed from a terminal's menu: the back chevron is the way out.+ await tester.tap(find.bySemanticsLabel(RegExp('Back')).first);+ await frames(tester, count: 6);+ expect(find.byType(SettingsPage), findsNothing);+ await close(tester, app);+ });++ testWidgets('an account whose name is only an email, or nothing at all', (+ tester,+ ) async {+ var app = await openSettings(+ tester,+ user: const CurrentUserProfile(id: 'u', email: '[email protected]'),+ );+ expect(find.text('Z'), findsOneWidget);+ await close(tester, app);++ app = await openSettings(+ tester,+ user: const CurrentUserProfile(id: 'u', name: ' ', email: ''),+ );+ expect(find.text('?'), findsOneWidget);+ await close(tester, app);+ });++ testWidgets('inside the sample: the way out, and no sample to try', (+ tester,+ ) async {+ final app = await openSettings(tester, sample: true);+ expect(find.text('Try the sample'), findsNothing);+ expect(find.text('sample'), findsOneWidget);- await tester.tap(find.text('Leave sample'));++ await tester.tap(find.text('Leave the sample'));+ await frames(tester);+ await close(tester, app);+ });+ }diff --cc mobile/test/voice_mic_fab_test.dartindex 09ffc2a74,fa85559db..bbe74aa79--- a/mobile/test/voice_mic_fab_test.dart+++ b/mobile/test/voice_mic_fab_test.dart@@@ -140,41 -161,4 +140,41 @@@ void main()expect(recorder.starts, 0);expect(frames, isEmpty);});++ testWidgets(+ 'VoiceOver can cancel a take — the swipe down is VoiceOver\'s own',+ (tester) async {+ final handle = tester.ensureSemantics();+ var cancelled = 0;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Center(+ child: VoiceMicButton(+ face: VoiceMicFace.listening,+ onPressed: () {},+ onSwipeDown: () => cancelled++,+ ),+ ),+ ),+ ),+ );+ final node = tester.getSemantics(find.byType(VoiceMicButton));+ // One word while the mic is open: a read-out sentence would land in the take.+ expect(node.label, 'Send');- tester.binding.pipelineOwner.semanticsOwner!.performAction(++ node.owner!.performAction(+ node.id,+ SemanticsAction.customAction,+ CustomSemanticsAction.getIdentifier(+ const CustomSemanticsAction(label: 'Cancel'),+ ),+ );- tester.binding.pipelineOwner.semanticsOwner!.performAction(++ node.owner!.performAction(+ node.id,+ SemanticsAction.dismiss,+ );+ expect(cancelled, 2);+ handle.dispose();+ },+ );}