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
Finish phone panel polish and offline coverage
deehw49383f4204b4
diff --git a/docs/research/2026-09-28-phone-overnight.md b/docs/research/2026-09-28-phone-overnight.mdindex c6af9b6e5..c89ced773 100644--- a/docs/research/2026-09-28-phone-overnight.md+++ b/docs/research/2026-09-28-phone-overnight.md@@ -8,12 +8,12 @@ The goal set at bedtime was to make the Harness phone app world class. That meanThat audience is people with strong consumer-app taste who now run Claude Code and Codex and want to manage them from a phone.-Everything below is on branch `phone-overnight-polish` (pushed to origin). Nothing was merged or released overnight. **The last section is the handoff for the next agent.**+Everything below is on branch `phone-overnight-polish` (pushed to origin), in [PR #398](https://github.com/autonomous-ai/openharness/pull/398). Nothing has been merged or released. **The last section is the handoff for the next agent.**## In one screen-- **Tests:** 486 → 1,555 (plus 25 skipped). The whole suite passes. `flutter analyze` is clean outside `third_party/`.-- **Coverage:** 50.4% → **87.0%** of lines, not counting `third_party/`.+- **Tests:** 486 → 1,555 overnight → **1,600** after continuation (plus 25 render tests skipped in the ordinary suite; all 25 pass when rendering is enabled). The whole suite passes. `flutter analyze` is clean outside `third_party/`.+- **Coverage:** 50.4% → 87.0% overnight → **88.8%** (18,185/20,485 lines), not counting `third_party/`.| Area | Coverage ||---|---|@@ -22,36 +22,38 @@ Everything below is on branch `phone-overnight-polish` (pushed to origin). Nothi| p2p | 98.5% || core | 97.2% || usage | 95.0% |- | ws | 93.1% |+ | ws | 94.8% || analytics | 92.1% || widgets | 89.8% |- | phone | 89.0% |+ | phone | 89.1% || shared | 81.2% |- | state | 80.3% |- | demo | 77.0% |- | terminal | 74.9% |- | logging | 72.6% |- | settings | 46.2% |- | clipboard | 33.3% |+ | state | 83.0% |+ | demo | 79.9% |+ | terminal | 84.4% |+ | logging | 87.6% |+ | settings | 100.0% |+ | clipboard | 88.9% |- **Dead code:**- 52 files and about 17,100 lines the phone never runs were deleted. Each deletion was proved with tree-shaken AOT builds for iOS and Android.- The desktop's half of `AppNotifier` was cut: 7,100 more lines, 13 files. `viewer` is now non-nullable.-- **Bugs:** 38 real bugs fixed, each with a regression test (listed below).+ - The continuation removes the remaining handoff list: unused dial routing and grid navigation, local plaintext transport, the unauthenticated local API mode, local-file opening and the CLI log channel. The cleanup was prepared and tested in a disposable copy before application.+- **Bugs:** 40 real bugs fixed, each with a regression test (listed below). The continuation fixes queued log notifications after disposal and misleading local-daemon explanations for phone backend failures.- **Test safety:** every test now runs in a throwaway home (`test/flutter_test_config.dart`), so no test can read or write a developer's `~/.harness`. `test/test_home_guard_test.dart` pins this.-- **Review panel:** five AI personas, two rounds. The average score went from 6/10 to 7/10. The round 2 fixes landed after scoring; round 3 has not run yet.+- **Offline verification:** HTTP clients are blocked by default in tests. API and WebSocket tests now use in-memory transports, including handshakes, token refreshes and reconnects. The simulator tour launches `SampleApp` directly without reading a saved account.+- **Review panel:** the four requested personas completed rounds 3 and 4. All now score the app **8+/10**; the round-4 mean is **8.05/10**. [Round-3/4 report](2026-09-28-phone-panel-rounds-3-4.md).## The review panelFive personas each reviewed renders of every phone screen. In round 2 they also saw an 18-screen walk-through of the real app, recorded on the iOS simulator in sample mode.-| Persona | Lens | Round 1 | Round 2 |-|---|---|---|---|-| Maya | design lead on two iconic consumer apps | 6 | 7 |-| Theo | founder of a Things/Superhuman/Linear-style productivity app | 6 | – |-| Priya | runs 6–10 Claude Code and Codex harnesses across three machines | 6 | 7 |-| Sam | first-time user with consumer taste; Claude Code on the Mac, no Harness | 6 | 7 |-| Jordan | former Apple Design Award juror (HIG, accessibility) | 6 | 7 |+| Persona | Lens | Round 1 | Round 2 | Round 3 | Round 4 |+|---|---|---|---|---|---|+| Maya | design lead on two iconic consumer apps | 6 | 7 | 7 | 8 |+| Theo | founder of a Things/Superhuman/Linear-style productivity app | 6 | – | – | – |+| Priya | runs 6–10 Claude Code and Codex harnesses across three machines | 6 | 7 | 7.5 | 8.2 |+| Sam | first-time user with consumer taste; Claude Code on the Mac, no Harness | 6 | 7 | 7 | 8 |+| Jordan | former Apple Design Award juror (HIG, accessibility) | 6 | 7 | 7 | 8 |### Round 1 findings that all five agreed on, and what happened@@ -80,6 +82,18 @@ Five personas each reviewed renders of every phone screen. In round 2 they also- **"Stop this harness…"** stays small at the foot of the menu but is now red; faint grey read as disabled.- **Form rows** put the label on the value's first line; "approvals" used to sit beside its note.+### Rounds 3 and 4++- The attention line has a fixed yellow dot, solid backing and readable text aligned to the terminal gutter.+- Chooser sheets fit their content, align headings with rows and support native drag dismissal.+- Field placeholders have stronger contrast, verified numerically in a regression test.+- Unlock uses the desktop's verified `Machines ▸ computer ▸ Set password` route and identifies the password as the Harness phone password.+- The sample is prominent on Welcome and setup, and labels pickup, Focus, Find and New. Its terminal input hint fits beside the mic.+- The Settings avatar is neutral. Incomplete sign-in codes visibly disable Sign in. New's compact keyboard summary puts the project first.+- All 25 screens were rendered again. The sample simulator walkthrough was recorded again and now captures 19 states, including the written help page.++These are AI persona reviews of offline artifacts. They establish the visual score; live VoiceOver, real-device speech and production connection behavior require separate verification.+## Bugs fixed (each with a regression test)**Sign-in and pairing**@@ -98,6 +112,7 @@ Five personas each reviewed renders of every phone screen. In round 2 they also- A data channel closing under an open link no longer throws uncaught.- A second `terminal_ready` for one open no longer leaks a heartbeat.- A locked state file no longer stops a machine reconnecting for good.+- Phone backend failures no longer tell the user that a local daemon is down or restarting.- A terminal switched off by an unanswered negotiation is asked about again.**Terminal and Focus**@@ -132,6 +147,7 @@ Five personas each reviewed renders of every phone screen. In round 2 they also- Log redaction blanks plain-base64 bearer tokens, Basic auth and sign-in codes in URLs.- An analytics event trimmed while on the wire no longer takes the next one with it.- A busy analytics visit keeps `analytics.json` within a minute of the clock.+- A queued log update no longer notifies a disposed stream.## Decisions already made by the user (do not re-propose)@@ -145,7 +161,7 @@ Five personas each reviewed renders of every phone screen. In round 2 they also### State-- Branch `phone-overnight-polish`, pushed. It is 113 commits ahead of `main`. **No PR is open yet**; opening one is the next step (the user merges).+- Branch `phone-overnight-polish`, pushed. [PR #398](https://github.com/autonomous-ai/openharness/pull/398) is open for the user to review and merge. The continuation and its validation are included; no merge or release has run.- Merged into it and finished: `coverage-rest` (coverage engineer), `desktop-cut` (the desktop's half of the notifier), and the phone-screens and state-core engineers' passes. No engineer is still running.- Never commit `mobile/ios/Runner.xcodeproj/project.pbxproj`. It carries the local signing team and stays modified in the worktree.@@ -166,40 +182,20 @@ From `mobile/`, with Flutter 3.47.2:- Every git and gh action is done as `deehw`.- No private data in the repo (no home paths, real usernames or emails).-### Open work, in order--1. **Open the PR** for `phone-overnight-polish`, with this document as its summary.-2. **Panel round 3.** Re-render, re-record the walk-through, and re-run the four personas on the same brief. The target is 8+/10.-3. **Round 2 items still open.** None of these conflict with the user's decisions:- - **The "needs you" line above the mic.**- - Its dot is green, but green means *working* in Find; make it the asking yellow.- - Give it an opaque band so terminal text never shows through it.- - Keep the dot at a fixed offset from the text; it moves between frames.- - Left-align it on the terminal gutter.- - **Sheets.**- - The Agent sheet covers about 75% of the screen for three rows; size sheets to their content.- - The sheet titles "Project" and "Agent" sit about 4pt right of the rows below them.- - Consider the system grabber.- - **Placeholder contrast.** #8B8B8B on the #2C2C2C raised field is 4.1:1. Use about #9A9A9A (5:1).- - **The Unlock page** says "Machines → studio → Set password". Check what the desktop menu actually calls it first, then use the same word, with ▸ as elsewhere.- - **The sample.**- - The pick-up heading should say it is a sample.- - The placeholder in Claude's input line (`Try "run the…`) runs under the mic; shorten it in `lib/demo/sample_scripts.dart`.- - "Try the sample" should be a first-class row near the top of the set-up page, not the last, dimmest line.- - **Settings:** the lone "?" avatar is the only blue in the app.-4. **Dead code** found by the desktop-cut engineer, now with no callers:- - In `app_state.dart`:- - `SpokenTaskRequest`, `spokenTasks`, `reportVoiceRoute` and the handling of `voice_route_request`;- - `selectAutonomousEnv`;- - `hasNavigationRail`, and the pin and grid-keyboard methods (`togglePinPane`, `focusLastPane`, `toggleZoomPane`, `focusPaneBy*`, `movePaneBy`, `reorderPane`);- - `paneFocusRequest`, `seedSwarm`, `openAgentFromDial`.- - Elsewhere:- - `DialState.restore`;- - `WsTransportKind.localPlaintext` in `ws_conn.dart`/`ws_pool.dart`;- - ApiClient's no-auth `localCliBaseUrl` mode;- - `TerminalLinkOpener.open(isLocalMachine:)`;- - the `cliLog` channel.-5. **Coverage gaps**, weakest first: `settings` (46%), `clipboard`, `logging` (73%), `terminal` (75%), `demo` (77%), `state` (80%).+### Continuation completed++1. Opened PR #398 with this report as its starting summary.+2. Ran the four-person panel twice more. Round 4: Maya 8, Priya 8.2, Sam 8, Jordan 8; all would use it daily.+3. Completed the round-2 attention-line, sheet, placeholder, Unlock-copy, sample-discovery and avatar work.+4. Removed every item in the remaining dead-code list: `SpokenTaskRequest` and its unused routing stream/handler; `selectAutonomousEnv`; `hasNavigationRail` and unused pin/grid-keyboard methods; `paneFocusRequest`, `seedSwarm`, `openAgentFromDial`; `DialState.restore`; local plaintext WebSockets; ApiClient's no-auth local mode; the local-machine terminal-file branch; and `cliLog`. Caller searches and the CLI's local-only event routing established that these paths cannot serve the phone. The explicitly approved patch was tested before and after application.+5. Added coverage in the requested order: settings persistence/reset; clipboard failures; logging lifecycle; terminal preferences, downloads and link opening; sample requests/lifecycle; and layout restoration/write coalescing. Every new real bug has a regression test.+6. Final validation: **1,600 tests pass**, 25 conditional render skips; **88.8% line coverage** excluding `third_party/`; analyzer clean outside `third_party/`. The separate 25-render run and 19-state sample simulator tour pass.++### Remaining observations++- The [round-4 report](2026-09-28-phone-panel-rounds-3-4.md) records optional finishing details: retain computer/project identity in asking Find rows, improve long-value spacing and compact agent labels, and simplify recovery/glossary copy. None blocks the panel's 8/10 threshold.+- Future coverage work can concentrate on the remaining state and sample branches. The desktop-only paths removed in this continuation should not be restored merely to exercise them in tests.+- The proposals below remain exactly as left by the user. No proposal has been implemented or reclassified as approved.### Proposals that need the user's decision (do not build without it)diff --git a/docs/research/2026-09-28-phone-panel-rounds-3-4.md b/docs/research/2026-09-28-phone-panel-rounds-3-4.mdnew file mode 100644index 000000000..4cd3ef2f6--- /dev/null+++ b/docs/research/2026-09-28-phone-panel-rounds-3-4.md@@ -0,0 +1,44 @@+# Phone review panel, rounds 3 and 4++Four independent AI personas reviewed every phone render and the sample-mode simulator tour. The fourth round meets the requested 8/10 threshold for every persona.++| Persona | Lens | Round 3 | Round 4 | Daily use after round 4 |+|---|---|---:|---:|---|+| Maya | Consumer-app design lead | 7 | 8 | Yes |+| Priya | 6–10 harnesses across three computers | 7.5 | 8.2 | Yes |+| Sam | First-time user | 7 | 8 | Yes |+| Jordan | Apple Design Award and accessibility lens | 7 | 8 | Yes |+| **Mean** | | **7.125** | **8.05** | |++## Evidence++- Round 3: 25 screen renders and 17 simulator tour captures.+- Round 4: 25 refreshed renders, 19 simulator tour captures, and a new walkthrough video.+- The integration tour now launches `SampleApp` directly. It never loads a saved account, and the sample's terminal, voice and computer replies run in process.+- The render fixture remains 42 columns wide. Chooser tests cover short lists, long lists, keyboard clearance and drag dismissal; sample tests pin the attention dot's position.++These scores describe the visible experience in offline artifacts. VoiceOver behavior, real-device speech accuracy and production connection performance require separate verification. Dynamic Type and the other user-decision proposals remain deferred.++## Changes reviewed in round 4++- A fixed yellow attention dot, opaque backing and readable text aligned to the terminal gutter.+- Agent and Project sheets that fit their contents, with aligned titles, scrolling when needed and a native grabber.+- Stronger field-placeholder contrast, including a numerical contrast regression test.+- A visible sample entry on Welcome and near the top of setup; sample identity on pickup, Focus, Find and New; a shorter sample terminal hint.+- Unlock copy that identifies the Harness phone password, promotes scanning and uses the desktop's verified `Machines ▸ computer ▸ Set password` wording.+- A neutral Settings avatar and visibly disabled sign-in until the four-digit code is complete.+- Project-first context in New's compact keyboard summary.++All four reviewers considered the material round-3 findings resolved. No visible blocker to 8/10 remained within the authorized scope.++## Remaining observations++- Priya: asking rows in Find should retain computer/project identity alongside the question. This concerns Find rows; it does not implement the deferred Focus header.+- Maya and Sam: leave more space between long project values and the chooser chevron.+- Priya and Jordan: the compact New summary can still abbreviate the agent name; two short lines could preserve both values.+- Maya and Sam: Unlock recovery could better serve someone who has never set a password; an empty password could have a clearer inactive action.+- Sam and Priya: shorten the glossary and avoid promising that separate worktrees isolate shared services.++The early play-icon objection was withdrawn after checking that setup opens a distinct video page. The written glossary is a separate destination.++The user's decisions on voice auto-send, microphone placement, the word “harness”, the asking label and the absence of a scroll indicator remain in place. The decision list in the [handoff](2026-09-28-phone-overnight.md) is unchanged.diff --git a/mobile/integration_test/tour_test.dart b/mobile/integration_test/tour_test.dartindex ffe28c8a6..ff38cfb3e 100644--- a/mobile/integration_test/tour_test.dart+++ b/mobile/integration_test/tour_test.dart@@ -2,11 +2,11 @@ import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:integration_test/integration_test.dart';-import 'package:harness_mobile/main.dart' as app;+import 'package:harness_mobile/demo/main_sample.dart' show SampleApp;import 'package:harness_mobile/phone/voice_mic_face.dart';/// Every state of the phone app, in the real app on a simulator, over the offline sample — a-/// screenshot each, for review. Signed out on a clean install, so nothing reaches a real account.+/// screenshot each, for review. Starts the standalone sample directly: no saved account is loaded.////// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \/// --target=integration_test/tour_test.dart@@ -51,10 +51,8 @@ void main() {await wait(1000);}- await app.main();- await waitFor(find.text('Is Harness on your computer?'));- // The sample, behind a long press on the wordmark: kept for these screenshots.- await tester.longPress(find.byKey(const ValueKey('welcome-wordmark')));+ await tester.pumpWidget(const SampleApp());+ await waitFor(find.text('fix-login', findRichText: true));await wait(3000);// It opens on the sessions to pick up, as a new phone does.await shot('pick-up');@@ -148,6 +146,12 @@ void main() {if (await tapIf(find.text('Settings'))) {await wait(1200);await shot('settings');+ await tester.scrollUntilVisible(+ find.text('How Harness works'),+ 250,+ scrollable: find.byType(Scrollable).last,+ );+ await shot('settings-help');if (await tapIf(find.text('How Harness works'))) {await wait(1000);await shot('how-it-works');diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dartindex 4e51a4fd9..d92830d21 100644--- a/mobile/lib/api/api_client.dart+++ b/mobile/lib/api/api_client.dart@@ -10,26 +10,31 @@ import 'access_token_source.dart';import 'bearer_auth_interceptor.dart';import 'multipart_body.dart';-/// Control-plane REST client.-///-/// In a desktop build every call goes to the LOCAL `harness` CLI (loopback, no credential — see-/// CLAUDE.md's naming/architecture notes for why), which proxies to the real backend using its own-/// saved SSO session, and this app never holds a bearer token itself. A viewer build has no CLI:-/// given [auth], the same calls go straight to the backend, signed with the session the app holds.-/// Terminal bytes ride the WS path either way.+/// Authenticated control-plane REST client for the phone.class ApiClient {final AppConfig config;final AuthSession session;final AccessTokenSource? auth;++ /// An in-process transport for tests; authentication and serialization still run.+ final HttpClientAdapter? httpClientAdapter;late final Dio _dio = _buildDio();- ApiClient({required this.config, required this.session, this.auth});+ ApiClient({+ required this.config,+ required this.session,+ this.auth,+ this.httpClientAdapter,+ });Dio _buildDio() {+ // In-memory subclasses override requests; every real API call requires auth.+ final source =+ auth ?? (throw StateError('API calls require an access token source'));final dio = attachHttpLog(Dio(BaseOptions(- baseUrl: auth == null ? config.localCliBaseUrl : config.apiBaseUrl,+ baseUrl: config.apiBaseUrl,connectTimeout: const Duration(seconds: 15),receiveTimeout: const Duration(seconds: 30),// Let the API wrapper turn HTTP failures into short, user-facing@@ -39,22 +44,21 @@ class ApiClient {),),);- final source = auth;- if (source != null) {- dio.interceptors.add(- BearerAuthInterceptor(source, dio, autonomousEnv: config.autonomousEnv),- );- }+ dio.interceptors.add(+ BearerAuthInterceptor(source, dio, autonomousEnv: config.autonomousEnv),+ );+ final adapter = httpClientAdapter;+ if (adapter != null) dio.httpClientAdapter = adapter;return dio;}- // -- auth (proxied by the local CLI — no credential on this leg) --+ // -- auth --Future<Map<String, dynamic>?> me() async {final res = await _dio.get('/api/auth/me');return unwrapApiResponse(res) as Map<String, dynamic>?;}- // -- machines (control plane, proxied by the local CLI) --+ // -- machines --Future<List<Machine>> machines() async {final res = await _dio.get('/api/machines');final data = unwrapApiResponse(res) as Map<String, dynamic>;@@ -168,28 +172,21 @@ dynamic unwrapApiResponse(Response res) {);}-/// The sentence a failed local-CLI call earns on an error strip. A raw-/// `DioException` is a paragraph about `RequestOptions.receiveTimeout` — true,-/// and useless to the person reading it: what they need is which leg failed.-/// The daemon not listening, the daemon not answering (it proxies to the-/// backend, so that is nearly always the backend being slow), or the backend-/// answering with a sentence of its own, which the daemon forwards verbatim.+/// A short explanation of a failed request to the Harness backend.String describeApiError(Object error) {if (error is ApiException) return error.message;if (error is DioException) {switch (error.type) {case DioExceptionType.connectionError:- return 'the local Harness service is not answering on its port. '- 'It usually restarts on its own; retry in a moment.';+ return 'could not reach Harness. Check your connection and try again.';case DioExceptionType.connectionTimeout:case DioExceptionType.sendTimeout:case DioExceptionType.receiveTimeout:final limit = error.requestOptions.receiveTimeout?.inSeconds;- return 'the local Harness service did not answer'- '${limit == null ? '' : ' within ${limit}s'} — the Harness '- 'backend is probably slow right now. Retry in a moment.';+ return 'Harness did not answer'+ '${limit == null ? '' : ' within ${limit}s'}. Try again in a moment.';case DioExceptionType.badResponse:- return 'the local Harness service answered '+ return 'Harness answered ''${error.response?.statusCode ?? 'with an error'}.';case DioExceptionType.badCertificate:case DioExceptionType.cancel:diff --git a/mobile/lib/core/config.dart b/mobile/lib/core/config.dartindex 24ba266c2..c925c6569 100644--- a/mobile/lib/core/config.dart+++ b/mobile/lib/core/config.dart@@ -1,15 +1,10 @@-/// Runtime configuration for the desktop app.+/// Runtime configuration for the phone app.class AppConfig {/// Base URL of the central backend (control plane + ws hub).final String apiBaseUrl;final String autonomousEnv;- final String localCliBaseUrl;- const AppConfig({- required this.apiBaseUrl,- this.autonomousEnv = 'prod',- this.localCliBaseUrl = 'http://127.0.0.1:18473',- });+ const AppConfig({required this.apiBaseUrl, this.autonomousEnv = 'prod'});static const AppConfig dev = AppConfig(apiBaseUrl: 'https://harness-api.autonomous.ai',diff --git a/mobile/lib/demo/main_sample.dart b/mobile/lib/demo/main_sample.dartindex a48f10164..63ede6c7e 100644--- a/mobile/lib/demo/main_sample.dart+++ b/mobile/lib/demo/main_sample.dart@@ -37,6 +37,7 @@ class SampleApp extends StatelessWidget {grid.AppTheme.brightness.value = Brightness.dark;return MaterialApp(title: 'Harness sample',+ debugShowCheckedModeBanner: false,theme: grid.buildAppTheme(brightness: Brightness.dark),builder: (context, child) =>grid.BrightnessScope(child: child ?? const SizedBox.shrink()),diff --git a/mobile/lib/demo/sample_notifier.dart b/mobile/lib/demo/sample_notifier.dartindex 752b3ff84..8b58a2a2a 100644--- a/mobile/lib/demo/sample_notifier.dart+++ b/mobile/lib/demo/sample_notifier.dart@@ -20,7 +20,6 @@ import 'package:harness_mobile/ws/ws_conn.dart';const sampleConfig = AppConfig(apiBaseUrl: 'https://sample.invalid',autonomousEnv: 'sample',- localCliBaseUrl: 'http://sample.invalid',);/// A key-value store that forgets everything when the sample is left.diff --git a/mobile/lib/demo/sample_screen.dart b/mobile/lib/demo/sample_screen.dartindex e226d92bc..427030a77 100644--- a/mobile/lib/demo/sample_screen.dart+++ b/mobile/lib/demo/sample_screen.dart@@ -360,7 +360,7 @@ class ClaudeLook extends SampleLook {width - 6,// Claude Code's own kind of nudge, and true of any project: not one project's file name// on every harness.- placeholder: 'Try "run the tests and fix what fails"',+ placeholder: 'Try "test"',).indexed)[Span(i == 0 ? '> ' : ' '), ...row],], width);diff --git a/mobile/lib/logging/cli_log.dart b/mobile/lib/logging/cli_log.dartdeleted file mode 100644index ab2edfa2b..000000000--- a/mobile/lib/logging/cli_log.dart+++ /dev/null@@ -1,94 +0,0 @@-import 'log_file.dart';--/// Durable, append-only transcript of every CLI call this app makes, written per-/// day to `~/.harness/logs/cli-YYYYMMDD.log`.-///-/// Ported from Grid. "The CLI did something unexpected" is the single most-/// common shape of a fault here, because the app itself holds almost no logic.-///-/// Concurrent calls interleave in the file, so each line is tagged with a-/// per-call id (`#3`) to keep one command's output readable.-///-/// **A command line is logged, its environment is not.** A secret handed to a-/// child travels in its environment precisely so it stays out of argv; writing-/// the environment here would undo that and put a key on disk.-abstract interface class CliLog {- /// Opens a section for one invocation. [command] is the display line- /// (`harness link create`). Returns a handle to append output and close it.- CliLogEntry begin(String command);-}--/// Handle to one in-flight invocation's transcript section.-abstract interface class CliLogEntry {- /// Append one line of the command's output; [isError] tags stderr.- void output(String line, {bool isError = false});-- /// Close the section with how the command ended. Idempotent — a second call is- /// ignored so a cancelled stream and its exit code don't double-close.- void end({int? exitCode, Duration? duration, String? error});-}--/// [CliLog] backed by a per-day file under `~/.harness/logs`.-class FileCliLog implements CliLog {- FileCliLog(this._file);-- final DailyLogFile _file;- int _seq = 0;-- @override- CliLogEntry begin(String command) {- final id = ++_seq;- final start = DateTime.now();- _file.append('[${logClock(start)}] #$id \$ $command');- return _FileCliLogEntry(_file, id, start);- }-}--class _FileCliLogEntry implements CliLogEntry {- _FileCliLogEntry(this._file, this._id, this._start);-- final DailyLogFile _file;- final int _id;- final DateTime _start;- bool _ended = false;-- @override- void output(String line, {bool isError = false}) {- if (_ended) return;- // `!` gutter marks stderr so failures stand out; `|` for normal output.- _file.append(- '[${logClock(DateTime.now())}] #$_id ${isError ? '!' : '|'} $line',- );- }-- @override- void end({int? exitCode, Duration? duration, String? error}) {- if (_ended) return;- _ended = true;- final took = logDuration(duration ?? DateTime.now().difference(_start));- final code = exitCode != null ? ' exit=$exitCode' : '';- final err = error != null ? ' error: $error' : '';- _file.append('[${logClock(DateTime.now())}] #$_id ← done$code ($took)$err');- }-}--/// No-op [CliLog] — the default, so tests never touch `~/.harness/logs`.-class NoopCliLog implements CliLog {- const NoopCliLog();-- @override- CliLogEntry begin(String command) => const _NoopEntry();-}--class _NoopEntry implements CliLogEntry {- const _NoopEntry();-- @override- void output(String line, {bool isError = false}) {}-- @override- void end({int? exitCode, Duration? duration, String? error}) {}-}--/// The CLI transcript sink. Muted until [installFileLogs] swaps in the file sink.-CliLog cliLog = const NoopCliLog();diff --git a/mobile/lib/logging/install.dart b/mobile/lib/logging/install.dartindex 03df5fa28..3d534cfe7 100644--- a/mobile/lib/logging/install.dart+++ b/mobile/lib/logging/install.dart@@ -1,19 +1,17 @@import 'app_log.dart';-import 'cli_log.dart';import 'debug_surface.dart';import 'log_file.dart';import 'log_stream.dart';import 'log_stream_sinks.dart';-/// Base names of the two per-day files under `~/.harness/logs`.+/// Base name of the per-day file under `~/.harness/logs`.const String kAppLogBase = 'app';-const String kCliLogBase = 'cli';-/// Point [appLog] and [cliLog] at real files under `~/.harness/logs`, and — in+/// Point [appLog] at real files under `~/.harness/logs`, and — in/// a build that has the Debug screen — at the in-memory [logStream] as well.////// Called once from `main()`. Nothing else calls it, which is what keeps the-/// suite honest: both sinks default to their no-op, so `flutter test` cannot+/// suite honest: the app log defaults to a no-op, so `flutter test` cannot/// write into a real Harness home no matter which code path it exercises — the/// same rule analytics follows.///@@ -22,14 +20,11 @@ const String kCliLogBase = 'cli';void installFileLogs() {final directory = DailyLogFile.defaultDirectory;final file = FileAppLog(DailyLogFile(directory, kAppLogBase));- final cli = FileCliLog(DailyLogFile(directory, kCliLogBase));if (!kDebugSurfaceEnabled) {appLog = file;- cliLog = cli;return;}- // The file first in both fan-outs: if the mirror ever throws, the durable+ // The file first in the fan-out: if the mirror ever throws, the durable// copy is already written.appLog = FanoutAppLog([file, StreamAppLog(logStream)]);- cliLog = FanoutCliLog([cli, StreamCliLog(logStream)]);}diff --git a/mobile/lib/logging/log_stream.dart b/mobile/lib/logging/log_stream.dartindex 8b866d91d..3b824ea36 100644--- a/mobile/lib/logging/log_stream.dart+++ b/mobile/lib/logging/log_stream.dart@@ -95,9 +95,9 @@ class LogCommand {/// The app's own log, as the running app still holds it: a bounded ring of the/// most recent entries, newest first.///-/// Fed by [StreamAppLog]/[StreamCliLog], read by Settings ▸ Debug. A singleton+/// Fed by `StreamAppLog`, read by Settings ▸ Debug. A singleton/// like `appLog` and `analytics`, and for the same reason: the things that-/// write to it — the socket, the CLI runners, the HTTP clients — hold no `Ref`+/// write to it — the socket and the HTTP clients — hold no `Ref`/// and no notifier between them.class LogStream extends ChangeNotifier {LogStream({this.maxEntries = 500, this.maxOutputLines = 300});@@ -113,6 +113,13 @@ class LogStream extends ChangeNotifier {final List<LogEntry> _entries = [];int _seq = 0;bool _notifyScheduled = false;+ bool _disposed = false;++ @override+ void dispose() {+ _disposed = true;+ super.dispose();+ }/// Newest first — the order the Debug list reads in, so the newest line is/// the one on screen without scrolling.@@ -207,7 +214,7 @@ class LogStream extends ChangeNotifier {_notifyScheduled = true;scheduleMicrotask(() {_notifyScheduled = false;- notifyListeners();+ if (!_disposed) notifyListeners();});}}diff --git a/mobile/lib/logging/log_stream_sinks.dart b/mobile/lib/logging/log_stream_sinks.dartindex ae025e900..dcb9f996e 100644--- a/mobile/lib/logging/log_stream_sinks.dart+++ b/mobile/lib/logging/log_stream_sinks.dart@@ -2,13 +2,12 @@/// the in-memory [LogStream] the Debug screen reads.////// A mirror rather than a second stream. Every call site keeps writing to the-/// one `appLog`/`cliLog` it already writes to, so a line cannot reach the+/// one `appLog` it already writes to, so a line cannot reach the/// screen without reaching the file — which is what makes "read it in Settings/// ▸ Debug" and "send us the log" the same evidence.library;import 'app_log.dart';-import 'cli_log.dart';import 'log_stream.dart';/// Writes one event to each of [sinks], in order.@@ -64,76 +63,3 @@ class StreamAppLog implements AppLog {);}}--/// Opens one section on each of [sinks] and keeps them in step.-class FanoutCliLog implements CliLog {- const FanoutCliLog(this.sinks);-- final List<CliLog> sinks;-- @override- CliLogEntry begin(String command) =>- _FanoutEntry([for (final sink in sinks) sink.begin(command)]);-}--class _FanoutEntry implements CliLogEntry {- const _FanoutEntry(this._entries);-- final List<CliLogEntry> _entries;-- @override- void output(String line, {bool isError = false}) {- for (final entry in _entries) {- entry.output(line, isError: isError);- }- }-- @override- void end({int? exitCode, Duration? duration, String? error}) {- for (final entry in _entries) {- entry.end(exitCode: exitCode, duration: duration, error: error);- }- }-}--/// [CliLog] that turns each invocation into one [LogEntry] carrying its own-/// transcript — one row in the Debug list that grows, rather than a row per-/// line, which is what the file wants and a list does not.-class StreamCliLog implements CliLog {- const StreamCliLog(this._stream);-- final LogStream _stream;-- @override- CliLogEntry begin(String command) {- final invocation = LogCommand();- final id = _stream.add(- AppLogLevel.info,- 'cli',- command,- command: invocation,- );- return _StreamEntry(_stream, id, DateTime.now());- }-}--class _StreamEntry implements CliLogEntry {- _StreamEntry(this._stream, this._id, this._start);-- final LogStream _stream;- final int _id;- final DateTime _start;-- @override- void output(String line, {bool isError = false}) =>- _stream.appendOutput(_id, line, isError: isError);-- @override- void end({int? exitCode, Duration? duration, String? error}) =>- _stream.finish(- _id,- exitCode: exitCode,- duration: duration ?? DateTime.now().difference(_start),- error: error,- );-}diff --git a/mobile/lib/logging/redact.dart b/mobile/lib/logging/redact.dartindex aec903b22..e6d428801 100644--- a/mobile/lib/logging/redact.dart+++ b/mobile/lib/logging/redact.dart@@ -76,7 +76,7 @@ String redactValue(Object? value) {////// [redactValue] above works on a decoded frame, where a secret is identified/// by its KEY. A CLI's stdout has no keys: `harness auth status --json` prints-/// a session, and it goes into the transcript `cliLog` keeps. This is the same denylist idea applied to text — ported from+/// a session, and it can appear in an error log. This is the same denylist idea applied to text — ported from/// Grid's `redactLogSecrets` (`features/feedback/logic/log_bundle.dart`), so a/// log line means the same thing in both products. Keep the two in step.///diff --git a/mobile/lib/phone/new_agent_chooser.dart b/mobile/lib/phone/new_agent_chooser.dartindex 253ebd70a..92703afb9 100644--- a/mobile/lib/phone/new_agent_chooser.dart+++ b/mobile/lib/phone/new_agent_chooser.dart@@ -42,8 +42,8 @@ class ChooserItem<T> {}}-/// A chooser for one of New's rows — a full-height sheet that slides UP, since sideways means Find-/// and New: a title and Cancel, a search field at the top, the list growing down with `✓` on the+/// A chooser for one of New's rows — a sheet sized to its rows that slides UP, since sideways means Find+/// and New: a title, a search field for long lists, the list growing down with `✓` on the/// current value, and the `+` actions ending it. A tap picks and closes.////// [fold] keeps a long list short: past that many items a `more` row stands in for the rest, until@@ -55,30 +55,25 @@ Future<T?> showNewAgentChooser<T>(List<ChooserItem<T>> actions = const [],String? title,int? fold,-}) => Navigator.of(context, rootNavigator: true).push<T>(- PageRouteBuilder<T>(- opaque: false,- barrierColor: Colors.black54,- barrierDismissible: true,- transitionDuration: const Duration(milliseconds: 200),- reverseTransitionDuration: const Duration(milliseconds: 160),- pageBuilder: (_, _, _) => _Chooser<T>(+}) => showModalBottomSheet<T>(+ context: context,+ useRootNavigator: true,+ useSafeArea: true,+ isScrollControlled: true,+ showDragHandle: true,+ backgroundColor: Tty.of(context).ground,+ constraints: BoxConstraints(+ maxHeight: MediaQuery.sizeOf(context).height * 0.85,+ ),+ builder: (context) => Padding(+ padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),+ child: _Chooser<T>(title: title ?? hint.replaceFirst(RegExp(r'^Search '), ''),hint: hint,items: items,actions: actions,fold: fold,),- transitionsBuilder: (_, animation, _, child) => SlideTransition(- position: Tween(begin: const Offset(0, 1), end: Offset.zero).animate(- CurvedAnimation(- parent: animation,- curve: Curves.easeOutCubic,- reverseCurve: Curves.easeInCubic,- ),- ),- child: child,- ),),);@@ -136,121 +131,96 @@ class _ChooserState<T> extends State<_Chooser<T>> {final terms = query.isEmpty? const <String>[]: query.split(RegExp(r'\s+'));- // Everything but a strip at the top, where the form it belongs to still shows.- return Align(- alignment: Alignment.bottomCenter,- child: Container(- // Three quarters of the screen: the dimmed form above it is the way out.- height: media.size.height * 0.75,- decoration: BoxDecoration(- color: tty.ground,- borderRadius: const BorderRadius.vertical(top: Radius.circular(10)),- border: Border(- top: BorderSide(color: tty.dim.withValues(alpha: 0.6)),+ return Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(Tty.origin, 0, Tty.origin, 0),+ child: Row(+ children: [+ Expanded(+ child: TtyText(+ widget.title,+ size: TtySize.title,+ weight: FontWeight.w600,+ ),+ ),+ // No Cancel: a tap above the sheet, or a pull down, puts it away.+ const SizedBox(height: 44),+ ],),),- child: Material(- type: MaterialType.transparency,- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,+ // Search where there is something to search: a long list that is not folded.+ if (widget.items.length > 8 && widget.fold == null)+ Padding(+ padding: const EdgeInsets.fromLTRB(Tty.origin, 4, Tty.origin, 4),+ child: TtyField(+ controller: _controller,+ focus: _focus,+ hint: widget.hint,+ action: TextInputAction.search,+ onChanged: (value) => setState(() => _query = value),+ onSubmitted: () {+ final first = matches.where((item) => item.enabled).firstOrNull;+ if (first != null) _choose(first);+ },+ ),+ ),+ Flexible(+ child: ListView(+ shrinkWrap: true,+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,+ padding: EdgeInsets.only(bottom: media.padding.bottom + 16),children: [- Padding(- padding: const EdgeInsets.fromLTRB(16, 8, 4, 0),- child: Row(- children: [- Expanded(- child: TtyText(- widget.title,- size: TtySize.title,- weight: FontWeight.w600,- ),- ),- // No Cancel: a tap above the sheet, or a pull down, puts it away.- const SizedBox(height: 44),- ],+ for (final item in shown)+ FindRow(+ title: item.title,+ detail: item.subtitle,+ terms: terms,+ state: item.selected+ ? '✓'+ : item.warn+ ? 'risky'+ : null,+ stateColor: item.selected ? tty.green : tty.red,+ enabled: item.enabled,+ onTap: () => _choose(item),),- ),- // Search where there is something to search: a long list that is not folded.- if (widget.items.length > 8 && widget.fold == null)+ if (folded)+ FindRow(+ title: 'more',+ detail: '${matches.length - shown.length} others, A to Z',+ onTap: () => setState(() => _unfolded = true),+ ),+ if (matches.isEmpty)Padding(padding: const EdgeInsets.fromLTRB(Tty.origin,- 4,+ 16,Tty.origin,- 4,+ 8,),- child: TtyField(- controller: _controller,- focus: _focus,- hint: widget.hint,- action: TextInputAction.search,- onChanged: (value) => setState(() => _query = value),- onSubmitted: () {- final first = matches- .where((item) => item.enabled)- .firstOrNull;- if (first != null) _choose(first);- },+ child: TtyText(+ 'No match.',+ color: tty.faint,+ size: TtySize.row,),),- Expanded(- child: ListView(- keyboardDismissBehavior:- ScrollViewKeyboardDismissBehavior.onDrag,- padding: EdgeInsets.only(bottom: media.padding.bottom + 16),- children: [- for (final item in shown)- FindRow(- title: item.title,- detail: item.subtitle,- terms: terms,- state: item.selected- ? '✓'- : item.warn- ? 'risky'- : null,- stateColor: item.selected ? tty.green : tty.red,- enabled: item.enabled,- onTap: () => _choose(item),- ),- if (folded)- FindRow(- title: 'more',- detail:- '${matches.length - shown.length} others, A to Z',- onTap: () => setState(() => _unfolded = true),- ),- if (matches.isEmpty)- Padding(- padding: const EdgeInsets.fromLTRB(- Tty.origin,- 16,- Tty.origin,- 8,- ),- child: TtyText(- 'No match.',- color: tty.faint,- size: TtySize.row,- ),- ),- if (widget.actions.isNotEmpty) const SizedBox(height: 8),- // An action the computer cannot do is left out, not drawn dead: a greyed row- // with no reason reads as broken.- for (final action in widget.actions)- if (action.enabled)- FindAddRow(- label: action.title,- detail: action.subtitle,- onTap: () => _choose(action),- ),- ],- ),- ),+ if (widget.actions.isNotEmpty) const SizedBox(height: 8),+ // An action the computer cannot do is left out, not drawn dead: a greyed row+ // with no reason reads as broken.+ for (final action in widget.actions)+ if (action.enabled)+ FindAddRow(+ label: action.title,+ detail: action.subtitle,+ onTap: () => _choose(action),+ ),],),),- ),+ ],);}}diff --git a/mobile/lib/phone/new_agent_page.dart b/mobile/lib/phone/new_agent_page.dartindex f94a60da6..f44c4e3b4 100644--- a/mobile/lib/phone/new_agent_page.dart+++ b/mobile/lib/phone/new_agent_page.dart@@ -13,6 +13,7 @@ import 'package:harness_mobile/core/git_project.dart';import 'package:harness_mobile/core/project_folder.dart';import 'package:harness_mobile/widgets/remote_folder_picker.dart';+import '../demo/sample_mode.dart' show SampleMode;import 'agent_index.dart';import 'branch_picker_sheet.dart';import 'phone_navigation.dart';@@ -697,8 +698,8 @@ class _NewAgentPageState extends State<NewAgentPage> {// Typing the task, the keyboard leaves room for one line of the choices, not four cut ones.final typing = MediaQuery.viewInsetsOf(context).bottom > 0;final summary = [- if (_engine != null) _engineName(_engine!),if (_folder != null || _project != null) _projectValue,+ if (_engine != null) _engineName(_engine!),if (_repository != null) _worktree ? 'worktree' : _branchTitle,if (_permissionModes.isNotEmpty)(_permissionModeChoice?.label ?? 'Auto-approve'),@@ -736,6 +737,15 @@ class _NewAgentPageState extends State<NewAgentPage> {weight: FontWeight.w600,),),+ if (SampleMode.ofNotifier(widget.notifier) != null)+ Padding(+ padding: const EdgeInsets.only(right: 8),+ child: TtyText(+ 'Sample',+ color: tty.faint,+ size: TtySize.meta,+ ),+ ),// No Cancel: a swipe right goes back, the way a swipe left came in.const SizedBox(height: 44),],diff --git a/mobile/lib/phone/phone_search_field.dart b/mobile/lib/phone/phone_search_field.dartindex 39d394db9..caebc4e50 100644--- a/mobile/lib/phone/phone_search_field.dart+++ b/mobile/lib/phone/phone_search_field.dart@@ -153,7 +153,7 @@ class _QueryInput extends StatelessWidget {hintText: hintText,// A size down from the query's own 16pt. Set when the hint spelled out// four modes on a 390pt screen, and kept.- hintStyle: TextStyle(color: AppPalette.textFaint, fontSize: 13),+ hintStyle: TextStyle(color: AppPalette.textSecondary, fontSize: 13),),);}diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dartindex 7bfb8d2cf..cb32d0ff1 100644--- a/mobile/lib/phone/settings_page.dart+++ b/mobile/lib/phone/settings_page.dart@@ -281,14 +281,14 @@ class _Avatar extends StatelessWidget {width: 34,height: 34,decoration: BoxDecoration(- color: AppPalette.avatarFill,+ color: Tty.of(context).selected,shape: BoxShape.circle,),alignment: Alignment.center,child: Text(initial,- style: const TextStyle(- color: Colors.white,+ style: TextStyle(+ color: Tty.of(context).text,// Scaled with the disc: 15pt inside 34 left almost no ring around the letter, which// reads as a cramped badge rather than an avatar.fontSize: 14,diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dartindex cc22f84d1..e6d32e9df 100644--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@ -767,29 +767,24 @@ class _TerminalPageState extends State<TerminalPage>}/// In the sample, the one thing to try next — `refactor-db needs you →` — following what has- /// been done: go to the harness that is asking, answer it, start one of your own. No counter:- /// the dot beside it glides the way the swipe goes. Null outside the sample, and once the sample- /// is done.- ({String text, int glide})? _sampleGuide() {+ /// been done: go to the harness that is asking, answer it, start one of your own. Null outside the sample and once the sample is done.+ String? _sampleGuide() {final sample = SampleMode.maybeOf(context);if (sample == null || sample.endCardSeen) return null;- final (step, text, glide) = switch (null) {+ final (step, text) = switch (null) {_ when widget.agentId.startsWith('sample-new-') => (4,'✓ yours is running',- 0,),_ when _questionWatcher?.view != null => (2,'say “yes”, or tap an answer',- 0,),_ when _askingElsewhere() != null => (1,'${_askingElsewhere()!.replaceFirst(' asking', '')} needs you →',- 1,),- _ => (3, '← start one of your own', -1),+ _ => (3, '← start one of your own'),};if (step == 4) _scheduleEndCard(sample);// A step done: a tick you can feel, once.@@ -797,7 +792,7 @@ class _TerminalPageState extends State<TerminalPage>HapticFeedback.mediumImpact();}_guideStep = step;- return (text: text, glide: glide);+ return text;}int? _guideStep;@@ -925,7 +920,7 @@ class _TerminalPageState extends State<TerminalPage>// one ("FAIL src/auth/…"). It is back the moment the reader is at the end again.if (_scrollback.value != null) return null;if (_sampleGuide() case final guide?) {- return _StatusLine(text: guide.text, glide: guide.glide, dot: true);+ return _StatusLine(text: guide, dot: true);}return null;}@@ -1833,126 +1828,119 @@ class _TerminalPageState extends State<TerminalPage>// listening for its notifications as they// bubble past is what survives that, and costs// the panel no knowledge of the page's chrome.- child:- NotificationListener<- ScrollNotification- >(- // A scroll on a terminal held elsewhere takes it,- // as a tap does: no button to find first.- onNotification: (notification) {- if (blocked &&- notification- is ScrollStartNotification &&- notification.dragDetails !=- null) {- unawaited(_takeControl());- }- return _chrome.onNotification(- notification,- );- },- child: agentGone- ? _AgentGone(- name: _cachedAgentName,- onPickAnother:- _pickAnotherAgent,- )- : pane == null ||- session == null- ? _Attaching(- key: _skeletonKey,- )- : TerminalPanel(- key: ValueKey(pane.id),- notifier: widget.notifier,- session: session,- // Only the page on screen takes the keyboard — see- // [TerminalPage.isActive]. `visible` is the same answer for the- // panel's other half: a page parked beside this one releases- // focus, stops rendering and stops resizing its remote shell.- //- // Whether it also HOLDS one that is already- // up is a separate question, and the pager asks- // it on every swipe — see [_shouldFocus].- focused: _shouldFocus,- // Asks again when `focused` did- // not move — coming back from- // another app. See- // [didChangeAppLifecycleState].- focusRequest:- _focusRequest,- visible: widget.isActive,- // Hold the remote resize while the keyboard- // slides. Separate from `visible` because this- // must NOT release focus — the animation being- // waited on is the one that focus started.- //- // The keyboard is the only thing left that- // moves this pane's height: the header slides- // OVER the terminal rather than out of its- // column — see [_SlideAway].- //- // ⚠️ Held for as long as search is open, too:- // its keyboard is typing a query over a faded- // terminal, and resizing the agent's shell for- // it redrew the whole TUI on the way in and- // again on the way out.- settling:- _keyboardSettling ||- _heldForSearch,- // ⚠️ The tap is taken in the panel, not by a- // `Listener` over it. xterm's own `_onTapDown`- // calls `requestKeyboard()`, so anything that- // merely ALSO reacted to the tap would raise- // the keyboard before the words said were typed- // into the prompt — and a re-armed claim on top- // of it was measured asking Android twice per- // tap, which answers a show mid-animation by- // cancelling and restarting it. Null while the- // keyboard is up or coming, so the tap is- // xterm's and the keyboard stays.- //- // ⚠️ A tap on a pane that cannot take input- // takes the TERMINAL first, not the- // keyboard: raising one over a read-only- // pane offers a prompt that silently- // swallows every letter.- //- // ⚠️ **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.- ),- ),+ 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,+ // 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.+ ),+ ),),),),@@ -2070,6 +2058,7 @@ class _TerminalPageState extends State<TerminalPage>mainAxisSize: MainAxisSize.min,children: [TerminalTitle(+ sample: SampleMode.maybeOf(context) != null,name:agent?.displayName ?? _cachedAgentName ?? '',place: _placeOf(agent, machine),@@ -3418,138 +3407,47 @@ class _AnchoredTerminalState extends State<_AnchoredTerminal> {);}-/// The line above the mic: a few words on what is going on, centred, over a band that fades the-/// output out above it. The sample's guide wears a 6pt green [dot] that glides 24pt the way the-/// swipe goes ([glide] 1 right, -1 left) every 2.4s; 0 holds it still.-class _StatusLine extends StatefulWidget {- const _StatusLine({- required this.text,- this.color,- this.glide = 0,- this.dot = false,- });+/// The line above the mic, on the terminal gutter with an opaque ground.+/// Its fixed yellow dot uses the same asking colour as Find.+class _StatusLine extends StatelessWidget {+ const _StatusLine({required this.text, this.color, this.dot = false});final String text;-- /// The words' colour; faint when null.final Color? color;- final int glide;final bool dot;-- /// How far the band reaches below its words' foot.static const double below = 6;- @override- State<_StatusLine> createState() => _StatusLineState();-}--class _StatusLineState extends State<_StatusLine>- with SingleTickerProviderStateMixin {- late final _clock = AnimationController(- vsync: this,- duration: const Duration(milliseconds: 2400),- );-- @override- void didChangeDependencies() {- super.didChangeDependencies();- _sync();- }-- @override- void didUpdateWidget(_StatusLine old) {- super.didUpdateWidget(old);- if (old.glide != widget.glide) _sync();- }-- void _sync() {- if (widget.glide == 0 ||- MediaQuery.maybeDisableAnimationsOf(context) == true) {- _clock- ..stop()- ..value = 0;- } else if (!_clock.isAnimating) {- unawaited(_clock.repeat());- }- }-- @override- void dispose() {- _clock.dispose();- super.dispose();- }-@overrideWidget build(BuildContext context) {final tty = Tty.of(context);- final dot = Container(- width: 6,- height: 6,- decoration: BoxDecoration(color: tty.green, shape: BoxShape.circle),- );- // A band the width of the screen, the output fading out above it as it does under the title —- // a pill only as wide as its words cut the rows behind it in half. A live region: what it says- // (a take not sent, a question to answer on screen) is read out as it changes.return Semantics(liveRegion: true,- child: DecoratedBox(- decoration: BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- colors: [tty.ground.withValues(alpha: 0), tty.ground, tty.ground],- stops: const [0, 0.4, 1],- ),- ),+ child: ColoredBox(+ color: tty.ground,child: Padding(- padding: const EdgeInsets.fromLTRB(- Tty.origin,- 14,- Tty.origin,- _StatusLine.below,- ),+ padding: const EdgeInsets.fromLTRB(Tty.origin, 8, Tty.origin, below),child: Row(- mainAxisAlignment: MainAxisAlignment.center,children: [- if (widget.dot) ...[- SizedBox(- width: 30,+ if (dot) ...[+ Container(+ key: const ValueKey('sample-guide-dot'),+ width: 6,height: 6,- child: AnimatedBuilder(- animation: _clock,- builder: (context, child) {- // A glide over the first 60% of each beat, easing in and out, then a rest.- final t = Curves.easeInOut.transform(- (_clock.value / 0.6).clamp(0.0, 1.0),- );- final from = widget.glide < 0 ? 24.0 : 0.0;- final x = widget.glide == 0- ? 12.0- : from + widget.glide * 24 * t;- final fade = widget.glide == 0 ? 1.0 : 1 - (t * t);- return Stack(- children: [- Positioned(- left: x,- top: 0,- child: Opacity(opacity: fade, child: child),- ),- ],- );- },- child: dot,+ decoration: BoxDecoration(+ color: tty.yellow,+ shape: BoxShape.circle,),),const SizedBox(width: 8),],Flexible(child: Text(- widget.text,+ text,maxLines: 1,overflow: TextOverflow.ellipsis,style: tty.style(size: TtySize.meta,- color: widget.color ?? tty.faint,+ color: color ?? tty.text,),),),diff --git a/mobile/lib/phone/terminal_search.dart b/mobile/lib/phone/terminal_search.dartindex 32a6f68d4..8acb5ee68 100644--- a/mobile/lib/phone/terminal_search.dart+++ b/mobile/lib/phone/terminal_search.dart@@ -11,6 +11,7 @@ import 'package:harness_mobile/shared/widgets/app_dialog.dart'show kDialogVeilBlur, kSheetVeilOpacity;import 'package:harness_mobile/state/app_state.dart';+import '../demo/sample_mode.dart' show SampleMode;import 'agents_page.dart' show openNewAgent;import 'find_models.dart';import 'tty.dart';@@ -490,6 +491,20 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>],),),+ if (SampleMode.ofNotifier(widget.notifier) != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ Tty.origin,+ 4,+ Tty.origin,+ 0,+ ),+ child: TtyText(+ 'Sample harnesses',+ color: Tty.of(context).faint,+ size: TtySize.meta,+ ),+ ),const SizedBox(height: 4),Expanded(child: switch ((_search.isModelMode, widget.showing)) {diff --git a/mobile/lib/phone/terminal_title.dart b/mobile/lib/phone/terminal_title.dartindex 0492d48df..ac86d0c61 100644--- a/mobile/lib/phone/terminal_title.dart+++ b/mobile/lib/phone/terminal_title.dart@@ -30,9 +30,11 @@ class TerminalTitle extends StatelessWidget {this.branch,this.asking,this.onHold,+ this.sample = false,});final String name;+ final bool sample;/// `machine:folder` — where the harness works.final String? place;@@ -146,6 +148,15 @@ class TerminalTitle extends StatelessWidget {],),),+ if (sample)+ Padding(+ padding: const EdgeInsets.only(left: 12),+ child: TtyText(+ 'Sample',+ color: tty.faint,+ size: TtySize.meta,+ ),+ ),if (asking case final asking?)Semantics(button: true,diff --git a/mobile/lib/phone/tty.dart b/mobile/lib/phone/tty.dartindex 9b160dcbe..c8d3fd72b 100644--- a/mobile/lib/phone/tty.dart+++ b/mobile/lib/phone/tty.dart@@ -45,8 +45,16 @@ class Tty {/// Secondary TEXT in the chrome: labels, details, hints. brightBlack on the ground is 3.1:1, too/// faint to read at a glance on a phone; this is the agent's own faint text, about 4.9:1.- Color get faint =>- Color.alphaBlend(theme.foreground.withValues(alpha: 0.52), theme.background);+ Color get faint => Color.alphaBlend(+ theme.foreground.withValues(alpha: 0.52),+ theme.background,+ );++ /// Hints stay readable on raised form fields, as well as on the terminal ground.+ Color get placeholder => Color.alphaBlend(+ theme.foreground.withValues(alpha: 0.60),+ theme.background,+ );Color get green => theme.green;Color get yellow => theme.yellow;Color get red => theme.red;@@ -110,7 +118,10 @@ class Tty {backgroundColor: background,fontWeight: weight,// Tabular by construction, but ligatures would glue `->` and `!=` in paths and branch names.- fontFeatures: const [FontFeature.disable('liga'), FontFeature.disable('calt')],+ fontFeatures: const [+ FontFeature.disable('liga'),+ FontFeature.disable('calt'),+ ],);}diff --git a/mobile/lib/phone/tty_controls.dart b/mobile/lib/phone/tty_controls.dartindex 6d0951f80..844cb9bc3 100644--- a/mobile/lib/phone/tty_controls.dart+++ b/mobile/lib/phone/tty_controls.dart@@ -432,7 +432,7 @@ class _TtyFieldState extends State<TtyField> {hintText: widget.hint,hintMaxLines: multi ? 3 : 1,hintStyle: tty.style(- color: tty.faint,+ color: tty.placeholder,size: multi ? TtySize.row : TtySize.title,),),diff --git a/mobile/lib/phone/welcome/connect_computer.dart b/mobile/lib/phone/welcome/connect_computer.dartindex bbefc5b5d..04e8a3fa9 100644--- a/mobile/lib/phone/welcome/connect_computer.dart+++ b/mobile/lib/phone/welcome/connect_computer.dart@@ -185,20 +185,9 @@ class _ConnectComputerPageState extends State<ConnectComputerPage> {],): null,- trailing: [- if (widget.onTrySample case final trySample?)- Align(- alignment: Alignment.centerLeft,- child: Transform.translate(- offset: const Offset(-12, 0),- child: TtyTextButton(- label: 'Try the sample while you wait',- color: tty.faint,- onPressed: () => unawaited(trySample(context)),- ),- ),- ),- ],+ onTrySample: widget.onTrySample == null+ ? null+ : () => unawaited(widget.onTrySample!(context)),),),);diff --git a/mobile/lib/phone/welcome/phone_welcome.dart b/mobile/lib/phone/welcome/phone_welcome.dartindex 26cf58654..48de26e64 100644--- a/mobile/lib/phone/welcome/phone_welcome.dart+++ b/mobile/lib/phone/welcome/phone_welcome.dart@@ -102,9 +102,7 @@ class _PhoneWelcomeState extends State<PhoneWelcome> {super.dispose();}- /// The offline sample — no longer offered on this screen (a video shows the app instead), but- /// kept behind a long press on the wordmark for the simulator's screenshots. Left from its end- /// card to set up a computer, it lands on the set-up page.+ /// The offline sample, offered on welcome and setup. Its end card can lead to setup.Future<void> _trySample() async {final result = await widget.onTrySample!(context);if (!mounted || result != 'set-up') return;@@ -236,6 +234,9 @@ class _PhoneWelcomeState extends State<PhoneWelcome> {_Step.setUp => SetUpComputerPage(onScan: () => _go(_Step.scan),onBack: () => _go(_Step.hello),+ onTrySample: widget.onTrySample == null+ ? null+ : () => unawaited(_trySample()),loadDownloads: widget.loadDownloads,),_Step.scan => ScanToConnectPage(@@ -282,11 +283,16 @@ class _PhoneWelcomeState extends State<PhoneWelcome> {onFilled: _signIn,),error: _error,- button: TtyPrimaryButton(- label: 'Sign in',- busy: _busy || signingIn,- busyLabel: 'Signing in…',- onPressed: _signIn,+ button: ValueListenableBuilder<TextEditingValue>(+ valueListenable: _code,+ builder: (_, value, _) => TtyPrimaryButton(+ label: 'Sign in',+ busy: _busy || signingIn,+ busyLabel: 'Signing in…',+ onPressed: value.text.trim().length == _codeLength+ ? _signIn+ : null,+ ),),footer: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,@@ -379,6 +385,10 @@ class _Hello extends StatelessWidget {_Answer(label: 'Yes — scan to connect', onTap: onScan),const SizedBox(height: 10),_Answer(label: 'Not yet — set it up', onTap: onSetUp),+ if (onSample != null) ...[+ const SizedBox(height: 8),+ TtyTextButton(label: 'Try the sample', onPressed: onSample),+ ],],),),diff --git a/mobile/lib/phone/welcome/pick_up_page.dart b/mobile/lib/phone/welcome/pick_up_page.dartindex 52afb291f..98cf52e8d 100644--- a/mobile/lib/phone/welcome/pick_up_page.dart+++ b/mobile/lib/phone/welcome/pick_up_page.dart@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/state/app_state.dart';+import '../../demo/sample_mode.dart' show SampleMode;import '../agent_index.dart';import '../agents_page.dart' show openNewAgent;import '../phone_status.dart';@@ -99,7 +100,9 @@ class _PickUpPageState extends State<PickUpPage> {),child: Text(// Broken by hand: at 28pt it wraps with "off" alone on the second line.- 'Pick up where\nyou left off',+ SampleMode.maybeOf(context) != null+ ? 'Try a sample\nharness'+ : 'Pick up where\nyou left off',key: const ValueKey('pick-up-title'),style: tty.style(size: TtySize.display, weight: FontWeight.w600)diff --git a/mobile/lib/phone/welcome/set_up_computer.dart b/mobile/lib/phone/welcome/set_up_computer.dartindex 74c3ac7ff..c304664df 100644--- a/mobile/lib/phone/welcome/set_up_computer.dart+++ b/mobile/lib/phone/welcome/set_up_computer.dart@@ -116,6 +116,7 @@ class SetUpComputerPage extends StatefulWidget {super.key,required this.onScan,this.onBack,+ this.onTrySample,this.status,this.trailing = const [],this.loadDownloads,@@ -128,6 +129,9 @@ class SetUpComputerPage extends StatefulWidget {/// Null draws no back button: the page is a home screen, not a pushed one.final VoidCallback? onBack;+ /// Opens the offline sample before the user sets up a computer.+ final VoidCallback? onTrySample;+/// A line under the title about what is going on — signed in, the watch for the computer.final Widget? status;@@ -207,6 +211,25 @@ class _SetUpComputerPageState extends State<SetUpComputerPage> {.style(size: TtySize.display, weight: FontWeight.w600).copyWith(height: 34 / 28, letterSpacing: -0.6),),+ if (widget.onTrySample case final onTrySample?) ...[+ const SizedBox(height: 16),+ TtyTap(+ onTap: onTrySample,+ semanticsLabel:+ 'Try the sample. No account or computer needed.',+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 10),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ TtyText('Try the sample ›', size: TtySize.title),+ const SizedBox(height: 4),+ Text('No account or computer needed.', style: faint),+ ],+ ),+ ),+ ),+ ],if (widget.status case final status?) ...[const SizedBox(height: 18),status,diff --git a/mobile/lib/phone/welcome/unlock_computer.dart b/mobile/lib/phone/welcome/unlock_computer.dartindex 8852c2983..52b515352 100644--- a/mobile/lib/phone/welcome/unlock_computer.dart+++ b/mobile/lib/phone/welcome/unlock_computer.dart@@ -17,10 +17,10 @@ import 'scan_to_connect.dart';////// ```/// Unlock M2-/// On M2, open Harness ▸ Add Phone…, then scan it.+/// On M2, open Harness ▸ Add Phone…, then scan the QR code./// [ Scan its code ]///-/// or enter its phone password+/// or enter its Harness phone password/// [ •••••••• Show ]/// Unlock///@@ -171,7 +171,7 @@ class _UnlockComputerState extends State<UnlockComputer> {TtyText('Unlock $name', size: 24, weight: FontWeight.w600),const SizedBox(height: 12),Text(- 'On $name, open Harness ▸ Add Phone…, then scan it.',+ 'On $name, open Harness ▸ Add Phone…, then scan the QR code.',style: tty.style(size: TtySize.row, color: tty.faint),),const SizedBox(height: 18),@@ -184,7 +184,7 @@ class _UnlockComputerState extends State<UnlockComputer> {),const SizedBox(height: 28),Text(- 'or enter its phone password',+ 'or enter its Harness phone password',style: tty.style(size: TtySize.meta, color: tty.faint),),const SizedBox(height: 8),@@ -215,7 +215,12 @@ class _UnlockComputerState extends State<UnlockComputer> {),const SizedBox(height: 32),Text(- 'Forgot it, or never set one? On $name, run',+ 'Forgot it? In Harness on $name, choose Machines ▸ $name ▸ Set password.',+ style: tty.style(size: TtySize.meta, color: tty.faint),+ ),+ const SizedBox(height: 8),+ Text(+ 'Using the CLI? Run this on $name:',style: tty.style(size: TtySize.meta, color: tty.faint),),const SizedBox(height: 8),@@ -258,11 +263,6 @@ class _UnlockComputerState extends State<UnlockComputer> {],),),- const SizedBox(height: 8),- Text(- 'or, in the Harness app on $name: Machines → $name → Set password.',- style: tty.style(size: TtySize.meta, color: tty.faint),- ),const SizedBox(height: 28),Row(crossAxisAlignment: CrossAxisAlignment.start,@@ -333,7 +333,10 @@ class _PasswordField extends StatelessWidget {enabledBorder: InputBorder.none,focusedBorder: InputBorder.none,hintText: 'Phone password',- hintStyle: tty.style(size: TtySize.title, color: tty.faint),+ hintStyle: tty.style(+ size: TtySize.title,+ color: tty.placeholder,+ ),),),),diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 564bb5399..36e4bb9e4 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -220,32 +220,6 @@ class MachineState {}}-/// Auth, Remote-machine discovery, E2EE and one explicit terminal attachment.-/// Structured chat intentionally does not exist in the Desktop MVP state.-/// A spoken task the daemon wants THIS window to route — see the `voice_route_request` case below.-///-/// Deliberately not the palette's own [SpokenTask]: this layer holds no callback and knows nothing about-/// dialogs. The screen that can open one turns this into that, and wires the answer back through-/// [AppNotifier.reportVoiceRoute].-class SpokenTaskRequest {- const SpokenTaskRequest({- required this.voiceId,- required this.machineId,- required this.text,- required this.cmd,- });-- final String voiceId;-- /// Which daemon asked — the answer has to go back to that one, not to whichever is selected when the- /// person finally picks.- final String machineId;- final String text;-- /// 'goal', 'loop', or empty: which of the dial's three buttons was held.- final String cmd;-}-/// What every `agents_list` asks for.////// ⚠️ **`includeStopped` is not optional polish — without it the fleet is@@ -288,14 +262,6 @@ class AppNotifier extends ChangeNotifier {final ViewerServices viewer;final ConfigStore? _store;- /// Spoken tasks waiting for a palette. Broadcast because the screen subscribes and unsubscribes with- /// its own lifetime, and a request that arrives with no screen up is dropped rather than queued — the- /// daemon's own deadline is the thing that decides how long a spoken task stays interesting.- final StreamController<SpokenTaskRequest> _spokenTasks =- StreamController<SpokenTaskRequest>.broadcast();-- /// Words from the dial, for whoever can put a palette on screen.- Stream<SpokenTaskRequest> get spokenTasks => _spokenTasks.stream;final Duration turnActivityTimeout;@visibleForTestingfinal WsConn Function(String machineId)? connectionForTest;@@ -681,7 +647,6 @@ class AppNotifier extends ChangeNotifier {if (owner.zoomedPaneId != null) owner.zoomedPaneId = pane.id;_activeSwarmId = owner.id;selectedMachineId = machineId;- _paneFocusRequest++;_persistLayout();notifyListeners();return true;@@ -806,7 +771,6 @@ class AppNotifier extends ChangeNotifier {);}target.focusedPaneId ??= target.panes.firstOrNull?.id;- _paneFocusRequest++;selectSwarm(target.id);return;}@@ -883,7 +847,6 @@ class AppNotifier extends ChangeNotifier {}_activeSwarmId = target.id;_settlePins();- _paneFocusRequest++;selectSwarm(target.id);return true;}@@ -902,23 +865,6 @@ class AppNotifier extends ChangeNotifier {takeControl: takeControl,);- Future<void> seedSwarm(- String name,- List<({String machineId, String agentId})> agents,- ) async {- final target = activeSwarm;- renameSwarm(target.id, name);- // Each call records membership synchronously, before its attachment waits.- // A slow/offline host must not hold back the other panes or retarget a tab.- final attachments = <Future<void>>[];- for (final agent in agents) {- attachments.add(- addAgentToSwarm(agent.machineId, agent.agentId, swarmId: target.id),- );- }- await Future.wait(attachments);- }-/// Which tile the keyboard, the dial and the rail's highlight all mean.////// Typing itself does NOT go through this on macOS — the renderer is a@@ -929,11 +875,6 @@ class AppNotifier extends ChangeNotifier {int? get focusedPaneId => activeSwarm.focusedPaneId;set focusedPaneId(int? value) => activeSwarm.focusedPaneId = value;- int _paneFocusRequest = 0;-- /// Explicit navigation must reveal and refocus even an already-selected pane.- int get paneFocusRequest => _paneFocusRequest;-int _nextPaneId = 1;static const maxPanes = 64;@@ -1108,7 +1049,6 @@ class AppNotifier extends ChangeNotifier {if (moved) _previousPaneId = focusedPaneId;focusedPaneId = paneId;selectedMachineId = focusedPane?.machineId;- if (reveal) _paneFocusRequest++;if (zoomedPaneId != null) zoomedPaneId = paneId;// ⚠️ **Nothing is told which agent is on screen.** The desktop sends `app_focus` and// `app_panes` here for the dial beside it; only the CLI's loopback server reads them@@ -1147,31 +1087,6 @@ class AppNotifier extends ChangeNotifier {if (_dismissedLinkPrompts.remove(machineId)) notifyListeners();}- /// Answer the daemon about a spoken task it asked this window to route.- ///- /// Fire and forget, and correlated by `voiceId` rather than by the rpc convention: the question- /// travelled the other way, so the pending id belongs to the daemon and this is a report, not a- /// request. Sent back to the machine that ASKED — with two daemons attached, answering the selected- /// one leaves the asker waiting on a reply that went to a stranger.- void reportVoiceRoute(- String machineId,- String voiceId,- String state,- String agentId,- ) {- final connection = _pool?[machineId];- if (connection == null) return;- unawaited(- connection- .sendTerminalFrame('voice_route_reply', {- 'voiceId': voiceId,- 'state': state,- if (agentId.isNotEmpty) 'agentId': agentId,- })- .catchError((_) => false),- );- }-MachineState? get activeMachineState {final terminal = activeTerminal;if (terminal != null) return machineStates[terminal.machineId];@@ -1201,19 +1116,6 @@ class AppNotifier extends ChangeNotifier {}}- Future<void> selectAutonomousEnv(String value) async {- if (value != 'prod' && value != 'stag') return;- _autonomousEnv = value;- config = AppConfig(- apiBaseUrl: config.apiBaseUrl,- autonomousEnv: value,- localCliBaseUrl: config.localCliBaseUrl,- );- _lastError = null;- notifyListeners();- await _store?.saveEnvironment(value);- }-Future<void> bootstrap() async {try {if (_store != null) {@@ -2310,10 +2212,7 @@ class AppNotifier extends ChangeNotifier {final testConnection = connectionForTest;if (testConnection != null) return testConnection(machineId);// Every machine is dialled through the relay: there is no local CLI to proxy for it.- final connection = _pool!.connFor(- machineId,- transportKind: WsTransportKind.cloudE2ee,- );+ final connection = _pool!.connFor(machineId);_wireConnectionHooks(connection, machineId);return connection;}@@ -4375,26 +4274,6 @@ class AppNotifier extends ChangeNotifier {}}- /// Opens a dial notification in this swarm without changing other memberships.- ///- /// Already on screen means FOCUS it, never open it twice: the daemon keeps a- /// single controller per agent, so a second open is a takeover — the window- /// would fight itself and the first tile would go dark with- /// `TERMINAL_TAKEN_OVER`.- ///- /// At capacity, the usual visible capacity error asks for another swarm.- Future<void> openAgentFromDial(String machineId, String agentId) async {- // Already on the desk: it has its tile, so this is only "look at it".- final existing = paneOfAgent(machineId, agentId);- if (existing != null) {- focusPane(existing.id);- selectedMachineId = machineId;- notifyListeners();- return;- }- await addAgentToSwarm(machineId, agentId);- }-/// Enable-time fallback: preserve the user's current choice and acknowledge it./// Selection records focus before waiting for terminal attachment, so a later/// user click is never overwritten by completion of an asynchronous open.@@ -4844,64 +4723,14 @@ class AppNotifier extends ChangeNotifier {terminal.dispose();}- /// Take a tile off the grid.- ///- /// Closing sends `terminal_close`, which is what lets the daemon put the- /// agent's tmux window back to the size it had before this app borrowed it —- /// a tile that vanished without saying so would leave that agent living in a- /// quarter-width terminal.- /// Put the pane at [paneId] where [targetPaneId] is, and that one where this- /// one was.- ///- /// A SWAP, not an insert. Position here is nothing but the index in [panes] —- /// PaneGrid lays the list out row-major — and on a 2x2 grid "between two- /// cells" names no place, so shifting the others would move tiles the user- /// did not touch. Swapping leaves every other tile exactly where it was.- ///- /// Focus follows the PANE, not the slot: `focusedPaneId` is an id, so a tile- /// that was focused stays focused after it moves, which is what the hand that- /// dragged it expects.- void reorderPane(int paneId, int targetPaneId) {- if (paneId == targetPaneId) return;- final from = panes.indexWhere((pane) => pane.id == paneId);- final to = panes.indexWhere((pane) => pane.id == targetPaneId);- if (from == -1 || to == -1) return;- final moved = panes[from];- panes[from] = panes[to];- panes[to] = moved;- // The pin follows the hand. A pinned tile dragged elsewhere is someone- // saying "here now", and a pinned tile displaced by another drag was still- // put there deliberately — bouncing either back would make the drag look- // broken while the state was in fact correct.- if (isPanePinned(panes[to])) _setPin(panes[to], to);- if (isPanePinned(panes[from])) _setPin(panes[from], from);- _persistLayout();- notifyListeners();- }-- bool hasNavigationRail = true;-/// ⌘; — the pane focused before this one.////// tmux spells it the same way, and the reason it earns a key is that two/// agents at a time is the shape most work actually has: a thing being built/// and a thing being watched. Walking a list to get back to the other one is/// the wrong motion, and it gets longer as the grid fills.- int? get _previousPaneId => activeSwarm.previousPaneId;set _previousPaneId(int? value) => activeSwarm.previousPaneId = value;- void focusLastPane() {- final back = _previousPaneId;- if (back == null) return;- if (!panes.any((pane) => pane.id == back)) {- // It was closed while we were away. Say nothing and stay put — jumping- // somewhere arbitrary is worse than a key that did not fire.- _previousPaneId = null;- return;- }- focusPane(back);- }-/// ⌘⏎ — one pane filling the grid, and back.////// The id is held rather than a flag, so a zoom SURVIVES the thing that@@ -4911,80 +4740,6 @@ class AppNotifier extends ChangeNotifier {int? get zoomedPaneId => activeSwarm.zoomedPaneId;set zoomedPaneId(int? value) => activeSwarm.zoomedPaneId = value;- void toggleZoomPane() {- final id = focusedPaneId;- if (id == null || panes.length < 2) return;- zoomedPaneId = zoomedPaneId == id ? null : id;- _persistLayout();- notifyListeners();- }-- /// Focus the nth tile on the grid — ⌘1…⌘9.- ///- /// The number is the tile's position on screen, which is also the number the- /// dial walks, so "the third one" means one thing wherever it is said. A digit- /// past the last tile does NOTHING: it used to address the sidebar instead,- /// where ⌘3 opened an agent that was not on the grid and replaced a tile to- /// show it — a key meant only to look, rearranging the desk.- void focusPaneByIndex(int index) {- if (index < 0 || index >= panes.length) return;- focusPane(panes[index].id);- }-- /// Walk the focus one tile — ⌘← / ⌘→, and ⌘[ / ⌘].- ///- /// Wraps, because the grid is what the eye reads as a loop of tiles; stopping- /// dead at the last one reads as a broken key. Moves focus ONLY — nothing on- /// the grid changes, which is what separates it from [movePaneBy].- void focusPaneBy(int delta) {- if (panes.length < 2) return;- final at = panes.indexWhere((pane) => pane.id == focusedPaneId);- final next = at < 0 ? 0 : (at + delta + panes.length) % panes.length;- focusPane(panes[next].id);- }-- /// Move the focused pane one slot, for the keyboard twin of the drag.- ///- /// Stops at the ends rather than wrapping: the grid is a shape, not a ring,- /// and a tile jumping from the last slot to the first reads as a bug.- void movePaneBy(int delta) {- final id = focusedPaneId;- if (id == null) return;- final from = panes.indexWhere((pane) => pane.id == id);- if (from == -1) return;- final to = from + delta;- if (to < 0 || to >= panes.length) return;- reorderPane(id, panes[to].id);- }-- /// Pin this tile to the slot it is in, or let it go.- ///- /// Pinning records the CURRENT slot rather than asking for one: the tile the- /// user is looking at is the answer they mean, and a dialog asking "which- /// number?" would be arithmetic about a thing they can already see.- int? pinnedSlotFor(TerminalPane pane) =>- hasNavigationRail ? pane.pinnedSlot : activeSwarm.pinnedSlots[pane.id];-- bool isPanePinned(TerminalPane pane) => pinnedSlotFor(pane) != null;-- void _setPin(TerminalPane pane, int? slot) {- if (slot == null) {- activeSwarm.pinnedSlots.remove(pane.id);- } else {- activeSwarm.pinnedSlots[pane.id] = slot;- }- if (hasNavigationRail) pane.pinnedSlot = slot;- }-- void togglePinPane(int paneId) {- final index = panes.indexWhere((pane) => pane.id == paneId);- if (index == -1) return;- final pane = panes[index];- _setPin(pane, isPanePinned(pane) ? null : index);- _persistLayout();- notifyListeners();- }-/// Put pinned tiles back in their slots after the list moved under them.////// Lifted rather than swapped: after a close everyone has slid up one, and@@ -4997,10 +4752,10 @@ class AppNotifier extends ChangeNotifier {/// closed can come back, and forgetting the pin the moment the grid got small/// would quietly undo a choice the user never revisited.void _settlePins() {- final pinned = panes.where(isPanePinned).toList()- ..sort((a, b) => pinnedSlotFor(a)!.compareTo(pinnedSlotFor(b)!));+ final pinned = panes.where((pane) => pane.pinnedSlot != null).toList()+ ..sort((a, b) => a.pinnedSlot!.compareTo(b.pinnedSlot!));for (final pane in pinned) {- final want = pinnedSlotFor(pane)!;+ final want = pane.pinnedSlot!;if (want >= panes.length) continue;final at = panes.indexOf(pane);if (at == want) continue;@@ -5387,32 +5142,6 @@ class AppNotifier extends ChangeNotifier {}}break;- case 'voice_route_request':- // WORDS SPOKEN INTO THE DIAL, handed here to be routed.- //- // The dial used to pick the agent itself with an older copy of this router — no candidate cap,- // untrimmed recaps, a shorter budget, and no way to ask when it was unsure, so an uncertain- // route was still a send. This window has the palette that can hold the answer up, so the- // decision moved to it and the dial became the microphone.- //- // The daemon is waiting on a reply for this voiceId; SpokenTask is what guarantees one goes- // back on every path out of the palette.- final voiceId = payload['voiceId'];- final spokenText = payload['text'];- if (voiceId is String &&- voiceId.isNotEmpty &&- spokenText is String &&- spokenText.trim().isNotEmpty) {- _spokenTasks.add(- SpokenTaskRequest(- voiceId: voiceId,- machineId: machineId,- text: spokenText.trim(),- cmd: payload['cmd'] is String ? payload['cmd'] as String : '',- ),- );- }- break;case 'dial_swarm':// The dial picked a swarm from its own list. The ordinary switch, exactly as ⌘] or a click on// the tab: the desk changes, `_persistLayout` re-describes it, and the dial's ring and swarm@@ -5420,17 +5149,6 @@ class AppNotifier extends ChangeNotifier {final swarmId = payload['swarmId'];if (swarmId is String && swarmId.isNotEmpty) selectSwarm(swarmId);break;- case 'dial_open':- // A notification was tapped on the dial. Unlike `dial_focus` this asks for a tile of its own —- // see openAgentFromDial for why a finished turn is not a replacement for what is on screen.- final openId = payload['agentId'];- if (openId is String && openId.isNotEmpty) {- final targetMachineId = _dialFocusMachine(payload, openId);- if (targetMachineId != null) {- unawaited(openAgentFromDial(targetMachineId, openId));- }- }- break;case 'desk_changed':// The account's tabs changed — in a window on some computer, or on// another phone. The frame carries only the revision; the document@@ -5803,7 +5521,6 @@ class AppNotifier extends ChangeNotifier {for (final swarm in swarms) {swarm.panes.clear();}- unawaited(_spokenTasks.close());sessionPreviews.dispose();agentNotices.dispose();_desk.dispose();diff --git a/mobile/lib/state/dial_status.dart b/mobile/lib/state/dial_status.dartindex d9ddca689..abcf43861 100644--- a/mobile/lib/state/dial_status.dart+++ b/mobile/lib/state/dial_status.dart@@ -53,16 +53,6 @@ class DialState extends ChangeNotifier {DialStatus status = DialStatus.none;bool seen = false;- Future<void> restore() async {- try {- seen = (await _storage?.read(_seenKey)) == '1';- } catch (_) {- seen =- false; // a missing or unreadable file is a first run, not a failure- }- notifyListeners();- }-void apply(DialStatus next) {status = next;if (next.attached && !seen) {diff --git a/mobile/lib/terminal/terminal_link_opener.dart b/mobile/lib/terminal/terminal_link_opener.dartindex 21d04a3ff..64dfdee3a 100644--- a/mobile/lib/terminal/terminal_link_opener.dart+++ b/mobile/lib/terminal/terminal_link_opener.dart@@ -10,19 +10,13 @@ class TerminalLinkOpener {TerminalLinkOpener({Future<bool> Function(Uri)? launch,Future<bool> Function(String)? fileExists,- String? homeDirectory,bool? windows,}) : _launch = launch ?? _launchExternal,_fileExists = fileExists ?? _exists,- _homeDirectory =- homeDirectory ??- Platform.environment['HOME'] ??- Platform.environment['USERPROFILE'],_windows = windows ?? Platform.isWindows;final Future<bool> Function(Uri) _launch;final Future<bool> Function(String) _fileExists;- final String? _homeDirectory;final bool _windows;static Future<bool> _launchExternal(Uri uri) =>@@ -32,7 +26,6 @@ class TerminalLinkOpener {/// Null means the OS accepted the request; otherwise a user-facing failure.Future<String?> open(String target, {- required bool isLocalMachine,Future<String> Function(String target)? downloadRemote,bool Function()? isCancelled,}) async {@@ -47,62 +40,29 @@ class TerminalLinkOpener {if (parsed.host.isEmpty) return 'This link is not supported.';uri = parsed;} else {- if (!isLocalMachine) {- if (parsed.scheme == 'file' &&- parsed.host.isNotEmpty &&- parsed.host != 'localhost') {- return 'This file is on another machine.';- }- if (parsed.hasScheme &&- parsed.scheme != 'file' &&- !RegExp(r'^[a-z]:[\\/]', caseSensitive: false).hasMatch(target)) {- return 'This link is not supported.';- }- if (!isMediaPath(parsed.scheme == 'file' ? parsed.path : target)) {- return 'Only image and video files can be opened here.';- }- if (downloadRemote == null) {- return 'This file is on another machine. Update Harness to download a preview.';- }- // Resolve paths on the owning machine; open only the completed local copy.- final localPath = await downloadRemote(target);- if (isCancelled?.call() == true) return null;- if (!await _fileExists(localPath)) {- return 'The downloaded preview is no longer available. Try again.';- }- uri = Uri.file(localPath, windows: _windows);- } else {- var path = target;- if (parsed.scheme == 'file') {- if (parsed.host.isNotEmpty && parsed.host != 'localhost') {- return 'This file is on another machine.';- }- path = parsed- .replace(host: '', query: '', fragment: '')- .toFilePath(windows: _windows);- } else if (parsed.hasScheme &&- !RegExp(r'^[a-z]:[\\/]', caseSensitive: false).hasMatch(path)) {- return 'This link is not supported.';- }- if (path.startsWith('~/') && _homeDirectory != null) {- path = '$_homeDirectory/${path.substring(2)}';- }- if (!isMediaPath(path)) {- return 'Only image and video files can be opened here.';- }- final absolute = _windows- ? RegExp(r'^[a-z]:[\\/]', caseSensitive: false).hasMatch(path)- : path.startsWith('/') && !path.startsWith('//');- if (!absolute) {- // Agent frames do not advertise cwd. Never resolve against Desktop's- // process directory, which belongs to a different app and workspace.- return 'Use the full file path to open this preview. The harness’s working folder is not available.';- }- if (!await _fileExists(path)) {- return 'This file is not available on this computer. It may still be generating or may have moved.';- }- uri = Uri.file(path, windows: _windows);+ if (parsed.scheme == 'file' &&+ parsed.host.isNotEmpty &&+ parsed.host != 'localhost') {+ return 'This file is on another machine.';}+ if (parsed.hasScheme &&+ parsed.scheme != 'file' &&+ !RegExp(r'^[a-z]:[\\/]', caseSensitive: false).hasMatch(target)) {+ return 'This link is not supported.';+ }+ if (!isMediaPath(parsed.scheme == 'file' ? parsed.path : target)) {+ return 'Only image and video files can be opened here.';+ }+ if (downloadRemote == null) {+ return 'This file is on another machine. Update Harness to download a preview.';+ }+ // Resolve paths on the owning machine; open only the completed local copy.+ final localPath = await downloadRemote(target);+ if (isCancelled?.call() == true) return null;+ if (!await _fileExists(localPath)) {+ return 'The downloaded preview is no longer available. Try again.';+ }+ uri = Uri.file(localPath, windows: _windows);}if (isCancelled?.call() == true) return null;if (!await _launch(uri)) {diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dartindex 7cef6b1e4..040ceefd7 100644--- a/mobile/lib/widgets/terminal_panel.dart+++ b/mobile/lib/widgets/terminal_panel.dart@@ -1035,7 +1035,6 @@ class _TerminalPanelState extends State<TerminalPanel>final message = await _linkOpener.open(target,// The agent runs on another machine: a file it names is there, not here.- isLocalMachine: false,isCancelled: () =>cancellation.isCancelled ||!mounted ||diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dartindex 584cb1b31..170f34789 100644--- a/mobile/lib/ws/ws_conn.dart+++ b/mobile/lib/ws/ws_conn.dart@@ -32,7 +32,11 @@ class WsCredentialRevoked implements Exception {String toString() => message;}-enum WsTransportKind { cloudE2ee, localPlaintext }+/// Socket construction can be replaced by an in-process channel in tests.+typedef WsChannelFactory = WebSocketChannel Function(+ Uri uri, {+ Iterable<String>? protocols,+});/// A `request()` call got no reply within its timeout — distinct from other request-level errors/// (an explicit `{error: ...}` response) so callers can tell "the peer is unresponsive" apart from@@ -80,22 +84,16 @@ class WsRequestFailure implements Exception {/// One SSO-authenticated, machine-scoped connection to `/api/web-ws`.class WsConn {+ final WsChannelFactory? connectChannel;final String wsBaseUrl;final String autonomousEnv;final String machineId;final AccessTokenProvider accessTokenProvider;final void Function(String message) onAuthFailure;- /// The local CLI closed this connection with a specific, non-retryable reason (currently just- /// `NO_PEER_LINK`: the target machine has no `harness link import`ed trust yet) — surfaced instead- /// of silently reconnecting forever against a failure the user has to act on to fix.+ /// A peer-link failure that needs user action, surfaced instead of retrying+ /// a connection until trust has been established.final void Function(int code, String reason)? onLocalFailure;- final WsTransportKind transportKind;- final Uri? localWsUri;-- /// Retained only for fixture constructor compatibility. Local transport ignores it.- final String? localApiKey;- final int localProtocolVersion;/// A viewer build's end-to-end session with the machine, minted fresh on every connect — the/// role the harness CLI plays everywhere else (see [RelayCodec]). Null leaves the relay's frames@@ -129,7 +127,6 @@ class WsConn {int _attempt = 0;Timer? _reconnectTimer;String? _tokenUsed;- bool _forceRelayReconnect = false;/// How long a dial may take to open before it counts as failed. Without one, a socket dialled/// into a network that swallows packets waits out the OS's own TCP timeout — over a minute on@@ -174,13 +171,11 @@ class WsConn {/// True once this connection has permanently given up (a deliberate [close], or a non-retryable/// local failure like NO_PEER_LINK) — [WsPool] must not hand a closed connection back out.bool get isClosed => _closing;- bool get isLocal => transportKind == WsTransportKind.localPlaintext;- String get endpointKey => isLocal- ? 'local:${localWsUri.toString()}'- : 'cloud:$wsBaseUrl:$autonomousEnv';+ String get endpointKey => 'cloud:$wsBaseUrl:$autonomousEnv';WsConn({required this.wsBaseUrl,+ this.connectChannel,required this.autonomousEnv,required this.machineId,required this.accessTokenProvider,@@ -188,10 +183,6 @@ class WsConn {this.onLocalFailure,required this.onEvent,required this.onStatus,- this.transportKind = WsTransportKind.cloudE2ee,- this.localWsUri,- this.localApiKey,- this.localProtocolVersion = 1,this.relayCodecs,this.transportPlugins,});@@ -224,13 +215,11 @@ class WsConn {// In series they were two waits stacked in front of the dial, on the// stretch the phone shows as "Connecting to your machine…", and every// reconnect paid it again.- final codecs = isLocal ? null : relayCodecs;- final pendingToken = isLocal- ? null- : StartupTrace.time(- 'ws.accessToken',- () => accessTokenProvider(false, null),- );+ final codecs = relayCodecs;+ final pendingToken = StartupTrace.time(+ 'ws.accessToken',+ () => accessTokenProvider(false, null),+ );// ⚠️ **The codec's own failure is captured HERE, where the future is made,// not where it is awaited.** The credential is awaited first and can// throw — a refresh against a dead network does — and every path out of@@ -245,13 +234,15 @@ class WsConn {// it is rethrown below into the catch that schedules the reconnect.final pendingCodec = codecs == null? null- : StartupTrace.time('ws.relayCodec', () => codecs(machineId))- .then<({RelayCodec? codec, Object? error})>(- (codec) => (codec: codec, error: null),- onError: (Object error) => (codec: null, error: error),- );+ : StartupTrace.time(+ 'ws.relayCodec',+ () => codecs(machineId),+ ).then<({RelayCodec? codec, Object? error})>(+ (codec) => (codec: codec, error: null),+ onError: (Object error) => (codec: null, error: error),+ );final token = await pendingToken;- if (!isLocal && (token == null || token.isEmpty)) {+ if (token.isEmpty) {throw StateError('WebSocket credential is missing');}if (_closing) return;@@ -272,26 +263,17 @@ class WsConn {final plugins = transportPlugins;if (plugins != null) _plugin = plugins(_PluginHost(this), machineId);}- final Uri uri;- if (isLocal) {- final local = localWsUri;- if (local == null ||- (local.host != '127.0.0.1' && local.host != 'localhost')) {- throw StateError('Local WebSocket must use loopback');- }- uri = local;- } else {- final base = Uri.parse('$wsBaseUrl/api/web-ws');- uri = base.replace(- queryParameters: {- ...base.queryParameters,- 'autonomousEnv': autonomousEnv,- },- );- }- final channel = dialing = isLocal- ? WebSocketChannel.connect(uri)- : WebSocketChannel.connect(uri, protocols: [token!]);+ final base = Uri.parse('$wsBaseUrl/api/web-ws');+ final uri = base.replace(+ queryParameters: {+ ...base.queryParameters,+ 'autonomousEnv': autonomousEnv,+ },+ );+ final channel = dialing = (connectChannel ?? WebSocketChannel.connect)(+ uri,+ protocols: [token],+ );_channel = channel;await StartupTrace.time('ws.dial',@@ -305,7 +287,7 @@ class WsConn {appLog.warn('ws','dial abandoned after ready (closing=$_closing '- 'superseded=$superseded) $machineId',+ 'superseded=$superseded) $machineId',);await channel.sink.close();// ⚠️ A superseded dial must leave a live connection behind it. This used@@ -322,8 +304,6 @@ class WsConn {onDone: () => _onDone(channel),onError: (_) => _onDone(channel),);- final forceRelayReconnect = _forceRelayReconnect;- _forceRelayReconnect = false;// ⚠️ **Armed BEFORE the send, and deliberately not after it.** `sendFrame`// queues behind `_outboundTail`, so it resolves when this frame reaches// the socket — which is not guaranteed to be soon, and on a fresh dial was@@ -339,11 +319,7 @@ class WsConn {appLog.debug('ws', '→ machine_select $machineId');await sendFrame({'type': 'machine_select',- 'payload': {- 'machineId': machineId,- if (isLocal) 'localProtocolVersion': localProtocolVersion,- if (isLocal && forceRelayReconnect) 'forceReconnect': true,- },+ 'payload': {'machineId': machineId},});} on WsCredentialRevoked catch (error) {// ⚠️ Not for a connection somebody already closed. Signing out closes every connection, and@@ -889,20 +865,6 @@ class WsConn {return;}final code = channel.closeCode;- if (isLocal) {- if (code == 4404) {- _closing = true;- // needsLink first: AppNotifier's onStatus handler reads machine.needsLink- // to decide whether a disconnect should be treated as the node going- // offline — it has to see it flipped before onStatus runs, or the very- // first 4404 for this machine reads as offline for one retry cycle.- onLocalFailure?.call(code!, channel.closeReason ?? 'NO_PEER_LINK');- onStatus(ConnectionStatus.disconnected);- return;- }- _scheduleReconnect();- return;- }if (code == 4401) {unawaited(_refreshAndReconnect());return;@@ -920,7 +882,9 @@ class WsConn {await accessTokenProvider(true, _tokenUsed);} on WsCredentialRevoked {// As in [connect]: a closed connection has nobody left to sign out.- if (!_closing) _signOut('Your SSO session expired. Please sign in again.');+ if (!_closing) {+ _signOut('Your SSO session expired. Please sign in again.');+ }return;} catch (_) {// The token is still stale, so the next dial refreshes again on its own.@@ -1029,8 +993,7 @@ class WsConn {Future<void> forceReconnect() async {// A viewer's relay connection holds that session itself, so for it this is simply a fresh dial// — and with it a fresh session.- if (_closing || (!isLocal && relayCodecs == null)) return;- _forceRelayReconnect = true;+ if (_closing || relayCodecs == null) return;_reconnectTimer?.cancel();// This dials again itself; a pending watchdog would make that two dials._selectWatchdog?.cancel();diff --git a/mobile/lib/ws/ws_pool.dart b/mobile/lib/ws/ws_pool.dartindex 52a192ebd..9bd8953ba 100644--- a/mobile/lib/ws/ws_pool.dart+++ b/mobile/lib/ws/ws_pool.dart@@ -9,6 +9,7 @@ import 'ws_conn.dart';/// Owns one SSO-authenticated [WsConn] per machine.class WsPool {+ final WsChannelFactory? connectChannel;final String wsBaseUrl;final String autonomousEnv;@@ -30,6 +31,7 @@ class WsPool {WsPool({required this.wsBaseUrl,+ this.connectChannel,required this.autonomousEnv,this.relayCodecs,this.transportPlugins,@@ -40,16 +42,8 @@ class WsPool {required this.onStatus,});- WsConn connFor(- String machineId, {- WsTransportKind transportKind = WsTransportKind.cloudE2ee,- Uri? localWsUri,- String? localApiKey,- int localProtocolVersion = 1,- }) {- final desiredKey = transportKind == WsTransportKind.localPlaintext- ? 'local:${localWsUri.toString()}'- : 'cloud:$wsBaseUrl:$autonomousEnv';+ WsConn connFor(String machineId) {+ final desiredKey = 'cloud:$wsBaseUrl:$autonomousEnv';final current = _conns[machineId];if (current != null &¤t.endpointKey == desiredKey &&@@ -63,7 +57,7 @@ class WsPool {appLog.warn('ws','replacing connection $machineId '- '(was ${current.endpointKey}, now $desiredKey)',+ '(was ${current.endpointKey}, now $desiredKey)',);unawaited(current.close());}@@ -80,13 +74,10 @@ class WsPool {conn = WsConn(wsBaseUrl: wsBaseUrl,+ connectChannel: connectChannel,autonomousEnv: autonomousEnv,- relayCodecs: transportKind == WsTransportKind.cloudE2ee- ? relayCodecs- : null,- transportPlugins: transportKind == WsTransportKind.cloudE2ee- ? transportPlugins- : null,+ relayCodecs: relayCodecs,+ transportPlugins: transportPlugins,machineId: machineId,accessTokenProvider: accessTokenProvider,onAuthFailure: (message) {@@ -103,10 +94,6 @@ class WsPool {onStatus: (status) {if (!replaced()) onStatus(machineId, status);},- transportKind: transportKind,- localWsUri: localWsUri,- localApiKey: localApiKey,- localProtocolVersion: localProtocolVersion,);_conns[machineId] = conn;unawaited(conn.connect());diff --git a/mobile/test/api/api_client_test.dart b/mobile/test/api/api_client_test.dartindex ff7a2a9e7..98774f7bb 100644--- a/mobile/test/api/api_client_test.dart+++ b/mobile/test/api/api_client_test.dart@@ -16,52 +16,68 @@ import 'package:harness_mobile/viewer/email_code_api.dart';import '../viewer/fake_http.dart';import '../voice_fakes.dart' show MemoryKeyValueStore;-/// The backend on loopback — nothing leaves the process. Each request is recorded, and answered-/// by [answer] with a status and a JSON body.-class _Backend {- _Backend._(this.server);-- final HttpServer server;- final requests =- <- ({- String method,- String path,- Map<String, String> query,- HttpHeaders headers,- List<int> body,- })- >[];- ({int status, Object? body}) Function(HttpRequest request, int index) answer =- (_, _) =>- (status: 200, body: {'success': true, 'data': <String, Object?>{}});-- String get url => 'http://127.0.0.1:${server.port}';-- static Future<_Backend> start() async {- final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);- final backend = _Backend._(server);- server.listen((request) async {- final body = await request.fold<List<int>>(- [],- (all, chunk) => all..addAll(chunk),- );- final index = backend.requests.length;- backend.requests.add((- method: request.method,- path: request.uri.path,- query: request.uri.queryParameters,- headers: request.headers,- body: body,- ));- final reply = backend.answer(request, index);- request.response- ..statusCode = reply.status- ..headers.contentType = ContentType.json- ..write(jsonEncode(reply.body));- await request.response.close();- });- return backend;+/// Answers serialized HTTP requests in-process, after the real auth interceptors.+class _Backend implements HttpClientAdapter {+ final requests = <_Request>[];+ ({int status, Object? body}) Function(_Request request, int index) answer = (+ _,+ _,+ ) => (status: 200, body: {'success': true, 'data': <String, Object?>{}});++ @override+ Future<ResponseBody> fetch(+ RequestOptions options,+ Stream<Uint8List>? requestStream,+ Future<void>? cancelFuture,+ ) async {+ final body =+ await requestStream?.fold<List<int>>(+ [],+ (all, chunk) => all..addAll(chunk),+ ) ??+ <int>[];+ final request = _Request(+ options.method,+ options.uri.path,+ options.uri.queryParameters,+ _Headers(options.headers),+ body,+ );+ final index = requests.length;+ requests.add(request);+ final reply = answer(request, index);+ return ResponseBody.fromString(+ jsonEncode(reply.body),+ reply.status,+ headers: {+ Headers.contentTypeHeader: [Headers.jsonContentType],+ },+ );+ }++ @override+ void close({bool force = false}) {}+}++class _Request {+ _Request(this.method, this.path, this.query, this.headers, this.body);+ final String method, path;+ final Map<String, String> query;+ final _Headers headers;+ final List<int> body;+}++class _Headers {+ _Headers(Map<String, dynamic> headers)+ : values = {+ for (final entry in headers.entries)+ entry.key.toLowerCase(): entry.value.toString(),+ };+ final Map<String, String> values;+ String? value(String key) => values[key.toLowerCase()];+ ContentType? get contentType {+ final type = value('content-type');+ return type == null ? null : ContentType.parse(type);}}@@ -86,11 +102,14 @@ class _Tokens implements AccessTokenSource {void main() {late _Backend backend;- setUp(() async => backend = await _Backend.start());- tearDown(() async => backend.server.close(force: true));+ setUp(() => backend = _Backend());ApiClient client(AccessTokenSource auth) => ApiClient(- config: AppConfig(apiBaseUrl: backend.url, autonomousEnv: 'stag'),+ config: const AppConfig(+ apiBaseUrl: 'https://api.invalid',+ autonomousEnv: 'stag',+ ),+ httpClientAdapter: backend,session: AuthSession(storage: MemoryKeyValueStore()),auth: auth,);@@ -98,6 +117,19 @@ void main() {Map<String, Object?> ok(Object? data) => {'success': true, 'data': data};group('signing', () {+ test(+ 'a real API call without credentials fails before transport',+ () async {+ final api = ApiClient(+ config: const AppConfig(apiBaseUrl: 'https://api.invalid'),+ session: AuthSession(storage: MemoryKeyValueStore()),+ httpClientAdapter: backend,+ );+ await expectLater(api.me(), throwsStateError);+ expect(backend.requests, isEmpty);+ },+ );+test('every call carries the bearer and the environment', () async {backend.answer = (_, _) => (status: 200, body: ok({'email': '[email protected]'}));final me = await client(_Tokens(['t1'])).me();@@ -345,11 +377,25 @@ void main() {message: type == DioExceptionType.unknown ? 'boom' : null,);+ test('phone backend errors never point to a local daemon', () {+ for (final type in [+ DioExceptionType.connectionError,+ DioExceptionType.receiveTimeout,+ DioExceptionType.badResponse,+ ]) {+ final message = describeApiError(dio(type, status: 503));+ expect(message, contains('Harness'));+ expect(message, isNot(contains('local')));+ expect(message, isNot(contains('port')));+ expect(message, isNot(contains('restarts')));+ }+ });+test('says which leg failed, in words', () {expect(describeApiError(ApiException('nope')), 'nope');expect(describeApiError(dio(DioExceptionType.connectionError)),- contains('not answering'),+ contains('could not reach Harness'),);expect(describeApiError(dio(DioExceptionType.receiveTimeout)),diff --git a/mobile/test/clipboard_test.dart b/mobile/test/clipboard_test.dartnew file mode 100644index 000000000..212bfa1b4--- /dev/null+++ b/mobile/test/clipboard_test.dart@@ -0,0 +1,45 @@+import 'dart:io';++import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/clipboard/native_clipboard.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ const channel = MethodChannel('harness/clipboard_image');+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ final supported = Platform.isMacOS || Platform.isLinux;+ tearDown(() => messenger.setMockMethodCallHandler(channel, null));++ test('image clipboard exchanges the exact PNG bytes', () async {+ final png = Uint8List.fromList([137, 80, 78, 71]);+ Object? written;+ messenger.setMockMethodCallHandler(channel, (call) async {+ if (call.method == 'readImagePng') return png;+ written = call.arguments;+ return true;+ });+ expect(await NativeClipboard.readImagePng(), supported ? png : null);+ expect(await NativeClipboard.writeImagePng(png), supported);+ expect(written, supported ? png : null);+ });++ test('missing platform handler falls back to text', () async {+ expect(await NativeClipboard.readImagePng(), isNull);+ expect(await NativeClipboard.writeImagePng(Uint8List(0)), isFalse);+ });++ for (final reply in ['empty', 'refused', 'failed']) {+ test('clipboard $reply does not interrupt terminal input', () async {+ messenger.setMockMethodCallHandler(channel, (call) async {+ if (reply == 'failed') throw PlatformException(code: 'unavailable');+ return call.method == 'writeImagePng' && reply == 'refused'+ ? false+ : null;+ });+ expect(await NativeClipboard.readImagePng(), isNull);+ expect(await NativeClipboard.writeImagePng(Uint8List(0)), isFalse);+ });+ }+}diff --git a/mobile/test/connect_computer_test.dart b/mobile/test/connect_computer_test.dartindex 14925708f..8c70f6bae 100644--- a/mobile/test/connect_computer_test.dart+++ b/mobile/test/connect_computer_test.dart@@ -105,7 +105,7 @@ void main() {expect(find.byType(SetUpComputerPage), findsOneWidget);expect(find.text('Apple Silicon'), findsOneWidget);expect(find.textContaining('Waiting for your computer'), findsOneWidget);- expect(find.text('Try the sample while you wait'), findsOneWidget);+ expect(find.text('Try the sample ›'), findsOneWidget);// The old page's second way of saying all this is gone.expect(find.text('Email me the setup link'), findsNothing);expect(find.textContaining('remote-password'), findsNothing);diff --git a/mobile/test/core_small_units_test.dart b/mobile/test/core_small_units_test.dartindex 29cc67014..0a981f2b0 100644--- a/mobile/test/core_small_units_test.dart+++ b/mobile/test/core_small_units_test.dart@@ -97,7 +97,6 @@ void main() {'ws://127.0.0.1:4000',);expect(AppConfig.dev.autonomousEnv, 'prod');- expect(AppConfig.dev.localCliBaseUrl, 'http://127.0.0.1:18473');});});diff --git a/mobile/test/flutter_test_config.dart b/mobile/test/flutter_test_config.dartindex 725292a0d..66cc5f369 100644--- a/mobile/test/flutter_test_config.dart+++ b/mobile/test/flutter_test_config.dart@@ -13,6 +13,7 @@ import 'package:harness_mobile/core/harness_file_store.dart';/// write the developer's real state — sessions and E2EE keys included. See the/// rules in `mobile/README.md`.Future<void> testExecutable(FutureOr<void> Function() testMain) async {+ HttpOverrides.global = _NoNetwork();final home = Directory.systemTemp.createTempSync('harness-test-home-');HarnessFileStore.homeForTest = home.path;tearDownAll(() {@@ -20,3 +21,10 @@ Future<void> testExecutable(FutureOr<void> Function() testMain) async {});await testMain();}++class _NoNetwork extends HttpOverrides {+ @override+ HttpClient createHttpClient(SecurityContext? context) => throw StateError(+ 'Network is disabled in tests. Inject an in-memory transport.',+ );+}diff --git a/mobile/test/logging/log_stream_lifecycle_test.dart b/mobile/test/logging/log_stream_lifecycle_test.dartnew file mode 100644index 000000000..04ff2a3b3--- /dev/null+++ b/mobile/test/logging/log_stream_lifecycle_test.dart@@ -0,0 +1,30 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/logging/app_log.dart';+import 'package:harness_mobile/logging/log_stream.dart';++void main() {+ test(+ 'clearing a log notifies once and preserves its live read-only view',+ () async {+ final stream = LogStream();+ final entries = stream.entries;+ var updates = 0;+ stream.addListener(() => updates++);+ stream.add(AppLogLevel.info, 'app', 'one');+ stream.clear();+ stream.clear();+ await Future<void>.delayed(Duration.zero);+ expect(entries, isEmpty);+ expect(updates, 1);+ expect(() => entries.clear(), throwsUnsupportedError);+ stream.dispose();+ },+ );++ test('disposing after a log burst cancels its queued notification', () async {+ final stream = LogStream();+ stream.add(AppLogLevel.info, 'app', 'closing');+ stream.dispose();+ await Future<void>.delayed(Duration.zero);+ });+}diff --git a/mobile/test/pane_layout_store_test.dart b/mobile/test/pane_layout_store_test.dartnew file mode 100644index 000000000..74e743999--- /dev/null+++ b/mobile/test/pane_layout_store_test.dart@@ -0,0 +1,109 @@+import 'dart:async';+import 'dart:convert';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/state/pane_layout_store.dart';+import 'package:harness_mobile/state/swarm.dart';++class _Store implements LocalKeyValueStore {+ final values = <String, String>{};+ final writes = <String>[];+ final gates = <Completer<void>>[];+ bool holdWrites = false;+ bool failReads = false;++ @override+ Future<String?> read(String key) async {+ if (failReads) throw StateError('storage unavailable');+ return values[key];+ }++ @override+ Future<void> write(String key, String value) async {+ writes.add(value);+ if (holdWrites) {+ final gate = Completer<void>();+ gates.add(gate);+ await gate.future;+ }+ values[key] = value;+ }++ @override+ Future<void> delete(String key) async => values.remove(key);+}++void main() {+ test(+ 'restoration drops malformed and duplicate panes, and caps old layouts',+ () async {+ final storage = _Store()+ ..values['terminal_pane_layout'] = jsonEncode([+ null,+ {'machineId': 'studio', 'agentId': 'one'},+ {'machineId': 'studio', 'agentId': 'one'},+ for (var i = 0; i < 15; i++)+ {'machineId': 'studio', 'agentId': 'agent-$i'},+ ]);+ final layout = await PaneLayoutStore(storage: storage).load();+ expect(layout, hasLength(PaneLayoutStore.maxPanes));+ expect(layout.map((p) => p.agentId).toSet(), hasLength(layout.length));+ expect(layout.first.agentId, 'one');+ },+ );++ test(+ 'invalid or unreadable layouts return a usable first-run state',+ () async {+ final storage = _Store();+ final store = PaneLayoutStore(storage: storage);+ for (final raw in ['', 'broken', '{}']) {+ storage.values['terminal_pane_layout'] = raw;+ expect(await store.load(), isEmpty);+ }+ for (final raw in [+ 'broken',+ '[]',+ '{"version":2,"swarms":[]}',+ '{"version":1,"swarms":{}}',+ ]) {+ storage.values['swarm_layout_v1'] = raw;+ expect(await store.loadSwarms(), isNull);+ }+ storage.failReads = true;+ expect(await store.load(), isEmpty);+ expect(await store.loadSwarms(), isNull);+ },+ );++ test(+ 'rapid navigation saves the latest captured snapshot after a failed write',+ () async {+ final storage = _Store()..holdWrites = true;+ final store = PaneLayoutStore(storage: storage);+ final swarm = Swarm(id: 'one', name: 'initial');+ final first = store.saveSwarms([swarm], 'one');+ swarm.name = 'intermediate';+ final second = store.saveSwarms([swarm], 'one');+ swarm.name = 'latest';+ final last = store.saveSwarms([swarm], 'one');+ swarm.name = 'not yet saved';+ expect(storage.writes, hasLength(1));+ storage.holdWrites = false;+ storage.gates.single.completeError(StateError('disk unavailable'));+ await Future.wait([first, second, last, store.flushSwarms()]);+ expect(storage.writes, hasLength(2));+ expect(+ ((await store.loadSwarms())!['swarms'] as List).single['name'],+ 'latest',+ );+ await store.saveSwarms([swarm], 'one');+ await store.flushSwarms();+ expect(+ ((await store.loadSwarms())!['swarms'] as List).single['name'],+ 'not yet saved',+ );+ },+ );+}diff --git a/mobile/test/phone_chooser_test.dart b/mobile/test/phone_chooser_test.dartnew file mode 100644index 000000000..a2b9950ab--- /dev/null+++ b/mobile/test/phone_chooser_test.dart@@ -0,0 +1,112 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/new_agent_chooser.dart';+import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/phone/tty_controls.dart';++void main() {+ Future<void> open(WidgetTester tester, {int count = 3, int? fold}) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(390, 844);+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () => showNewAgentChooser<int>(+ context,+ title: 'Agent',+ hint: 'Search agents',+ fold: fold,+ items: [+ for (var i = 0; i < count; i++)+ ChooserItem(value: i, title: 'Agent $i'),+ ],+ ),+ child: const Text('Choose'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Choose'));+ await tester.pumpAndSettle();+ }++ testWidgets('short chooser fits its rows and can be pulled down', (+ tester,+ ) async {+ await open(tester);+ expect(tester.getSize(find.byType(BottomSheet)).height, lessThan(400));+ expect(+ tester.getTopLeft(find.text('Agent')).dx,+ tester.getTopLeft(find.text('Agent 0', findRichText: true)).dx,+ );+ await tester.drag(find.text('Agent'), const Offset(0, 500));+ await tester.pumpAndSettle();+ expect(find.byType(BottomSheet), findsNothing);+ });++ testWidgets('expanded long chooser scrolls to its last choice', (+ tester,+ ) async {+ await open(tester, count: 20, fold: 2);+ await tester.tap(find.text('more', findRichText: true));+ await tester.pumpAndSettle();+ await tester.scrollUntilVisible(+ find.text('Agent 19', findRichText: true),+ 250,+ scrollable: find.byType(Scrollable),+ );+ await tester.tap(find.text('Agent 19', findRichText: true));+ await tester.pumpAndSettle();+ expect(find.byType(BottomSheet), findsNothing);+ expect(tester.takeException(), isNull);+ });++ testWidgets('search choices remain above the keyboard', (tester) async {+ await open(tester, count: 20);+ tester.view.viewInsets = const FakeViewPadding(bottom: 300);+ await tester.enterText(find.byType(TextField), '19');+ await tester.pumpAndSettle();+ final choice = find.text('Agent 19', findRichText: true);+ expect(tester.getBottomLeft(choice).dy, lessThan(544));+ expect(tester.takeException(), isNull);+ await tester.tap(choice);+ await tester.pumpAndSettle();+ expect(find.byType(BottomSheet), findsNothing);+ });++ testWidgets('placeholder clears normal-text contrast on its field', (+ tester,+ ) async {+ final controller = TextEditingController();+ addTearDown(controller.dispose);+ late Color background;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Builder(+ builder: (context) {+ background = ttyRaised(Tty.of(context));+ return TtyField(+ controller: controller,+ hint: 'What should it do?',+ );+ },+ ),+ ),+ ),+ );+ final ink = tester+ .widget<TextField>(find.byType(TextField))+ .decoration!+ .hintStyle!+ .color!;+ final a = ink.computeLuminance();+ final b = background.computeLuminance();+ final contrast = ((a > b ? a : b) + .05) / ((a > b ? b : a) + .05);+ expect(contrast, greaterThanOrEqualTo(4.5));+ });+}diff --git a/mobile/test/phone_edge/welcome_behavior_test.dart b/mobile/test/phone_edge/welcome_behavior_test.dartindex e6bd82604..9a216cb1b 100644--- a/mobile/test/phone_edge/welcome_behavior_test.dart+++ b/mobile/test/phone_edge/welcome_behavior_test.dart@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/phone/new_agent_page.dart';+import 'package:harness_mobile/phone/tty_controls.dart';import 'package:harness_mobile/phone/phone_shell_scope.dart';import 'package:harness_mobile/phone/welcome/connect_code.dart';import 'package:harness_mobile/phone/welcome/connect_computer.dart';@@ -120,9 +121,13 @@ void main() {expect(find.text('Resend in 30s'), findsOneWidget);await tester.enterText(find.byType(TextField), '12');+ final signIn = tester.widget<TtyPrimaryButton>(+ find.byType(TtyPrimaryButton),+ );+ expect(signIn.onPressed, isNull, reason: 'two digits cannot sign in');await tester.tap(find.text('Sign in'));await frames(tester);- expect(find.textContaining('Enter the 4 digits'), findsOneWidget);+ expect(find.textContaining('Enter the 4 digits'), findsNothing);await tester.enterText(find.byType(TextField), '1234');await frames(tester);@@ -176,11 +181,11 @@ void main() {await close(tester, app);});- testWidgets('the sample, behind a long press, left to set up a computer', (+ testWidgets('the visible sample action leads back to setup', (tester,) async {final (:app, sent: _, scans: _) = await welcome(tester, sample: 'set-up');- await tester.longPress(find.byKey(const ValueKey('welcome-wordmark')));+ await tester.tap(find.text('Try the sample'));await frames(tester);expect(find.text('Get Harness for\nyour computer'), findsOneWidget);await close(tester, app);@@ -297,7 +302,7 @@ void main() {await frames(tester);expect(find.text('Apple Silicon'), findsOneWidget);expect(find.text('Email me the setup link'), findsNothing);- await tapInView(tester, find.text('Try the sample while you wait'));+ await tapInView(tester, find.text('Try the sample ›'));await frames(tester);expect(samples, 1);await close(tester, app);diff --git a/mobile/test/remote_media_download_test.dart b/mobile/test/remote_media_download_test.dartnew file mode 100644index 000000000..df2c9cd04--- /dev/null+++ b/mobile/test/remote_media_download_test.dart@@ -0,0 +1,174 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:math';+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/terminal/remote_media_download.dart';++void main() {+ late Directory cache;+ setUp(() => cache = Directory.systemTemp.createTempSync('phone-media-test-'));+ tearDown(() => cache.deleteSync(recursive: true));+ final revision = 'a' * 64;+ final bytes = Uint8List.fromList(+ List.generate(remoteMediaChunkBytes * 5 + 7, (i) => i % 251),+ );+ Map<String, dynamic> chunk(+ int offset, {+ String name = 'result.png',+ int? total,+ }) {+ final length = total ?? bytes.length;+ return {+ 'media': true,+ 'offset': offset,+ 'filename': name,+ 'totalBytes': length,+ 'revision': revision,+ 'contentBase64': base64Encode(+ bytes.sublist(offset, min(offset + remoteMediaChunkBytes, length)),+ ),+ };+ }++ Future<String> download(+ ReadRemoteMediaChunk read, {+ MediaDownloadCancellation? cancel,+ void Function(RemoteMediaProgress)? progress,+ }) => RemoteMediaDownloader(directory: cache).download(+ readChunk: read,+ cancellation: cancel ?? MediaDownloadCancellation(),+ onProgress: progress ?? (_) {},+ );++ test('parallel chunk replies are assembled in file order', () async {+ final progress = <RemoteMediaProgress>[];+ final revisions = <String?>[];+ final path = await download(({required offset, revision}) async {+ revisions.add(revision);+ await Future<void>.delayed(+ Duration(milliseconds: offset == remoteMediaChunkBytes ? 5 : 0),+ );+ return chunk(offset);+ }, progress: progress.add);+ expect(await File(path).readAsBytes(), bytes);+ expect(revisions.first, isNull);+ expect(revisions.skip(1), everyElement(revision));+ expect(progress.last.fraction, 1);+ expect(+ progress.map((p) => p.receivedBytes).toList(),+ orderedEquals([131072, 262144, 393216, 524288, 655360, 655367]),+ );+ expect(+ File('${File(path).parent.path}/download.part').existsSync(),+ isFalse,+ );+ });++ for (final broken in ['filename', 'offset', 'total', 'base64', 'short']) {+ test('refuses $broken metadata without leaving partial files', () async {+ final raw = chunk(0, total: 3);+ switch (broken) {+ case 'filename':+ raw['filename'] = '../private.png';+ case 'offset':+ raw['offset'] = 1;+ case 'total':+ raw['totalBytes'] = remoteMediaMaxBytes + 1;+ case 'base64':+ raw['contentBase64'] = '!!!!';+ case 'short':+ raw['contentBase64'] = '';+ }+ await expectLater(+ download(({required offset, revision}) async => raw),+ throwsA(isA<RemoteMediaException>()),+ );+ expect(cache.listSync(), isEmpty);+ });+ }++ test('changed revision removes the partial preview', () async {+ await expectLater(+ download(({required offset, revision}) async {+ final raw = chunk(offset);+ if (offset > 0) raw['revision'] = 'b' * 64;+ return raw;+ }),+ throwsA(isA<RemoteMediaException>()),+ );+ expect(cache.listSync(), isEmpty);+ });++ test(+ 'cancelled pending read finishes promptly and consumes late errors',+ () async {+ final cancel = MediaDownloadCancellation();+ final pending = Completer<Map<String, dynamic>>();+ final done = download(+ ({required offset, revision}) => pending.future,+ cancel: cancel,+ );+ final check = expectLater(done, throwsA(isA<RemoteMediaCancelled>()));+ cancel.cancel();+ cancel.cancel();+ await check;+ pending.completeError(StateError('late read failure'));+ await Future<void>.delayed(Duration.zero);+ expect(cache.listSync(), isEmpty);+ },+ );++ test('cancellation during a write cleans staging data', () async {+ final cancel = MediaDownloadCancellation();+ await expectLater(+ download(+ ({required offset, revision}) async => chunk(offset),+ cancel: cancel,+ progress: (_) => cancel.cancel(),+ ),+ throwsA(isA<RemoteMediaCancelled>()),+ );+ expect(cache.listSync(), isEmpty);+ });++ test('identical names from concurrent previews never overwrite', () async {+ final paths = await Future.wait([+ for (var i = 0; i < 2; i++)+ download(+ ({required offset, revision}) async => chunk(offset, total: 3),+ ),+ ]);+ expect(paths[0], isNot(paths[1]));+ expect(await File(paths[0]).readAsBytes(), bytes.sublist(0, 3));+ });++ test('cache symlink is refused without touching its target', () async {+ final target = Directory('${cache.path}/target')..createSync();+ final link = Link('${cache.path}/link')..createSync(target.path);+ await expectLater(+ RemoteMediaDownloader(directory: Directory(link.path)).download(+ readChunk: ({required offset, revision}) async =>+ chunk(offset, total: 3),+ cancellation: MediaDownloadCancellation(),+ onProgress: (_) {},+ ),+ throwsA(isA<RemoteMediaException>()),+ );+ expect(target.listSync(), isEmpty);+ });++ test(+ 'unsafe filename characters are sanitized in a completed preview',+ () async {+ final path = await download(+ ({required offset, revision}) async =>+ chunk(offset, name: 'a:b?.png', total: 3),+ );+ expect(path, endsWith('/a_b_.png'));+ expect(const RemoteMediaProgress('x', 0, null).fraction, isNull);+ },+ );+}diff --git a/mobile/test/render/phone_screens_render_test.dart b/mobile/test/render/phone_screens_render_test.dartindex acf7d3a98..b780848ca 100644--- a/mobile/test/render/phone_screens_render_test.dart+++ b/mobile/test/render/phone_screens_render_test.dart@@ -278,7 +278,9 @@ void main() {key.currentContext!.findRenderObject()! as RenderRepaintBoundary;final image = await boundary.toImage(pixelRatio: 3);final png = await image.toByteData(format: ui.ImageByteFormat.png);- await File('$_outDir/$name.png').writeAsBytes(png!.buffer.asUint8List());+ final file = File('$_outDir/$name.png');+ await file.parent.create(recursive: true);+ await file.writeAsBytes(png!.buffer.asUint8List());});// Done with the screen: take it down and run its clocks out, so no timer outlives the test.await tester.pumpWidget(const SizedBox());@@ -383,7 +385,11 @@ void main() {testWidgets('set up your computer', skip: skip, (tester) async {final key = await pumpScreen(tester,- ConnectComputerPage(notifier: notifier, onTrySample: (_) async => null),+ ConnectComputerPage(+ notifier: notifier,+ onTrySample: (_) async => null,+ loadDownloads: () async => const {},+ ),);await shoot(tester, key, '0d-connect-computer');});@@ -398,6 +404,7 @@ void main() {child: SetUpComputerPage(onScan: () {},onBack: () {},+ onTrySample: () {},loadDownloads: () async => const {},),),diff --git a/mobile/test/sample_mode_test.dart b/mobile/test/sample_mode_test.dartindex c0cfc9c1a..30924ae15 100644--- a/mobile/test/sample_mode_test.dart+++ b/mobile/test/sample_mode_test.dart@@ -45,7 +45,7 @@ void main() {await tester.tap(find.text('Try a sample'));await settle(tester, const Duration(seconds: 2));// It opens on its sessions to pick from, as a new phone does: the working one is picked.- expect(find.byKey(const ValueKey('pick-up-title')), findsOneWidget);+ expect(find.text('Try a sample\nharness'), findsOneWidget);await tester.tap(find.text('fix-login', findRichText: true).first);await settle(tester, const Duration(seconds: 2));return tester.widget<PhoneShell>(find.byType(PhoneShell)).notifier;@@ -93,7 +93,16 @@ void main() {reason: 'the terminal shows the session so far',);expect(notifier.agentIsProcessing(_studio, 'sample-fix-login'), isTrue);+ expect(find.text('Sample'), findsOneWidget);+ final dot = find.byKey(const ValueKey('sample-guide-dot'));+ final dotBefore = tester.getRect(dot);+ expect(dotBefore.left, 12);await settle(tester, const Duration(seconds: 6));+ expect(+ tester.getRect(dot),+ dotBefore,+ reason: 'attention cue must not drift',+ );expect(screenOf(notifier, 'sample-fix-login'),contains('ensureSession'),diff --git a/mobile/test/sample_runtime_test.dart b/mobile/test/sample_runtime_test.dartnew file mode 100644index 000000000..c16990449--- /dev/null+++ b/mobile/test/sample_runtime_test.dart@@ -0,0 +1,183 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/demo/sample_runtime.dart';+import 'package:harness_mobile/ws/ws_conn.dart';++void main() {+ late SampleRuntime runtime;+ late SampleConnection connection;+ setUp(() {+ runtime = SampleRuntime();+ connection = runtime.connectionFor('sample-studio');+ });+ tearDown(() => runtime.dispose());++ test('sample folders and git metadata come from fixtures', () async {+ final home = await connection.request(+ 'fs_list_dir',+ payload: {'path': '.'},+ );+ expect(home['path'], '~');+ expect(home['entries'], contains(equals({'name': 'code', 'isDir': true})));+ final folder = await connection.request(+ 'fs_list_dir',+ payload: {'path': ' ~/code/api/ '},+ );+ expect(folder['path'], '~/code/api');+ expect(+ folder['entries'],+ contains(equals({'name': 'tests', 'isDir': true})),+ );+ final empty = await connection.request(+ 'fs_list_dir',+ payload: {'path': '~/code/unlisted'},+ );+ expect(empty['entries'], isEmpty);+ expect(+ (await connection.request(+ 'git_project_info',+ payload: {'path': '~/code/scratch'},+ ))['isGit'],+ isFalse,+ );+ final repo = await connection.request(+ 'git_project_info',+ payload: {'path': '~/code/api'},+ );+ expect(repo['isGit'], isTrue);+ expect(repo['defaultRef'], 'refs/remotes/origin/main');+ });++ test(+ 'creation status, rename, and deletion follow the sample harness',+ () async {+ final result = await connection.request(+ 'agent_create',+ payload: {+ 'creationId': 'creation-one',+ 'engine': 'codex',+ 'repositoryUrl': 'https://example.invalid/team/project.git',+ 'branchRef': 'refs/remotes/origin/feature',+ },+ );+ final agent = result['agent'] as Map;+ final id = agent['id'] as String;+ expect(agent['engine'], 'codex');+ expect((agent['project'] as Map)['cwd'], '~/code/project');+ expect(+ (await connection.request(+ 'agent_create_status',+ payload: {'creationId': 'creation-one'},+ ))['agent'],+ agent,+ );+ expect(+ (await connection.request(+ 'agent_create_status',+ payload: {'creationId': 'unknown'},+ ))['state'],+ 'missing',+ );+ await connection.request(+ 'agent_update',+ payload: {'agentId': id, 'name': ' renamed ', 'opened': true},+ );+ final renamed = runtime.harnessOf('sample-studio', id)!;+ expect(renamed.agent['name'], 'renamed');+ expect(+ DateTime.tryParse(renamed.agent['lastOpenedAt'] as String),+ isNotNull,+ );+ await connection.request(+ 'agent_update',+ payload: {'agentId': id, 'name': ' '},+ );+ expect(renamed.agent['name'], 'renamed');+ final recent = await connection.request(+ 'agent_recent',+ payload: {'agentId': id},+ );+ expect(recent['asks'], isEmpty);+ await connection.request('agent_delete', payload: {'agentId': id});+ expect(runtime.harnessOf('sample-studio', id), isNull);+ final listed =+ (await connection.request('agents_list'))['agents'] as List;+ expect(listed.where((agent) => agent['id'] == id), isEmpty);+ },+ );++ test(+ 'sample creation honors explicit folders and validates engines',+ () async {+ for (final payload in <Map<String, dynamic>>[+ {'cwd': ' ~/code/chosen ', 'gitSource': '~/code/ignored'},+ {'gitSource': '~/code/chosen'},+ {},+ ]) {+ final result = await connection.request(+ 'agent_create',+ payload: payload,+ );+ final cwd = ((result['agent'] as Map)['project'] as Map)['cwd'];+ expect(+ cwd,+ payload.isEmpty ? startsWith('~/code/new-project-') : '~/code/chosen',+ );+ }+ await expectLater(+ connection.request('agent_create', payload: {'engine': 'missing'}),+ throwsA(+ isA<WsRequestFailure>().having(+ (e) => e.code,+ 'code',+ 'INVALID_ENGINE',+ ),+ ),+ );+ final probe = await connection.request(+ 'engines_probe',+ payload: {+ 'engines': ['codex', 'missing'],+ },+ );+ expect((probe['engines'] as List).map((e) => e['installed']), [+ true,+ false,+ ]);+ },+ );++ test('missing harnesses and unsupported requests fail explicitly', () async {+ await expectLater(+ connection.request('agent_recent', payload: {'agentId': 'gone'}),+ throwsA(+ isA<WsRequestFailure>().having(+ (e) => e.code,+ 'code',+ 'AGENT_NOT_FOUND',+ ),+ ),+ );+ await expectLater(+ connection.request('not_a_sample_method'),+ throwsA(+ isA<WsRequestFailure>().having((e) => e.code, 'code', 'UNSUPPORTED'),+ ),+ );+ });++ test('leaving sample mode cancels timers and refuses later input', () async {+ var fired = false;+ runtime.schedule(Duration.zero, () => fired = true);+ runtime.dispose();+ final after = runtime.schedule(Duration.zero, () => fired = true);+ expect(after.isActive, isFalse);+ expect(connection.isReady, isFalse);+ expect(await connection.sendTerminalFrame('terminal_open', {}), isFalse);+ await expectLater(+ connection.request('agents_list'),+ throwsA(isA<WsRequestFailure>().having((e) => e.code, 'code', 'CLOSED')),+ );+ await Future<void>.delayed(Duration.zero);+ expect(fired, isFalse);+ });+}diff --git a/mobile/test/settings/config_store_test.dart b/mobile/test/settings/config_store_test.dartindex 29ed5a128..c816d6150 100644--- a/mobile/test/settings/config_store_test.dart+++ b/mobile/test/settings/config_store_test.dart@@ -5,9 +5,7 @@ import 'package:harness_mobile/settings/config_store.dart';/// The connection settings the phone reads once, at the top of every launch/// (`AppNotifier.bootstrap`), before it knows which backend to sign in to.///-/// Only the read is the phone's: the writes behind it (a base URL, the staging-/// switch, a skipped desktop update) have no screen on a phone, and are left to-/// the desktop's own suite.+/// Persistence and reset contracts are exercised against an isolated in-memory store.void main() {test('before anything is read it points at production', () {// Touches the shared file store's constructor only — no read, no IO.@@ -39,6 +37,34 @@ void main() {expect(storage.reads, 0);});+ test('saved connection choices survive a fresh store', () async {+ final storage = _Store({});+ final store = ConfigStore(storage: storage);+ await store.save('https://private-backend.example');+ await store.saveEnvironment('stag');+ final restored = await ConfigStore(storage: storage).load();+ expect(restored.apiBaseUrl, 'https://private-backend.example');+ expect(restored.autonomousEnv, 'stag');+ await store.saveEnvironment('unknown');+ expect((await ConfigStore(storage: storage).load()).autonomousEnv, 'prod');+ });++ test('reset removes connection and legacy settings, preserving other preferences', () async {+ final storage = _Store({+ 'terminal_font_size': '18',+ 'app_api_base_url': 'https://staging.example',+ 'app_autonomous_environment': 'stag',+ 'skipped_desktop_update_version': 'old',+ 'environment_setup_version': 'old',+ });+ final store = ConfigStore(storage: storage);+ await store.load();+ await store.reset();+ expect(storage.values, {'terminal_font_size': '18'});+ expect(store.config.apiBaseUrl, ConfigStore.defaultBaseUrl);+ expect(store.config.autonomousEnv, 'prod');+ });+test('an environment that is not staging is production', () async {final store = ConfigStore(storage: _Store({'app_autonomous_environment': 'Stag '}),diff --git a/mobile/test/terminal_link_opener_test.dart b/mobile/test/terminal_link_opener_test.dartnew file mode 100644index 000000000..e135fa810--- /dev/null+++ b/mobile/test/terminal_link_opener_test.dart@@ -0,0 +1,135 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/terminal/remote_media_download.dart';+import 'package:harness_mobile/terminal/terminal_link_opener.dart';++void main() {+ test('web links launch directly without downloading a file', () async {+ final launched = <Uri>[];+ final opener = TerminalLinkOpener(+ launch: (uri) async {+ launched.add(uri);+ return true;+ },+ );+ expect(await opener.open('https://example.invalid/report?q=one'), isNull);+ expect(launched.single, Uri.parse('https://example.invalid/report?q=one'));+ });++ test(+ 'a terminal file is downloaded from its computer before opening',+ () async {+ final launched = <Uri>[];+ final requested = <String>[];+ final opener = TerminalLinkOpener(+ launch: (uri) async {+ launched.add(uri);+ return true;+ },+ fileExists: (_) async => true,+ windows: false,+ );+ expect(+ await opener.open(+ '~/project/preview.png',+ downloadRemote: (target) async {+ requested.add(target);+ return '/sample-cache/preview.png';+ },+ ),+ isNull,+ );+ expect(requested, ['~/project/preview.png']);+ expect(launched.single, Uri.file('/sample-cache/preview.png'));+ },+ );++ test('unsupported targets never launch or request a download', () async {+ final opener = TerminalLinkOpener(+ launch: (_) async => fail('unsupported link launched'),+ );+ for (final target in [+ 'javascript:alert(1)',+ 'https:',+ 'file://other-machine/image.png',+ '/project/credentials.txt',+ 'image.png\ncommand',+ ]) {+ expect(+ await opener.open(+ target,+ downloadRemote: (_) async => fail('unsupported file downloaded'),+ ),+ isNotNull,+ );+ }+ });++ test(+ 'missing download support or an expired preview explains the failure',+ () async {+ final opener = TerminalLinkOpener(+ launch: (_) async => fail('missing file launched'),+ fileExists: (_) async => false,+ );+ expect(+ await opener.open('/project/image.png'),+ contains('download a preview'),+ );+ expect(+ await opener.open(+ '/project/image.png',+ downloadRemote: (_) async => '/sample-cache/gone.png',+ ),+ contains('no longer available'),+ );+ },+ );++ test('a cancelled download stays silent and never launches', () async {+ var cancelled = false;+ final opener = TerminalLinkOpener(+ launch: (_) async => fail('cancelled preview launched'),+ );+ expect(+ await opener.open(+ '/project/image.png',+ isCancelled: () => cancelled,+ downloadRemote: (_) async {+ cancelled = true;+ return '/sample-cache/image.png';+ },+ ),+ isNull,+ );+ expect(+ await opener.open(+ '/project/image.png',+ downloadRemote: (_) async => throw const RemoteMediaCancelled(),+ ),+ isNull,+ );+ });++ test('download and launcher failures become readable messages', () async {+ final opener = TerminalLinkOpener(launch: (_) async => false);+ expect(+ await opener.open('https://example.invalid'),+ contains('Could not open'),+ );+ expect(+ await opener.open(+ '/project/image.png',+ downloadRemote: (_) async =>+ throw const RemoteMediaException('Preview too large.'),+ ),+ 'Preview too large.',+ );+ final throwing = TerminalLinkOpener(+ launch: (_) async => throw StateError('launcher unavailable'),+ );+ expect(+ await throwing.open('https://example.invalid'),+ contains('Could not open'),+ );+ });+}diff --git a/mobile/test/terminal_preferences_test.dart b/mobile/test/terminal_preferences_test.dartnew file mode 100644index 000000000..669d7e6af--- /dev/null+++ b/mobile/test/terminal_preferences_test.dart@@ -0,0 +1,140 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/terminal/terminal_font_store.dart';+import 'package:harness_mobile/terminal/terminal_theme_store.dart';+import 'package:harness_mobile/terminal/terminal_typography.dart';++class _Store implements LocalKeyValueStore {+ final values = <String, String>{};+ bool fail = false;+ int writes = 0;++ @override+ Future<String?> read(String key) async {+ if (fail) throw StateError('storage unavailable');+ return values[key];+ }++ @override+ Future<void> write(String key, String value) async {+ writes++;+ if (fail) throw StateError('storage unavailable');+ values[key] = value;+ }++ @override+ Future<void> delete(String key) async => values.remove(key);+}++void main() {+ test(+ 'font choices persist, reset, and leave unrelated preferences alone',+ () async {+ final storage = _Store()..values['unrelated'] = 'kept';+ final font = TerminalFontStore(storage: storage);+ addTearDown(font.dispose);+ await font.setFamily(TerminalFontChoice.courierNew);+ await font.setSize(18);+ final restored = TerminalFontStore(storage: storage);+ addTearDown(restored.dispose);+ await restored.load();+ expect(restored.family, TerminalFontChoice.courierNew);+ expect(restored.size, 18);+ expect(restored.isDefault, isFalse);+ await restored.reset();+ await font.load();+ expect(font.isDefault, isTrue);+ expect(storage.values['unrelated'], 'kept');+ },+ );++ test(+ 'font bounds make further stepper taps silent, without another write',+ () async {+ final storage = _Store();+ final font = TerminalFontStore(storage: storage);+ addTearDown(font.dispose);+ var notifications = 0;+ font.addListener(() => notifications++);+ await font.setSize(100);+ expect(font.size, TerminalFontStore.maxSize);+ final largest = font.value;+ final writes = storage.writes;+ await font.increaseSize();+ expect(font.value, same(largest));+ expect(storage.writes, writes);+ expect(notifications, 1);+ await font.setSize(-1);+ await font.decreaseSize();+ expect(font.size, TerminalFontStore.minSize);+ expect(notifications, 2);+ await font.setSize(100);+ expect(+ font.value,+ same(largest),+ reason: 'returning to a style reuses its render identity',+ );+ },+ );++ test('unknown or unreadable saved typography falls back safely', () async {+ final storage = _Store()+ ..values.addAll({+ 'terminal_font_family': 'removed-font',+ 'terminal_font_size': 'corrupt',+ });+ final font = TerminalFontStore(storage: storage);+ addTearDown(font.dispose);+ await font.load();+ expect(font.isDefault, isTrue);+ storage.values['terminal_font_size'] = '1000';+ await font.load();+ expect(font.size, TerminalFontStore.maxSize);+ storage.fail = true;+ await font.load();+ expect(font.size, terminalFontSize);+ expect(font.isDefault, isTrue);+ await font.setSize(19);+ expect(+ font.size,+ 19,+ reason: 'a failed save keeps the choice for this run',+ );+ });++ test(+ 'terminal colors persist and reset without notifying on a no-op',+ () async {+ final storage = _Store();+ final theme = TerminalThemeStore(storage: storage);+ addTearDown(theme.dispose);+ var notifications = 0;+ theme.addListener(() => notifications++);+ await theme.set(TerminalThemeChoice.tango);+ await theme.set(TerminalThemeChoice.tango);+ expect(notifications, 1);+ expect(storage.writes, 1);+ final restored = TerminalThemeStore(storage: storage);+ addTearDown(restored.dispose);+ await restored.load();+ expect(restored.value, TerminalThemeChoice.tango);+ expect(restored.isDefault, isFalse);+ await restored.reset();+ await theme.load();+ expect(theme.isDefault, isTrue);+ },+ );++ test('unknown colors and storage failures keep a usable theme', () async {+ final storage = _Store()..values['terminal_theme'] = 'removed-theme';+ final theme = TerminalThemeStore(storage: storage);+ addTearDown(theme.dispose);+ await theme.load();+ expect(theme.isDefault, isTrue);+ storage.fail = true;+ await theme.set(TerminalThemeChoice.tango);+ expect(theme.value, TerminalThemeChoice.tango);+ await theme.load();+ expect(theme.isDefault, isTrue);+ });+}diff --git a/mobile/test/terminal_session_protocol_test.dart b/mobile/test/terminal_session_protocol_test.dartindex 61076410d..8b0335885 100644--- a/mobile/test/terminal_session_protocol_test.dart+++ b/mobile/test/terminal_session_protocol_test.dart@@ -1015,7 +1015,7 @@ void main() {s.attachViewport(viewport);s.clearPrompt();- await Future<void>.delayed(const Duration(milliseconds: 10));+ await until(() => _typed(wire).length == 2);expect(_typed(wire), '\x05\x15');expect(viewport.cleared, 1);diff --git a/mobile/test/unlock_by_scan_test.dart b/mobile/test/unlock_by_scan_test.dartindex f0b24248d..675434ba4 100644--- a/mobile/test/unlock_by_scan_test.dart+++ b/mobile/test/unlock_by_scan_test.dart@@ -102,7 +102,7 @@ void main() {final links = _Links(const CliLinkConnectResult(linkedMachineId: 'studio'));final (_, unlocked) = await pump(tester, links);expect(find.text('Scan its code'), findsOneWidget);- expect(find.text('or enter its phone password'), findsOneWidget);+ expect(find.text('or enter its Harness phone password'), findsOneWidget);await scan(tester,diff --git a/mobile/test/ws/fake_relay.dart b/mobile/test/ws/fake_relay.dartindex 305c82169..2b6628ffb 100644--- a/mobile/test/ws/fake_relay.dart+++ b/mobile/test/ws/fake_relay.dart@@ -1,17 +1,17 @@import 'dart:async';import 'dart:convert';-import 'dart:io';import 'dart:typed_data';import 'package:harness_mobile/e2ee/keys.dart';import '../e2ee/machine_session.dart';+import 'memory_web_socket.dart';/// One socket a phone opened to the [FakeRelay], and the machine behind it.class RelayLink {RelayLink(this.ws, this.protocol);- final WebSocket ws;+ final MemoryWebSocket ws;final String protocol;/// Every JSON frame the phone sent on this socket, as sent (sealed payloads stay sealed).@@ -27,15 +27,15 @@ class RelayLink {/// nothing to anyone.void send(Map<String, dynamic> frame) {try {- ws.add(jsonEncode(frame));+ ws.sink.add(jsonEncode(frame));} on StateError {// Already hung up.}}- void sendText(String text) => ws.add(text);+ void sendText(String text) => ws.sink.add(text);- void sendBytes(List<int> bytes) => ws.add(bytes);+ void sendBytes(List<int> bytes) => ws.sink.add(bytes);Future<void> close([int? code, String? reason]) => ws.close(code, reason);@@ -47,13 +47,11 @@ class RelayLink {];}-/// A relay on loopback — nothing leaves the process — with the machine at the far end of it+/// An in-memory relay with no network access — with the machine at the far end of it/// played the way `manager.ts` plays it: `connected` for the select, a signed welcome for the/// hello. Each hook lets a test replace one step with something broken or hostile.class FakeRelay {- FakeRelay._(this.server, this.machineIdentity);-- final HttpServer server;+ FakeRelay._(this.machineIdentity);final E2eeIdentity machineIdentity;final links = <RelayLink>[];int get opened => links.length;@@ -89,13 +87,17 @@ class FakeRelay {/// The next socket whose session the machine has welcomed.Future<RelayLink> nextSession() => _ready.stream.first;- String get url => 'ws://127.0.0.1:${server.port}';+ String get url => 'ws://relay.invalid';++ static Future<FakeRelay> start(E2eeIdentity machineIdentity) async =>+ FakeRelay._(machineIdentity);- static Future<FakeRelay> start(E2eeIdentity machineIdentity) async {- final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);- final relay = FakeRelay._(server, machineIdentity);- server.listen(relay._serve);- return relay;+ MemoryWebSocket connect(Uri uri, {Iterable<String>? protocols}) {+ final (client, server) = MemoryWebSocket.pair(+ protocol: protocols?.firstOrNull,+ );+ unawaited(_serve(client, server));+ return client;}/// When set, a dial waits here before its upgrade is answered — a slow network's handshake.@@ -104,25 +106,20 @@ class FakeRelay {/// Completes when a dial has reached the relay (and is being held, if [holdUpgrade] is set).final dialled = StreamController<void>.broadcast();- Future<void> _serve(HttpRequest request) async {+ Future<void> _serve(MemoryWebSocket client, MemoryWebSocket server) async {dialled.add(null);final hold = holdUpgrade;if (hold != null) await hold.future;- if (refuse || !WebSocketTransformer.isUpgradeRequest(request)) {- request.response.statusCode = 404;- await request.response.close();+ if (refuse) {+ client.reject();+ await client.close();return;}- final protocol = request.headers.value('sec-websocket-protocol') ?? '';- final ws = await WebSocketTransformer.upgrade(- request,- protocolSelector: (protocols) =>- protocols.isNotEmpty ? protocols.first : null,- );- final link = RelayLink(ws, protocol);+ client.accept();+ final link = RelayLink(server, server.protocol ?? '');links.add(link);_linked.add(link);- ws.listen(+ server.stream.listen((data) => unawaited(_receive(link, data)),onError: (_) {},cancelOnError: false,@@ -178,6 +175,8 @@ class FakeRelay {for (final link in links) {await link.ws.close();}- await server.close(force: true);+ await _linked.close();+ await _ready.close();+ await dialled.close();}}diff --git a/mobile/test/ws/memory_web_socket.dart b/mobile/test/ws/memory_web_socket.dartnew file mode 100644index 000000000..32cdf73c4--- /dev/null+++ b/mobile/test/ws/memory_web_socket.dart@@ -0,0 +1,89 @@+import 'dart:async';++import 'package:web_socket_channel/web_socket_channel.dart';++/// Two asynchronous endpoints, including handshake and close metadata, with no sockets.+class MemoryWebSocket implements WebSocketChannel {+ MemoryWebSocket._(this.protocol);++ static (MemoryWebSocket, MemoryWebSocket) pair({String? protocol}) {+ final client = MemoryWebSocket._(protocol);+ final server = MemoryWebSocket._(protocol);+ client._peer = server;+ server._peer = client;+ server.accept();+ return (client, server);+ }++ final _incoming = StreamController<dynamic>();+ final _ready = Completer<void>();+ final _done = Completer<void>();+ late final MemoryWebSocket _peer;+ bool _closed = false;++ @override+ final String? protocol;+ @override+ int? closeCode;+ @override+ String? closeReason;+ @override+ Future<void> get ready => _ready.future;+ @override+ Stream<dynamic> get stream => _incoming.stream;+ @override+ late final WebSocketSink sink = _Sink(this);++ void accept() {+ if (!_ready.isCompleted) _ready.complete();+ }++ void reject() {+ if (!_ready.isCompleted) {+ _ready.completeError(WebSocketChannelException('upgrade refused'));+ }+ }++ Future<void> close([int? code, String? reason]) async {+ for (final endpoint in [this, _peer]) {+ if (endpoint._closed) continue;+ endpoint._closed = true;+ endpoint.closeCode = code;+ endpoint.closeReason = reason;+ unawaited(endpoint._incoming.close());+ endpoint._done.complete();+ }+ }++ @override+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);+}++class _Sink implements WebSocketSink {+ _Sink(this.channel);+ final MemoryWebSocket channel;++ @override+ void add(dynamic data) {+ if (channel._closed) throw StateError('channel closed');+ channel._peer._incoming.add(data);+ }++ @override+ void addError(Object error, [StackTrace? stackTrace]) =>+ channel._peer._incoming.addError(error, stackTrace);++ @override+ Future<void> addStream(Stream<dynamic> stream) async {+ await for (final event in stream) {+ add(event);+ }+ }++ @override+ Future<void> close([int? closeCode, String? closeReason]) =>+ channel.close(closeCode, closeReason);++ @override+ Future<void> get done => channel._done.future;+}diff --git a/mobile/test/ws/ws_conn_plugin_test.dart b/mobile/test/ws/ws_conn_plugin_test.dartindex e8a977065..9264fea40 100644--- a/mobile/test/ws/ws_conn_plugin_test.dart+++ b/mobile/test/ws/ws_conn_plugin_test.dart@@ -123,6 +123,7 @@ void main() {WsConn newConn({RelayCodecFactory? relayCodecs}) {final conn = WsConn(wsBaseUrl: relay.url,+ connectChannel: relay.connect,autonomousEnv: 'test',machineId: machineId,accessTokenProvider: (_, _) async => 'token',diff --git a/mobile/test/ws/ws_conn_relay_test.dart b/mobile/test/ws/ws_conn_relay_test.dartindex a2e58464e..bc707caad 100644--- a/mobile/test/ws/ws_conn_relay_test.dart+++ b/mobile/test/ws/ws_conn_relay_test.dart@@ -17,7 +17,7 @@ import 'package:harness_mobile/ws/ws_conn.dart';import '../e2ee/machine_session.dart';import 'fake_relay.dart';-/// A phone's relay connection end to end, against a loopback relay with the machine behind it:+/// A phone's relay connection end to end, against an in-memory relay with the machine behind it:/// the dial, the E2EE handshake, requests and events through the session — and the ways each of/// those goes wrong on a phone.void main() {@@ -58,6 +58,7 @@ void main() {events = [];final conn = WsConn(wsBaseUrl: relay.url,+ connectChannel: relay.connect,autonomousEnv: 'test',machineId: machineId,accessTokenProvider: tokens ?? (_, _) async => 'token',@@ -110,7 +111,6 @@ void main() {ConnectionStatus.connected,]);expect(conn.endpointKey, 'cloud:${relay.url}:test');- expect(conn.isLocal, isFalse);},);diff --git a/mobile/test/ws/ws_pool_test.dart b/mobile/test/ws/ws_pool_test.dartindex f8d182df4..0ad9c09cb 100644--- a/mobile/test/ws/ws_pool_test.dart+++ b/mobile/test/ws/ws_pool_test.dart@@ -3,9 +3,10 @@ import 'dart:async';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/core/models.dart';-import 'package:harness_mobile/ws/ws_conn.dart';import 'package:harness_mobile/ws/ws_pool.dart';+import 'memory_web_socket.dart';+/// One connection per machine, and who may speak for that machine.void main() {late List<String> events;@@ -15,6 +16,12 @@ void main() {events = [];pool = WsPool(wsBaseUrl: 'ws://fixture.invalid',+ connectChannel: (_, {protocols}) {+ final (client, server) = MemoryWebSocket.pair();+ server.stream.listen((_) {});+ client.accept();+ return client;+ },autonomousEnv: 'test',// Never resolves: nothing is ever dialled.accessTokenProvider: (_, _) => Completer<String>().future,@@ -108,17 +115,4 @@ void main() {pool.reconnectAll();expect(a.isClosed || b.isClosed, isFalse);});-- test('a local connection keys on its loopback address', () {- final conn = pool.connFor(- 'm',- transportKind: WsTransportKind.localPlaintext,- localWsUri: Uri.parse('ws://127.0.0.1:1/ws'),- );- expect(conn.endpointKey, 'local:ws://127.0.0.1:1/ws');- expect(conn.isLocal, isTrue);- // A different transport for the same machine replaces it.- final cloud = pool.connFor('m');- expect(cloud, isNot(same(conn)));- });}diff --git a/mobile/test/ws_resume_test.dart b/mobile/test/ws_resume_test.dartindex cccc70f7f..62c767fe0 100644--- a/mobile/test/ws_resume_test.dart+++ b/mobile/test/ws_resume_test.dart@@ -1,4 +1,6 @@-import 'dart:io';+import 'dart:async';++import 'ws/memory_web_socket.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/core/models.dart';@@ -10,46 +12,33 @@ import 'package:harness_mobile/ws/ws_conn.dart';/// these tests reproduce is the shape of that loss, not its cause: the wire goes away, and the app/// finds out by being unable to use it.class _Hub {- _Hub._(this.server);-- final HttpServer server;- final List<WebSocket> live = [];+ final List<MemoryWebSocket> live = [];int opened = 0;-- /// Answers every dial with a 404 rather than an upgrade — a dial that fails.bool refuse = false;-- /// Closes the next socket opened with this code the moment it opens.int? closeNextWith;- int get port => server.port;-- static Future<_Hub> start() async {- final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);- final hub = _Hub._(server);- server.listen((request) async {- if (hub.refuse || !WebSocketTransformer.isUpgradeRequest(request)) {- request.response.statusCode = 404;- await request.response.close();- return;- }- final ws = await WebSocketTransformer.upgrade(- request,- protocolSelector: (protocols) =>- protocols.isNotEmpty ? protocols.first : null,- );- hub.opened++;- final closeWith = hub.closeNextWith;- if (closeWith != null) {- hub.closeNextWith = null;- await ws.close(closeWith);- return;- }- hub.live.add(ws);- // Whatever the client says, this hub only counts connections.- ws.listen((_) {}, onDone: () => hub.live.remove(ws));- });- return hub;+ static Future<_Hub> start() async => _Hub();++ MemoryWebSocket connect(Uri uri, {Iterable<String>? protocols}) {+ final (client, server) = MemoryWebSocket.pair(+ protocol: protocols?.firstOrNull,+ );+ if (refuse) {+ client.reject();+ unawaited(client.close());+ return client;+ }+ client.accept();+ opened++;+ final closeWith = closeNextWith;+ if (closeWith != null) {+ closeNextWith = null;+ unawaited(server.close(closeWith));+ return client;+ }+ live.add(server);+ server.stream.listen((_) {}, onDone: () => live.remove(server));+ return client;}Future<void> dropAll() async {@@ -60,7 +49,7 @@ class _Hub {}}- Future<void> stop() async => server.close(force: true);+ Future<void> stop() => dropAll();}void main() {@@ -77,7 +66,8 @@ void main() {tearDown(() async => hub.stop());WsConn newConn({AccessTokenProvider? tokens}) => WsConn(- wsBaseUrl: 'ws://127.0.0.1:${hub.port}',+ wsBaseUrl: 'ws://hub.invalid',+ connectChannel: hub.connect,autonomousEnv: 'test',machineId: 'm',accessTokenProvider: tokens ?? (_, _) async => 'token',