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
Make the mobile app a standalone package
Dev jacob32f348731e20
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dartindex 504bc7222..ea3326ddd 100644--- a/desktop/lib/app_shell.dart+++ b/desktop/lib/app_shell.dart@@ -37,10 +37,11 @@ typedef AuthenticatedScreenBuilder = Widget Function(AppNotifier app);/// crash log, the keyboard config, the saved appearance, and the native window/// where there is one.///-/// Lives here rather than in either `main.dart` so the two cannot drift — the-/// mobile app is a separate package (`../mobile`) that depends on this one, and-/// a second copy of this preamble is exactly how the last mobile build ended up-/// stranded from the desktop it shared a codebase with.+/// Lives here rather than in `main.dart` so every screen up to sign-in has one+/// definition of what precedes it. `../mobile` carries its own vendored copy of+/// this file — it depended on this package until it was made standalone — so a+/// change here that belongs on the phone too has to be carried across; the two+/// trees are otherwise byte-identical outside `lib/phone/` and `lib/p2p/`.Future<void> startHarness({required AuthenticatedScreenBuilder authenticatedScreen,/// A viewer build's second wire to each machine (seediff --git a/desktop/lib/core/asset_owner.dart b/desktop/lib/core/asset_owner.dartdeleted file mode 100644index b24965d6a..000000000--- a/desktop/lib/core/asset_owner.dart+++ /dev/null@@ -1,12 +0,0 @@-/// The package Flutter should look in for this app's bundled assets.-///-/// `null` in the desktop app, where `harness` IS the root package and-/// `Image.asset('assets/…')` resolves against its own manifest. An app that-/// DEPENDS on `harness` — `../mobile` — gets those same files registered under-/// `packages/harness/assets/…` instead, which only `package:` reaches.-///-/// Set once, from that app's `main()`, before the first frame. A mutable global-/// rather than a `--dart-define` on purpose: a flag that has to be passed on-/// every `flutter run` and `flutter build` is a flag someone will forget, and-/// the symptom — every icon silently missing — looks nothing like its cause.-String? harnessAssetPackage;diff --git a/desktop/lib/main.dart b/desktop/lib/main.dartindex 52fafc422..3ad85258f 100644--- a/desktop/lib/main.dart+++ b/desktop/lib/main.dart@@ -4,8 +4,8 @@ import 'screens/swarm_screen.dart';/// Harness for macOS, Linux and Windows: a swarm of terminal panes in one/// window. Everything before the first frame, and every screen up to sign-in,-/// is [startHarness] — shared with `../mobile`, which mounts a phone shell here-/// instead.+/// is [startHarness]. `../mobile` mounts a phone shell into its own vendored+/// copy of that function rather than depending on this package.Future<void> main() => startHarness(authenticatedScreen: (app) => SwarmScreen(notifier: app),);diff --git a/desktop/lib/screens/login_screen.dart b/desktop/lib/screens/login_screen.dartindex b1862ea86..b0962c85c 100644--- a/desktop/lib/screens/login_screen.dart+++ b/desktop/lib/screens/login_screen.dart@@ -1,7 +1,6 @@import 'package:flutter/material.dart';import 'package:flutter/services.dart';-import '../core/asset_owner.dart';import '../shared/theme/app_theme.dart' as grid;import '../state/app_state.dart';@@ -412,7 +411,6 @@ class _AppMark extends StatelessWidget {// No ClipRRect: the asset carries its own rounded corners, and clipping// would cut the edge twice. Same reason About renders it bare.child: Image.asset(- package: harnessAssetPackage,'assets/app_icon.png',width: 36,height: 36,diff --git a/desktop/lib/settings/sections/about_section.dart b/desktop/lib/settings/sections/about_section.dartindex 75e6a5d2b..1546b53de 100644--- a/desktop/lib/settings/sections/about_section.dart+++ b/desktop/lib/settings/sections/about_section.dart@@ -1,6 +1,5 @@import 'package:flutter/material.dart';-import '../../core/asset_owner.dart';import '../../core/app_version.dart';import '../../core/build_identity.dart';@@ -163,7 +162,6 @@ class _Identity extends StatelessWidget {// The icon is already rounded with transparent corners, so it needs no// clip of its own — one would only cut its edge twice.Image.asset(- package: harnessAssetPackage,'assets/app_icon.png',width: 46,height: 46,diff --git a/desktop/lib/viewer/viewer_services.dart b/desktop/lib/viewer/viewer_services.dartindex fec09acd3..d99814709 100644--- a/desktop/lib/viewer/viewer_services.dart+++ b/desktop/lib/viewer/viewer_services.dart@@ -11,9 +11,9 @@ import 'viewer_key_store.dart';/// The second wire a viewer build offers its relay connections — the phone's WebRTC/// data channel to the machine. Set once, from that app's `main()` through-/// `startHarness`, before the first frame; a mutable global for the same reason-/// `harnessAssetPackage` is one. Null — the desktop, or a viewer without one —-/// leaves every terminal frame on the relay socket.+/// `startHarness`, before the first frame; a mutable global because its one+/// writer runs before any widget tree exists to carry it. Null — the desktop, or+/// a viewer without one — leaves every terminal frame on the relay socket.TerminalTransportPluginFactory? harnessTransportPlugins;/// Everything a viewer build uses in place of the harness CLI, built once and handed todiff --git a/desktop/lib/widgets/bootstrapping_screen.dart b/desktop/lib/widgets/bootstrapping_screen.dartindex 170393132..4ad5311d7 100644--- a/desktop/lib/widgets/bootstrapping_screen.dart+++ b/desktop/lib/widgets/bootstrapping_screen.dart@@ -1,6 +1,5 @@import 'package:flutter/material.dart';-import '../core/asset_owner.dart';import '../shared/theme/app_theme.dart' as grid;import 'login_relay_diagram.dart';@@ -150,7 +149,6 @@ class _BootAppMark extends StatelessWidget {),alignment: Alignment.center,child: Image.asset(- package: harnessAssetPackage,'assets/app_icon.png',width: 36,height: 36,diff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dartindex 60c80ee13..86390a55f 100644--- a/desktop/lib/widgets/engine_identity.dart+++ b/desktop/lib/widgets/engine_identity.dart@@ -1,6 +1,5 @@import 'dart:math' as math;-import '../core/asset_owner.dart';import 'package:flutter/material.dart';@@ -145,7 +144,6 @@ class EngineMark extends StatelessWidget {final identity = engineIdentity(engine, displayName: displayName);final mark = identity.asset != null? Image.asset(- package: harnessAssetPackage,identity.asset!,key: ValueKey('engine-icon-${identity.id}'),width: size,diff --git a/mobile/README.md b/mobile/README.mdindex 1e9ddd091..ac655156c 100644--- a/mobile/README.md+++ b/mobile/README.md@@ -1,17 +1,75 @@-# mobile+# Harness for iOS and Android-A new Flutter project.+A viewer onto the machines this device has linked — one agent at a time, on a phone.-## Getting Started+```bash+flutter pub get+flutter analyze # 0 issues outside third_party/xterm+flutter test+flutter run # -d <your device>+flutter build ios --debug --no-codesign+flutter build apk --debug+```-This project is a starting point for a Flutter application.+## This package depends on nothing else in this repo-A few resources to get you started if this is your first Flutter project:+`harness_mobile` is standalone. It used to be a thin shell over `path: ../desktop`, which meant every+desktop-only concern was a phone concern too: the app pulled in `window_manager`, `file_selector`,+`desktop_drop`, `sqlite3` and `go_router`, and the phone build was pinned to a Flutter app whose+targets are macOS and Linux.-- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter)-- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)-- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources)+The app it runs now lives under `lib/`, in the same folders the desktop app uses for it:-For help getting started with Flutter development, view the-[online documentation](https://docs.flutter.dev/), which offers tutorials,-samples, guidance on mobile development, and a full API reference.+| | |+|---|---|+| `lib/core/` | models, config, platform, file store, crash log |+| `lib/state/` | `AppNotifier` — machines, agents, connections, panes |+| `lib/api/`, `lib/ws/` | REST to the backend, and the relay socket per machine |+| `lib/auth/`, `lib/viewer/` | SSO, device linking, and the viewer's stand-ins for the harness CLI |+| `lib/e2ee/` | the end-to-end encryption this app terminates itself |+| `lib/terminal/`, `lib/widgets/` | the xterm session, the terminal panel and its chrome |+| `lib/shared/`, `lib/analytics/`, `lib/logging/` | design system, analytics, file logs |+| `third_party/xterm/` | the vendored, patched xterm 4.0.0 (see its `README.autonomous.md`) |++Two folders are this package's own, and have no counterpart on the desktop:++- **`lib/phone/`** — the shell a phone needs that a window does not: tabs, cards, sheets, the+ one-agent-at-a-time terminal page.+- **`lib/p2p/`** — the phone's second wire to each machine. The `terminal-v1` WebRTC data channel the+ harness CLI opens with werift on the desktop's behalf, so a terminal rides p2p or TURN when it can+ and the relay only when it must.++## It is a VIEWER build, always++No harness CLI runs beside this app and no agent is ever hosted here. It holds its own SSO session and+terminates the E2EE to each machine itself (`lib/viewer/`, `lib/e2ee/`) — where the desktop hands both+to the CLI on its own computer. `kViewerMode` (`lib/core/viewer_mode.dart`) is true on iOS and Android+unconditionally, and that one flag is what gates the paths a phone cannot take: first-run provisioning+and the self-updater are both skipped in `AppNotifier.bootstrap`, because an app the store updates+installs nothing.++## Keeping in step with `../desktop`++The shared half of `lib/` was **vendored** from `desktop/lib/`, not rewritten, and outside+`lib/phone/` and `lib/p2p/` the two trees are byte-identical apart from the package name and six+files. So a fix that belongs on both sides can be carried across with `diff`:++```bash+# What has drifted, ignoring the package rename+cd mobile/lib && for f in $(find . -name '*.dart' | sed 's|^\./||'); do+ [ -f "../../desktop/lib/$f" ] || continue+ diff -q <(sed 's|package:harness_mobile/|package:harness/|g' "$f") "../../desktop/lib/$f" >/dev/null \+ || echo "DIFFERS: $f"+done+```++The six that are expected to differ, and why:++| File | Why |+|---|---|+| `main.dart` | mounts `PhoneShell` and the p2p transport, not `SwarmScreen` |+| `app_shell.dart` | no managed window: `window_manager` ships for macOS/Windows/Linux only |+| `widgets/update_notice.dart` | same — it was wrapped in a window drag area |+| `screens/login_screen.dart`, `widgets/bootstrapping_screen.dart`, `widgets/engine_identity.dart` | assets are this package's own, so they no longer name a `package:` to load from |++`lib/core/desktop_window.dart` and `lib/widgets/window_chrome.dart` have no copy here at all.diff --git a/mobile/assets/app_icon.png b/mobile/assets/app_icon.pngnew file mode 100644index 000000000..d04fcb30dBinary files /dev/null and b/mobile/assets/app_icon.png differdiff --git a/mobile/assets/engine-icons/agy.png b/mobile/assets/engine-icons/agy.pngnew file mode 100644index 000000000..c677e4f5fBinary files /dev/null and b/mobile/assets/engine-icons/agy.png differdiff --git a/mobile/assets/engine-icons/amp.png b/mobile/assets/engine-icons/amp.pngnew file mode 100644index 000000000..0c66a6965Binary files /dev/null and b/mobile/assets/engine-icons/amp.png differdiff --git a/mobile/assets/engine-icons/codex.png b/mobile/assets/engine-icons/codex.pngnew file mode 100644index 000000000..7ef8986ebBinary files /dev/null and b/mobile/assets/engine-icons/codex.png differdiff --git a/mobile/assets/engine-icons/commandcode.png b/mobile/assets/engine-icons/commandcode.pngnew file mode 100644index 000000000..6af0c72efBinary files /dev/null and b/mobile/assets/engine-icons/commandcode.png differdiff --git a/mobile/assets/engine-icons/copilot.png b/mobile/assets/engine-icons/copilot.pngnew file mode 100644index 000000000..c0dd924faBinary files /dev/null and b/mobile/assets/engine-icons/copilot.png differdiff --git a/mobile/assets/engine-icons/cursor.png b/mobile/assets/engine-icons/cursor.pngnew file mode 100644index 000000000..ffc2f9b31Binary files /dev/null and b/mobile/assets/engine-icons/cursor.png differdiff --git a/mobile/assets/engine-icons/devin.png b/mobile/assets/engine-icons/devin.pngnew file mode 100644index 000000000..e5474fc06Binary files /dev/null and b/mobile/assets/engine-icons/devin.png differdiff --git a/mobile/assets/engine-icons/grok.png b/mobile/assets/engine-icons/grok.pngnew file mode 100644index 000000000..45cc9f579Binary files /dev/null and b/mobile/assets/engine-icons/grok.png differdiff --git a/mobile/assets/engine-icons/hermes.png b/mobile/assets/engine-icons/hermes.pngnew file mode 100644index 000000000..8db2977a5Binary files /dev/null and b/mobile/assets/engine-icons/hermes.png differdiff --git a/mobile/assets/engine-icons/kilo.png b/mobile/assets/engine-icons/kilo.pngnew file mode 100644index 000000000..03ebe10e6Binary files /dev/null and b/mobile/assets/engine-icons/kilo.png differdiff --git a/mobile/assets/engine-icons/muse.png b/mobile/assets/engine-icons/muse.pngnew file mode 100644index 000000000..d4b8c320dBinary files /dev/null and b/mobile/assets/engine-icons/muse.png differdiff --git a/mobile/assets/engine-icons/opencode.png b/mobile/assets/engine-icons/opencode.pngnew file mode 100644index 000000000..673c7e3a2Binary files /dev/null and b/mobile/assets/engine-icons/opencode.png differdiff --git a/mobile/assets/engine-icons/pi.png b/mobile/assets/engine-icons/pi.pngnew file mode 100644index 000000000..2b52d1275Binary files /dev/null and b/mobile/assets/engine-icons/pi.png differdiff --git a/mobile/lib/analytics/analytics.dart b/mobile/lib/analytics/analytics.dartnew file mode 100644index 000000000..7ef5a2f09--- /dev/null+++ b/mobile/lib/analytics/analytics.dart@@ -0,0 +1,54 @@+import 'analytics_config.dart';++export 'analytics_events.dart';+export 'analytics_sink.dart' show analytics, analyticsAccount;++/// The app's behavioural-event sink.+///+/// Ported from Grid (`lib/infrastructure/analytics/`) rather than rewritten, so+/// the two desktop apps report into one stream in one shape — see+/// [AnalyticsConfig] for the destination and why it is shared.+///+/// Not to be confused with the Harness CLI's `harness analytics`. That is a+/// different product: aggregate usage metering (turns per engine per day)+/// uploaded to the Harness backend. This is what a person *did* in this window,+/// and the two never meet.+///+/// Every call site talks to this, never to the transport underneath, so+/// tracking can be muted (opt-out, a test run, a build with no key) by handing+/// out a [NoopAnalytics] instead of by checking a flag at each call site.+///+/// Nothing here throws and nothing here is awaited by the UI: an analytics+/// problem must never be something the user finds out about.+abstract interface class Analytics {+ /// Queue one event. [name] must be `snake_case`+ /// (`analyticsEventNamePattern`) or it is dropped with a warning in the+ /// debug log — the backend would accept it silently and leave the stream+ /// unqueryable.+ ///+ /// [params] is free-form, but it is a *product* record, not a debug dump:+ /// never put message text, prompts, terminal output, file contents or+ /// absolute paths in it.+ void track(String name, {Map<String, Object?> params});++ /// Send whatever is queued now, instead of waiting on the retry timer.+ Future<void> flush();++ /// Final, time-boxed drain, then release the connection. Called when the app+ /// quits; the instance is spent afterwards.+ Future<void> close();+}++/// Does nothing, for a muted app and for tests.+class NoopAnalytics implements Analytics {+ const NoopAnalytics();++ @override+ void track(String name, {Map<String, Object?> params = const {}}) {}++ @override+ Future<void> flush() async {}++ @override+ Future<void> close() async {}+}diff --git a/mobile/lib/analytics/analytics_client.dart b/mobile/lib/analytics/analytics_client.dartnew file mode 100644index 000000000..b5a2037f9--- /dev/null+++ b/mobile/lib/analytics/analytics_client.dart@@ -0,0 +1,99 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'analytics_config.dart';++/// What one send attempt came to.+enum AnalyticsSendResult {+ /// The server took it.+ sent,++ /// Worth trying again with the same body — a timeout, an offline machine, a+ /// 429 or a 5xx. The event stays at the head of the queue.+ retry,++ /// The server refused the event itself (a 4xx that isn't 408 or 429). Sending+ /// it again would fail identically, so it is dropped and logged: that is our+ /// instrumentation being wrong, not the network.+ rejected,+}++/// Posts one event to Autonomous Analytics.+///+/// An interface rather than a bare function so the queue can be exercised+/// against a fake, which is how `test/analytics_test.dart` reaches every branch+/// without a socket.+abstract interface class AnalyticsClient {+ /// Sends [payload] as `POST …/event_tracking`. Never throws; a transport+ /// failure comes back as [AnalyticsSendResult.retry].+ Future<AnalyticsSendResult> send(Map<String, Object?> payload);++ /// Releases the underlying connection. Called once, when the app quits.+ void dispose();+}++/// Real [AnalyticsClient] over `dart:io` [HttpClient].+///+/// Deliberately not the app's Dio [ApiClient]: that one carries the CLI's base+/// URL and unwraps `{success, data|error}` envelopes, neither of which applies+/// to a third-party ingest host. One [HttpClient] for the life of the app, so a+/// burst of events reuses the connection instead of paying a TLS handshake per+/// click.+class HttpAnalyticsClient implements AnalyticsClient {+ HttpAnalyticsClient(this._config);++ final AnalyticsConfig _config;+ HttpClient? _client;+ bool _disposed = false;++ @override+ Future<AnalyticsSendResult> send(Map<String, Object?> payload) async {+ if (_disposed) return AnalyticsSendResult.rejected;+ try {+ final body = utf8.encode(jsonEncode(payload));+ final request = await _http().postUrl(_config.endpoint);+ request.headers.set(HttpHeaders.authorizationHeader, _config.writeKey);+ request.headers.set(HttpHeaders.contentTypeHeader, 'application/json');+ request.contentLength = body.length;+ request.add(body);+ final response = await request.close().timeout(+ AnalyticsLimits.requestTimeout,+ );+ // Drained rather than read: the response body says nothing the app acts+ // on, but an undrained socket is one that never returns to the pool.+ await response.drain<void>();+ return _resultFor(response.statusCode);+ } on TimeoutException {+ return AnalyticsSendResult.retry;+ } on SocketException {+ return AnalyticsSendResult.retry;+ } on HttpException {+ return AnalyticsSendResult.retry;+ } on Object {+ // Anything left (a bad URL, a TLS failure) would fail the same way every+ // time, so it is the event that goes, not the queue behind it.+ return AnalyticsSendResult.rejected;+ }+ }++ @override+ void dispose() {+ _disposed = true;+ _client?.close(force: true);+ _client = null;+ }++ HttpClient _http() =>+ _client ??= (HttpClient()+ ..connectionTimeout = const Duration(seconds: 10));++ /// 408 and 429 are "come back later", not "you are wrong" — they retry with+ /// the rest of the transport failures.+ static AnalyticsSendResult _resultFor(int status) => switch (status) {+ >= 200 && < 300 => AnalyticsSendResult.sent,+ 408 || 429 => AnalyticsSendResult.retry,+ >= 500 => AnalyticsSendResult.retry,+ _ => AnalyticsSendResult.rejected,+ };+}diff --git a/mobile/lib/analytics/analytics_config.dart b/mobile/lib/analytics/analytics_config.dartnew file mode 100644index 000000000..84187c6c9--- /dev/null+++ b/mobile/lib/analytics/analytics_config.dart@@ -0,0 +1,170 @@+import 'dart:io';++import 'package:flutter/foundation.dart';++import '../core/test_run.dart';++/// Where behavioural events go, whether they go at all, and under what limits.+///+/// The destination is **Autonomous Analytics** — the same event stream the+/// website and the Grid desktop app report into. Sharing the destination is the+/// point: someone who read the site, installed Grid and then installed Harness+/// is one funnel, not three datasets that can never be joined. [category] is+/// what keeps them apart within it.+///+/// ⚠️ **This app reports under GRID's write key, not one of its own.** The+/// constant below is the same one `autonomous-grid-app` ships, so both desktop+/// apps append into the same analytics project. That is a deliberate stopgap —+/// a muted stream measures nothing, and this app has been waiting on a key of+/// its own since the port — but the cost is real and worth stating: the two+/// apps are then separable **only by [category]** (`harness-desktop` against+/// Grid's `grid-app`, stamped on every event), not at the source. Anyone+/// reading the Grid project sees this app's events inside it, and anything set+/// per project — a quota, a retention rule, a rotated or revoked key — lands on+/// both apps at once.+///+/// TODO(BE): swap in a Harness Desktop key from the analytics owner. It is a+/// one-constant change here, and it is the only thing that separates the two+/// streams properly.+///+/// The key is a *write* key rather than a secret. The website ships the same+/// kind of key in its public JS bundle, a desktop binary can be unpacked either+/// way, and it only lets the holder append events.+class AnalyticsConfig {+ const AnalyticsConfig({+ required this.endpoint,+ required this.writeKey,+ this.offReason,+ });++ /// The full `…/api/v1/event_tracking` URL one event is POSTed to. Autonomous+ /// Analytics takes a single event per request — there is no batch route — so+ /// the queue sends serially rather than in batches.+ final Uri endpoint;++ /// Sent verbatim as `Authorization`, with no `Bearer` prefix — that is what+ /// the web client does and what the server reads.+ final String writeKey;++ /// Why nothing is being sent, or null when the stream is live. A sentence+ /// rather than a bool, because it is the answer to "why is nothing arriving"+ /// and a developer can lose an hour to that question.+ final String? offReason;++ /// Whether events are queued and sent at all.+ bool get enabled => offReason == null;++ /// Stamped on every event, so this app's stream stays separable from Grid's+ /// and the website's inside the shared project. Grid sends `grid-app`.+ static const String category = 'harness-desktop-v2';++ /// Env var / `--dart-define` names. The URL and key overrides are dev-only so+ /// a shipped build always reports to production; [disableEnvKey] is honoured+ /// everywhere, because a user who wants to be left alone has to be able to+ /// say so in a release build.+ static const String urlEnvKey = 'HARNESS_ANALYTICS_URL';+ static const String keyEnvKey = 'HARNESS_ANALYTICS_KEY';+ static const String disableEnvKey = 'HARNESS_ANALYTICS_DISABLED';++ // `String.fromEnvironment` needs a const literal, so the names above can't be+ // used here — keep the two in step by hand.+ static const String _urlDefine = String.fromEnvironment(+ 'HARNESS_ANALYTICS_URL',+ );+ static const String _keyDefine = String.fromEnvironment(+ 'HARNESS_ANALYTICS_KEY',+ );++ static const String _defaultBaseUrl =+ 'https://autonomous-analytics-qffztaoryq-uc.a.run.app/api/v1';+ static const String _path = 'event_tracking';++ /// Borrowed from Grid until this app has its own — see the class TODO(BE).+ /// Keep it byte-for-byte equal to `autonomous-grid-app`'s+ /// `AnalyticsConfig._defaultWriteKey`; a copy that drifts sends this app's+ /// events to a project nobody is reading.+ static const String _defaultWriteKey = 'tBCs0oLwgFgf1borYn54cjHz4fvWahyV';++ /// The live configuration, from the environment alone.+ static AnalyticsConfig resolve() {+ final base = (_devOverride(urlEnvKey) ?? _defaultBaseUrl).replaceFirst(+ RegExp(r'/+$'),+ '',+ );+ final key = _devOverride(keyEnvKey) ?? _defaultWriteKey;+ return AnalyticsConfig(+ endpoint: Uri.parse('$base/$_path'),+ writeKey: key,+ offReason: _offReason(key),+ );+ }++ static String? _offReason(String key) {+ if (key.isEmpty) {+ return 'This build carries no analytics key '+ '(set $keyEnvKey to turn the stream on).';+ }+ if (_muted) return '$disableEnvKey is set in this environment.';+ if (_underTest) return 'Running under flutter test.';+ return null;+ }++ /// True when `HARNESS_ANALYTICS_DISABLED` is set to anything truthy.+ static bool get _muted {+ final value = Platform.environment[disableEnvKey]?.toLowerCase().trim();+ return value == '1' || value == 'true' || value == 'yes';+ }++ /// Tests here build a real `AppNotifier` and drive real controllers, so one+ /// that happens to track an event must not open a socket or touch+ /// `~/.harness` to do it. See [kUnderTest] for the whole of why.+ static bool get _underTest => kUnderTest;++ /// [key]'s override — `--dart-define` first, then the process env — ignored+ /// in release so a shipped build can only ever report to production.+ static String? _devOverride(String key) {+ if (kReleaseMode) return null;+ final define = switch (key) {+ urlEnvKey => _urlDefine,+ keyEnvKey => _keyDefine,+ _ => '',+ };+ if (define.isNotEmpty) return define;+ final value = Platform.environment[key];+ return (value != null && value.isNotEmpty) ? value : null;+ }+}++/// The limits the queue and the payload are held to.+///+/// [sessionIdle] matches the website's and Grid's 15 minutes on purpose: a+/// "visit" has to mean the same span everywhere or the streams cannot be+/// compared. The rest are a desktop app's own — one quit offline and reopened+/// on a plane needs a bounded queue and a backoff, which a page that unloads+/// after a few minutes never did.+class AnalyticsLimits {+ const AnalyticsLimits._();++ /// Events kept while the server is unreachable. Past this the oldest go —+ /// a full queue is a signal, and the newest events describe it best.+ static const int queueCap = 500;++ /// Params per event, and the length of any one string value. The backend+ /// truncates and drops on its own; doing it here keeps what we send and what+ /// lands identical, so a value read back in analysis is the value we meant.+ static const int paramsMaxKeys = 40;+ static const int paramsMaxStringLength = 500;++ /// How long a visit survives without an event before a new one starts.+ static const Duration sessionIdle = Duration(minutes: 15);++ static const Duration requestTimeout = Duration(seconds: 10);++ /// First retry delay, doubled up to [retryDelayMax] while sends keep failing.+ static const Duration retryDelay = Duration(seconds: 2);+ static const Duration retryDelayMax = Duration(minutes: 2);++ /// How long a quit waits for the queue to drain. A wedged network must never+ /// be what keeps the window on screen after the user pressed ⌘Q.+ static const Duration closeDeadline = Duration(seconds: 3);+}diff --git a/mobile/lib/analytics/analytics_event.dart b/mobile/lib/analytics/analytics_event.dartnew file mode 100644index 000000000..ad588468a--- /dev/null+++ b/mobile/lib/analytics/analytics_event.dart@@ -0,0 +1,200 @@+import 'dart:convert';++import 'package:flutter/foundation.dart';++import 'analytics_config.dart';++/// The name rule this app holds itself to: `snake_case`, 3–64 characters.+///+/// Autonomous Analytics accepts anything — the website sends whole sentences+/// (`"Click button add to cart"`) — which is exactly why a rule is worth having+/// here. A stream where the same action is called three things is a stream+/// nobody can query, and the app is the only place that can prevent it.+final RegExp analyticsEventNamePattern = RegExp(r'^[a-z][a-z0-9_]{2,63}$');++/// The machine, the build and the OS an event happened on. Resolved once per+/// launch and attached to every event.+@immutable+class AnalyticsContext {+ const AnalyticsContext({+ required this.platform,+ required this.appVersion,+ required this.appBuild,+ required this.osVersion,+ required this.arch,+ required this.locale,+ required this.release,+ });++ /// `macos`, `windows` or `linux`. The website sends `web` in this field; the+ /// app says which desktop it is, because that is the first question asked of+ /// a desktop funnel.+ final String platform;++ final String appVersion;++ /// The `+N` build behind [appVersion]. Note that this app's `pubspec.yaml`+ /// version is a placeholder — the published version comes from the remote GCS+ /// manifest — so this field tells builds apart, it does not name a release.+ final String appBuild;++ final String osVersion;++ /// `macosArm64`, `macosX64`, … — an Intel Mac and an Apple Silicon one are+ /// different products as far as running agents and models locally goes.+ final String arch;++ final String locale;++ /// False in a developer build. Sent on every event so analysis can drop the+ /// noise our own machines make instead of guessing at it.+ final bool release;++ /// Stand-in for a context that could not be read, so an event still goes out+ /// with its name and identity rather than being dropped over a version+ /// lookup.+ static const AnalyticsContext unknown = AnalyticsContext(+ platform: '',+ appVersion: '',+ appBuild: '',+ osVersion: '',+ arch: '',+ locale: '',+ release: kReleaseMode,+ );++ /// The context as event params. Empty strings are dropped downstream, so a+ /// half-resolved context costs the missing fields and nothing else.+ Map<String, Object?> asParams() => {+ 'app_version': appVersion.isEmpty ? null : appVersion,+ 'app_build': appBuild.isEmpty ? null : appBuild,+ 'os': platform.isEmpty ? null : platform,+ 'os_version': osVersion.isEmpty ? null : osVersion,+ 'arch': arch.isEmpty ? null : arch,+ 'locale': locale.isEmpty ? null : locale,+ 'build': release ? 'release' : 'debug',+ };+}++/// Who an event belongs to and which visit it is part of.+@immutable+class AnalyticsIdentity {+ const AnalyticsIdentity({+ required this.pseudoId,+ required this.sessionId,+ this.userId,+ this.userEmail,+ });++ /// The device id — stable for the life of the machine, present whether or not+ /// anyone is signed in. See `AnalyticsIdentityStore`.+ final String pseudoId;++ /// The visit id, rotated after quiet (`AnalyticsLimits.sessionIdle`).+ final String sessionId;++ /// The signed-in account, or null before sign-in. The account id the CLI+ /// reports through `api.me()` — stable, and not something a user typed.+ final String? userId;++ /// Sent as a param, mirroring the website, so the same person can be found in+ /// both streams. Null while signed out.+ final String? userEmail;+}++/// One event, as it sits in the queue and goes on the wire.+@immutable+class AnalyticsEvent {+ const AnalyticsEvent({+ required this.name,+ required this.params,+ required this.at,+ required this.identity,+ });++ final String name;+ final Map<String, Object?> params;++ /// When the event *happened*, not when it was flushed — a queue that drains+ /// after a reconnect must not report an hour of activity as one instant.+ final DateTime at;++ final AnalyticsIdentity identity;+}++/// The Autonomous Analytics request body for [event].+///+/// Pure, so the wire format is checked by reading one function rather than by+/// watching a queue. The shape is the web client's: an envelope naming the+/// event and its timestamp, with everything else under `data`, and the params+/// as a `{key, value}` list.+///+/// `user_id` goes in both `data` and the params, as it does on the web — most+/// queries read the params table, and dropping it from there would make the+/// app's events the only ones that cannot be filtered by account.+Map<String, Object?> analyticsPayload(+ AnalyticsEvent event,+ AnalyticsContext context,+) {+ final identity = event.identity;+ // Merged as a map, not appended to a list: a later key simply wins, so an+ // event that wants to say more about `model` than the context did needs no+ // de-duplication pass afterwards (the web has one because it uses a list).+ final params = <String, Object?>{+ ...context.asParams(),+ 'user_id': identity.userId,+ 'user_email': identity.userEmail,+ ...event.params,+ 'category': AnalyticsConfig.category,+ };+ return {+ 'event_name': event.name,+ 'event_timestamp': event.at.millisecondsSinceEpoch ~/ 1000,+ 'data': {+ 'session_id': identity.sessionId,+ 'user_pseudo_id': identity.pseudoId,+ if (identity.userId != null) 'user_id': identity.userId,+ 'platform': context.platform,+ 'event_params': analyticsParams(params),+ },+ };+}++/// [params] as the wire's `{key, value}` list: nulls dropped, nested values+/// JSON-encoded, long strings clipped, and never more than+/// `AnalyticsLimits.paramsMaxKeys` entries.+List<Map<String, Object?>> analyticsParams(Map<String, Object?> params) {+ final out = <Map<String, Object?>>[];+ for (final entry in params.entries) {+ final value = entry.value;+ if (value == null) continue;+ if (value is String && value.isEmpty) continue;+ if (out.length >= AnalyticsLimits.paramsMaxKeys) break;+ out.add({'key': entry.key, 'value': analyticsValue(value)});+ }+ return out;+}++/// One param value the backend can store: a string, a number or a bool.+/// Anything else is JSON-encoded (the website does the same), and anything long+/// is clipped to `AnalyticsLimits.paramsMaxStringLength`.+Object analyticsValue(Object value) {+ final encoded = switch (value) {+ String() || num() || bool() => value,+ _ => _encode(value),+ };+ if (encoded is! String) return encoded;+ return encoded.length > AnalyticsLimits.paramsMaxStringLength+ ? encoded.substring(0, AnalyticsLimits.paramsMaxStringLength)+ : encoded;+}++/// JSON, or the value's own `toString` when it isn't encodable — a param that+/// cannot be serialised must cost that param, never the event.+String _encode(Object value) {+ try {+ return jsonEncode(value);+ } on Object {+ return value.toString();+ }+}diff --git a/mobile/lib/analytics/analytics_events.dart b/mobile/lib/analytics/analytics_events.dartnew file mode 100644index 000000000..135a07629--- /dev/null+++ b/mobile/lib/analytics/analytics_events.dart@@ -0,0 +1,117 @@+import 'analytics.dart';++/// The events this app sends, one method each.+///+/// An extension rather than a set of loose helpers, so every [Analytics]+/// implementation gets them for free — and so the name and the params of an+/// event are written down **once**. Two call sites that name the same action+/// differently is the failure mode this exists to prevent.+///+/// Adding an event: add a method here, keep the name `snake_case`, and keep the+/// params to product facts — a short code, an option, a count. **Never** a+/// prompt, terminal output, an agent's name, a repository path or a machine+/// hostname. This stream describes what someone did, not what they wrote or+/// what their machines are called; ids are fine, the names people give things+/// are not.+extension AnalyticsEvents on Analytics {+ // --- The launch ---------------------------------------------------------++ /// The app came up. [signedIn] separates a returning user from someone who+ /// is about to meet the login screen.+ void appOpened({required bool signedIn}) =>+ track('app_opened', params: {'signed_in': signedIn});++ /// The app is quitting, after [open]. Sent on the way out, so it is the last+ /// thing the queue drains.+ void appClosed({required Duration open}) =>+ track('app_closed', params: {'open_seconds': open.inSeconds});++ /// A screen was opened. [screen] is the section's stable name, never its+ /// label — labels are rewritten weekly and a renamed label would read as a+ /// new screen.+ ///+ /// [source] is the DOOR that was used, and it is `required` for the reason+ /// `new_agent_opened`'s is: a screen with several ways in tells you almost+ /// nothing as a bare count.+ ///+ /// Values: `account_menu` and `shortcut` (a door that OPENED Settings on this+ /// pane); `rail` (moved here from another pane, using the settings rail).+ void screenView(String screen, {required String source}) =>+ track('screen_view', params: {'screen': screen, 'source': source});++ // --- Sign-in ------------------------------------------------------------++ /// Sign-in completed.+ void signedIn() => track('signed_in');++ /// Sign-in didn't complete. [reason] is a short code — `cancelled`,+ /// `failed` — never the error text, which can carry a path or a host name.+ void signInFailed(String reason) =>+ track('sign_in_failed', params: {'reason': reason});++ /// The user signed out.+ void signedOut() => track('signed_out');++ /// First-run provisioning finished. [ready] is false when a required step+ /// could not be completed — which says how much of a fresh Mac this app can+ /// actually set up on its own, otherwise only visible in a support thread.+ void environmentPrepared({required bool ready}) =>+ track('environment_prepared', params: {'ready': ready});++ // --- Agents -------------------------------------------------------------+ //+ // How many people open the New agent dialog, how many of those finish it,+ // and how many of THOSE ever send the agent a message. Each step is a+ // separate event carrying the same device and user id, so the funnel is+ // built by counting distinct people per step.++ /// The New agent dialog was opened. [source] is which door was used —+ /// `machine_row` (the `+` on a machine's row), `rail_empty` (the button the+ /// empty rail shows), `pane_empty` (the button in the empty centre pane) or+ /// `shortcut` (⌘N and the app menu).+ ///+ /// Sent by `showNewAgentDialog` itself rather than by its callers, so a door+ /// added later cannot forget to report itself.+ void newAgentOpened({required String source}) =>+ track('new_agent_opened', params: {'source': source});++ /// An agent was created from the New agent dialog. [engine] is the engine id+ /// and [bypassPermission] whether its own guardrails were switched off, both+ /// product facts.+ ///+ /// The working folder is deliberately absent: it is an absolute path, which+ /// this stream never carries.+ void agentCreated({required String engine, required bool bypassPermission}) =>+ track(+ 'agent_created',+ params: {'engine': engine, 'bypass_permission': bypassPermission},+ );++ /// The first message of a signed-in session — how long it took this person to+ /// get from being logged in to actually talking to an agent, whichever agent+ /// that turned out to be.+ ///+ /// **Once per sign-in, not per agent.** Which agent it was is+ /// [agentCreated]'s question; this one is about the gap at the top of the+ /// funnel, where somebody signs in and then does nothing.+ ///+ /// [from] says what started the clock, because the two populations behave+ /// nothing alike: `sign_in` is a fresh log-in, `launch` is opening the app+ /// with a session already on the machine. Averaging them together would hide+ /// both.+ ///+ /// Driven by the CLI's `turn_started`, not by the composer, so a message+ /// typed straight into the terminal counts the same as one sent from the box+ /// underneath it — which is how most people drive these engines.+ ///+ /// ⚠️ **No message text, ever**, and no agent, machine or folder either. Who+ /// it was and when are already on every event (`user_email`,+ /// `event_timestamp`); what this adds is the wait.+ void appFirstMessage({+ required String from,+ required int secondsSinceLogin,+ }) => track(+ 'app_first_message',+ params: {'from': from, 'seconds_since_login': secondsSinceLogin},+ );+}diff --git a/mobile/lib/analytics/analytics_identity.dart b/mobile/lib/analytics/analytics_identity.dartnew file mode 100644index 000000000..ec2a9fdbc--- /dev/null+++ b/mobile/lib/analytics/analytics_identity.dart@@ -0,0 +1,178 @@+import 'dart:convert';+import 'dart:io';+import 'dart:math';++import '../core/harness_file_store.dart';+import 'analytics_config.dart';++/// The device id and the visit id every event carries, kept in+/// `~/.harness/desktop-app/analytics.json`.+///+/// Two ids, two lifetimes. The **device id** is minted once and never reset —+/// it is what ties a person's first launch to the day they finally ran an+/// agent, across sign-in and sign-out. The **visit id** rotates after+/// `AnalyticsLimits.sessionIdle` of quiet, which is how a session is counted.+///+/// The file also carries the user's own switch: `{"enabled": false}` mutes the+/// app, and is preserved by every write here so turning it off stays off.+///+/// Its own file rather than a key in [HarnessFileStore]'s `state.json`: that+/// store is async, serialised behind a lock and holds credentials, while this+/// is read synchronously on the first event of a launch and is the one piece of+/// app state a user may reasonably want to open and edit by hand.+///+/// Lenient like the other app stores — a missing, corrupt or hand-edited file+/// reads as "no ids yet" rather than throwing, because the alternative is an+/// analytics detail breaking the launch it was meant to measure. Both files are+/// overridable so tests never touch a real Harness home.+class AnalyticsIdentityStore {+ AnalyticsIdentityStore({File? file, File? computerIdFile, Random? random})+ : _file = file ?? File('${HarnessFileStore.defaultDirectoryPath()}/$_name'),+ _computerIdFile = computerIdFile ?? File(_defaultComputerIdPath()),+ _random = random ?? Random.secure();++ static const String _name = 'analytics.json';++ final File _file;+ final File _computerIdFile;+ final Random _random;++ _StoredIdentity? _state;++ /// How stale the on-disk `last_active_ms` is allowed to get. A write per event+ /// would be an fsync per click; the cost of lagging is that a restart after a+ /// long quiet spell may start a new visit up to a minute early, which is+ /// noise beside a 15-minute window.+ static const Duration _persistEvery = Duration(minutes: 1);++ /// `~/.harness/computer-id` — the machine identity this app already shares+ /// with the CLI (`LocalCliDiscovery.defaultComputerIdPath`). Resolved the same+ /// way rather than imported, so an analytics detail cannot drag the WS layer+ /// into every test that builds this store.+ static String _defaultComputerIdPath() =>+ '${Directory(HarnessFileStore.defaultDirectoryPath()).parent.path}'+ '/computer-id';++ /// Whether the user turned tracking off in+ /// `~/.harness/desktop-app/analytics.json`.+ bool get optedOut => _load().optedOut;++ /// The ids as they stand, without starting a visit or moving the clock.+ /// `sessionId` is empty until the first event of a launch has been tracked.+ ({String pseudoId, String sessionId}) peek() {+ final state = _load();+ return (pseudoId: state.pseudoId, sessionId: state.sessionId);+ }++ /// The ids for an event happening at [now], rotating the visit after a quiet+ /// spell and persisting sparingly (see [_persistEvery]).+ ({String pseudoId, String sessionId}) touch(DateTime now) {+ final state = _load();+ final at = now.millisecondsSinceEpoch;+ final expired =+ state.sessionId.isEmpty ||+ at - state.lastActive > AnalyticsLimits.sessionIdle.inMilliseconds;+ final next = _StoredIdentity(+ pseudoId: state.pseudoId,+ sessionId: expired ? _uuidV4(_random) : state.sessionId,+ lastActive: at,+ optedOut: state.optedOut,+ );+ _state = next;+ if (expired || at - state.lastActive >= _persistEvery.inMilliseconds) {+ _persist(next);+ }+ return (pseudoId: next.pseudoId, sessionId: next.sessionId);+ }++ _StoredIdentity _load() {+ final cached = _state;+ if (cached != null) return cached;+ var json = const <String, Object?>{};+ try {+ if (_file.existsSync()) {+ final decoded = jsonDecode(_file.readAsStringSync());+ if (decoded is Map) json = decoded.cast<String, Object?>();+ }+ } on Object {+ // Corrupt or hand-edited: start over rather than fail the launch.+ }+ final stored = (json['user_pseudo_id'] as String?)?.trim();+ final state = _StoredIdentity(+ pseudoId: stored != null && stored.isNotEmpty ? stored : _newPseudoId(),+ sessionId: (json['session_id'] as String?) ?? '',+ lastActive: (json['last_active_ms'] as num?)?.toInt() ?? 0,+ optedOut: json['enabled'] == false,+ );+ _state = state;+ return state;+ }++ /// A fresh device id: this computer's Harness id when it has one, else a new+ /// UUID.+ ///+ /// Borrowing `computer-id` rather than minting a second one is what lets an+ /// event be lined up with the machine the backend knows about. It is copied+ /// here on first use and then never re-read, so a later re-registration that+ /// rewrites that file cannot silently turn this machine into a second+ /// visitor.+ String _newPseudoId() => _computerId() ?? _uuidV4(_random);++ String? _computerId() {+ try {+ if (!_computerIdFile.existsSync()) return null;+ final id = _computerIdFile.readAsStringSync().trim();+ return id.isEmpty ? null : id;+ } on Object {+ return null;+ }+ }++ /// Writes the ids back, `enabled` included so a user's opt-out survives.+ void _persist(_StoredIdentity state) {+ try {+ _file.parent.createSync(recursive: true);+ _file.writeAsStringSync(+ const JsonEncoder.withIndent(' ').convert({+ 'user_pseudo_id': state.pseudoId,+ 'session_id': state.sessionId,+ 'last_active_ms': state.lastActive,+ 'enabled': !state.optedOut,+ }),+ flush: true,+ );+ } on Object {+ // A read-only home or a full disk costs id stability across restarts,+ // not the event in hand.+ }+ }+}++/// What `analytics.json` holds, as one immutable value.+class _StoredIdentity {+ const _StoredIdentity({+ required this.pseudoId,+ required this.sessionId,+ required this.lastActive,+ required this.optedOut,+ });++ final String pseudoId;+ final String sessionId;++ /// Epoch ms of the last tracked event.+ final int lastActive;+ final bool optedOut;+}++/// A random v4 UUID — the id format both this stream and the CLI already use.+/// `Random.secure` so two machines starting in the same millisecond cannot be+/// handed the same device id.+String _uuidV4(Random random) {+ final bytes = List<int>.generate(16, (_) => random.nextInt(256));+ bytes[6] = (bytes[6] & 0x0f) | 0x40;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;+ final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();+ return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-'+ '${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';+}diff --git a/mobile/lib/analytics/analytics_lifecycle.dart b/mobile/lib/analytics/analytics_lifecycle.dartnew file mode 100644index 000000000..3a1f6a3f7--- /dev/null+++ b/mobile/lib/analytics/analytics_lifecycle.dart@@ -0,0 +1,70 @@+import 'dart:ui' show AppExitResponse;++import 'package:flutter/widgets.dart';++import '../stats/harness_stats.dart';+import 'analytics.dart';++/// Closes the launch out: `app_closed`, then a time-boxed drain of whatever is+/// still queued. Renders [child] unchanged.+///+/// Only `didRequestAppExit` is hooked, which covers ⌘Q, the app menu's Quit and+/// an OS log-out. Grid also intercepts the window's close button, but that+/// needs `windowManager.setPreventClose(true)` and a matching `destroy()` call+/// — and a bug on that path leaves a window the user cannot close. A missing+/// `app_closed` is worth less than that risk, so this app takes the exit hook+/// alone; `app_opened` is unaffected either way.+///+/// The matching `app_opened` is NOT here. It is sent by `AppNotifier` when+/// bootstrap resolves, because `signed_in` is not known until the CLI has been+/// asked, and a first-frame event would report every launch as signed out.+class AnalyticsLifecycle extends StatefulWidget {+ const AnalyticsLifecycle({super.key, required this.child});++ final Widget child;++ @override+ State<AnalyticsLifecycle> createState() => _AnalyticsLifecycleState();+}++class _AnalyticsLifecycleState extends State<AnalyticsLifecycle>+ with WidgetsBindingObserver {+ /// When this launch started, so the quit event can say how long the app was+ /// open.+ final DateTime _openedAt = DateTime.now();++ /// Guards against a quit that somehow asks twice.+ bool _closed = false;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }++ @override+ Future<AppExitResponse> didRequestAppExit() async {+ if (!_closed) {+ _closed = true;+ analytics.appClosed(open: DateTime.now().difference(_openedAt));+ // Before the drain below, and awaited: this is a local file write that+ // finishes in milliseconds, and it is the ONLY place a turn still running+ // at quit gets its time counted — the debounce timer is cancelled by the+ // process exiting, not fired by it.+ await harnessStats.flush();+ // Time-boxed inside `close` itself — a wedged network must never be what+ // keeps the window on screen after the user pressed ⌘Q.+ await analytics.close();+ }+ return AppExitResponse.exit;+ }++ @override+ Widget build(BuildContext context) => widget.child;+}diff --git a/mobile/lib/analytics/analytics_log.dart b/mobile/lib/analytics/analytics_log.dartnew file mode 100644index 000000000..15a3ef6f7--- /dev/null+++ b/mobile/lib/analytics/analytics_log.dart@@ -0,0 +1,216 @@+import 'dart:async';+import 'dart:collection';+import 'dart:convert';++import 'package:flutter/foundation.dart';++/// Where one tracked event got to.+enum AnalyticsEventStatus {+ /// In the queue: never sent, or sent and waiting on a retry.+ queued,++ /// The server took it.+ sent,++ /// The server refused it (a 4xx that isn't 408/429) — our instrumentation is+ /// wrong, not the network.+ refused,++ /// Never reached the wire: an invalid name, a full queue, or a build whose+ /// stream is muted.+ dropped,+}++/// One tracked event as Settings ▸ Tracking shows it: what was tracked, what+/// went over the wire, and how it ended.+///+/// Mutable in place, like [LogEntry] and unlike Grid's immutable+/// `AnalyticsLogEntry`: Grid rebuilds through `copyWith` because Riverpod+/// compares state objects, while this buffer is a [ChangeNotifier] and an event+/// that is still retrying collects its attempts on the entry it already has.+class AnalyticsLogEntry {+ AnalyticsLogEntry({+ required this.id,+ required this.name,+ required this.params,+ required this.queuedAt,+ });++ /// Monotonic within a session — the handle the queue settles a row by.+ final int id;++ final String name;++ /// The params as the call site passed them, before the context and the+ /// identity are merged in. [payload] is what actually went out.+ final Map<String, Object?> params;++ final DateTime queuedAt;++ AnalyticsEventStatus status = AnalyticsEventStatus.queued;++ /// How many times this event has been put on the wire. Two or more means the+ /// endpoint failed and the queue retried, which is the thing this screen+ /// exists to make visible.+ int attempts = 0;++ /// The exact JSON body sent, re-indented, or null before the first attempt.+ String? payload;++ /// Why it ended the way it did, when the status alone doesn't say.+ String? note;++ DateTime? settledAt;++ /// How long from being tracked to being settled, or null while it waits.+ Duration? get took => settledAt?.difference(queuedAt);+}++/// The recorder the analytics queue reports to.+///+/// An interface so the queue stays free of the screen, and so a release build —+/// which has no Tracking screen — pays nothing for it. The same seam+/// `AnalyticsClient` gives the transport.+abstract interface class AnalyticsLog {+ /// Records an event entering the queue; returns its id for the calls below.+ int queued(String name, Map<String, Object?> params, DateTime at);++ /// Records that [payload] has just gone on the wire for entry [id]. Called+ /// once per attempt, so the count reads as retries.+ ///+ /// Takes the payload as the map the queue already built rather than as a+ /// string: encoding it is the recorder's business, and a build with nothing+ /// recording must not pay for a `jsonEncode` per event.+ void attempted(int id, Map<String, Object?> payload);++ /// Records how entry [id] ended.+ void settled(int id, AnalyticsEventStatus status, {String? note});+}++/// Records nothing — what a release build gets, so the queue can run with no+/// screen watching.+class NoopAnalyticsLog implements AnalyticsLog {+ const NoopAnalyticsLog();++ @override+ int queued(String name, Map<String, Object?> params, DateTime at) => 0;++ @override+ void attempted(int id, Map<String, Object?> payload) {}++ @override+ void settled(int id, AnalyticsEventStatus status, {String? note}) {}+}++/// The events this session tracked, newest first — a bounded ring, fed by+/// `QueuedAnalytics` and read by Settings ▸ Tracking.+///+/// In memory only, and deliberately: this is a window onto a queue that is+/// itself in memory, and a stream that measures the app must not become a+/// second thing the app writes to disk on every click. It is the one place the+/// question analytics always raises can be answered — *did that event actually+/// leave, and what was in it?* — because an event that was never sent, sent+/// with a missing field, or refused by the server looks exactly like an event+/// that landed: the app is silent either way, by design.+class AnalyticsLogStream extends ChangeNotifier implements AnalyticsLog {+ AnalyticsLogStream({this.maxEntries = 200});++ /// How many events the buffer keeps. Smaller than [LogStream]'s 500: one row+ /// here is one deliberate product event, not a socket frame, and a session+ /// that has tracked two hundred of them has long since answered the question+ /// this screen was opened with.+ final int maxEntries;++ final List<AnalyticsLogEntry> _entries = [];+ int _seq = 0;+ bool _notifyScheduled = false;++ /// Newest first — the order the Tracking list reads in.+ late final UnmodifiableListView<AnalyticsLogEntry> entries =+ UnmodifiableListView(_entries);++ @override+ int queued(String name, Map<String, Object?> params, DateTime at) {+ final id = ++_seq;+ _entries.insert(+ 0,+ AnalyticsLogEntry(+ id: id,+ name: name,+ // Copied, so a caller that reuses its map cannot rewrite history here.+ params: Map<String, Object?>.unmodifiable(params),+ queuedAt: at,+ ),+ );+ if (_entries.length > maxEntries) {+ _entries.removeRange(maxEntries, _entries.length);+ }+ _scheduleNotify();+ return id;+ }++ @override+ void attempted(int id, Map<String, Object?> payload) {+ final entry = _entryFor(id);+ if (entry == null) return;+ entry.attempts += 1;+ entry.payload = _pretty(payload);+ _scheduleNotify();+ }++ @override+ void settled(int id, AnalyticsEventStatus status, {String? note}) {+ final entry = _entryFor(id);+ if (entry == null) return;+ entry.status = status;+ entry.note = note;+ entry.settledAt = DateTime.now();+ _scheduleNotify();+ }++ void clear() {+ if (_entries.isEmpty) return;+ _entries.clear();+ _scheduleNotify();+ }++ /// An event settles near where it was queued, and the newest rows are at the+ /// front — so this walks a handful of entries, not the buffer. Null once a+ /// row has been pushed out by [maxEntries] or dropped by [clear], which the+ /// callers treat as "nothing left to update" rather than as an error.+ AnalyticsLogEntry? _entryFor(int id) {+ for (final entry in _entries) {+ if (entry.id == id) return entry;+ }+ return null;+ }++ /// One notification per microtask, however many rows changed in it — the+ /// same rhythm [LogStream] keeps, for the same reason: a queue draining after+ /// a reconnect settles a run of events in one pass.+ void _scheduleNotify() {+ if (_notifyScheduled) return;+ _notifyScheduled = true;+ scheduleMicrotask(() {+ _notifyScheduled = false;+ notifyListeners();+ });+ }++ /// The body as it went out, re-indented so the dialog can be read.+ ///+ /// A payload that will not encode costs its own readability and nothing else+ /// — this is a debug view of an event that has *already been sent*, and+ /// throwing here would take the row with it.+ static String _pretty(Map<String, Object?> payload) {+ try {+ return const JsonEncoder.withIndent(' ').convert(payload);+ } on Object {+ return payload.toString();+ }+ }+}++/// This session's tracked events. Fed only where the Tracking screen exists —+/// see `analyticsRecorder` in `analytics_sink.dart`.+final AnalyticsLogStream analyticsLog = AnalyticsLogStream();diff --git a/mobile/lib/analytics/analytics_service.dart b/mobile/lib/analytics/analytics_service.dartnew file mode 100644index 000000000..2ad50bd19--- /dev/null+++ b/mobile/lib/analytics/analytics_service.dart@@ -0,0 +1,220 @@+import 'dart:async';+import 'dart:collection';++import 'package:flutter/foundation.dart';++import 'analytics.dart';+import 'analytics_client.dart';+import 'analytics_config.dart';+import 'analytics_event.dart';+import 'analytics_identity.dart';+import 'analytics_log.dart';++/// Who is signed in, asked fresh at track time — a session that starts signed+/// out and ends signed in must not report the whole visit as anonymous.+typedef AnalyticsUserLookup = ({String? id, String? email}) Function();++/// [Analytics] that queues in memory and sends serially, with retry.+///+/// Autonomous Analytics takes one event per request, so this is a queue with a+/// worker rather than a batcher. The order of the three failure paths is the+/// point: a **transport** failure keeps the event and backs off, a **refusal**+/// drops it (resending changes nothing), and a queue that grows past+/// `AnalyticsLimits.queueCap` drops its oldest — the newest events are the ones+/// that describe what is happening now.+///+/// Not persisted across launches: a machine quit while offline loses what was+/// still queued. That is a deliberate limit, not an oversight — the alternative+/// is a spool file that outlives an uninstall.+///+/// Ported from Grid, [recorder] included: Settings ▸ Tracking is this app's+/// version of Grid's Tracking tab, and it is fed from here rather than from a+/// second stream, so a row on that screen is an event this queue really held.+class QueuedAnalytics implements Analytics {+ QueuedAnalytics({+ required this.client,+ required this.identityStore,+ required this.contextFuture,+ required this.userLookup,+ this.recorder = const NoopAnalyticsLog(),+ this.clock = DateTime.now,+ });++ /// The collaborators, public because they arrive through the constructor and+ /// a test that swaps one has no reason to reach past the door it came in by.+ /// Named apart from the locals they produce (`context`, the account) so a+ /// method body cannot quietly shadow one of them.+ final AnalyticsClient client;+ final AnalyticsIdentityStore identityStore;+ final Future<AnalyticsContext> contextFuture;+ final AnalyticsUserLookup userLookup;++ /// Where the Tracking screen reads this queue from. A [NoopAnalyticsLog] in+ /// a release build, so nothing is retained for a screen that is not there.+ final AnalyticsLog recorder;++ final DateTime Function() clock;++ /// Each queued event beside the id of its row on the Tracking screen, so the+ /// row can be settled without the wire model carrying a debug field.+ final Queue<({AnalyticsEvent event, int logId})> _queue =+ Queue<({AnalyticsEvent event, int logId})>();++ AnalyticsContext? _resolvedContext;+ Future<void>? _draining;+ Timer? _retryTimer;+ Duration _retryDelay = AnalyticsLimits.retryDelay;+ bool _warnedFull = false;+ bool _closed = false;++ /// How many events are waiting to go out. Test seam, and the one honest+ /// answer to "did that call actually queue anything".+ @visibleForTesting+ int get pending => _queue.length;++ @override+ void track(String name, {Map<String, Object?> params = const {}}) {+ if (_closed) return;+ final now = clock();+ if (!analyticsEventNamePattern.hasMatch(name)) {+ const reason = 'names must be snake_case, 3-64 characters';+ // Recorded before it is refused, so the Tracking screen shows the mistake+ // rather than nothing at all — an event that never lands is exactly what+ // somebody would open that screen to explain.+ recorder.settled(+ recorder.queued(name, params, now),+ AnalyticsEventStatus.dropped,+ note: reason,+ );+ debugPrint('analytics: ignored event "$name" — $reason');+ return;+ }+ try {+ final ids = identityStore.touch(now);+ final account = userLookup();+ _queue.add((+ event: AnalyticsEvent(+ name: name,+ params: params,+ at: now,+ identity: AnalyticsIdentity(+ pseudoId: ids.pseudoId,+ sessionId: ids.sessionId,+ userId: account.id,+ userEmail: account.email,+ ),+ ),+ logId: recorder.queued(name, params, now),+ ));+ _trim();+ unawaited(_pump());+ } on Object catch (error) {+ debugPrint('analytics: dropped event "$name" — $error');+ }+ }++ @override+ Future<void> flush() {+ _cancelRetry();+ return _pump();+ }++ @override+ Future<void> close() async {+ if (_closed) return;+ _cancelRetry();+ await _pump().timeout(AnalyticsLimits.closeDeadline, onTimeout: () {});+ _closed = true;+ client.dispose();+ }++ /// Drops the oldest events once the queue is over its cap, warning once per+ /// outage so a plane ride doesn't fill the log with the same line.+ void _trim() {+ if (_queue.length <= AnalyticsLimits.queueCap) return;+ while (_queue.length > AnalyticsLimits.queueCap) {+ recorder.settled(+ _queue.removeFirst().logId,+ AnalyticsEventStatus.dropped,+ note: 'the queue was full',+ );+ }+ if (_warnedFull) return;+ _warnedFull = true;+ debugPrint(+ 'analytics: event queue full (${AnalyticsLimits.queueCap}) — dropping '+ 'the oldest; the endpoint has been unreachable for a while',+ );+ }++ /// One drain at a time: concurrent callers share the in-flight future rather+ /// than starting a second worker on the same queue.+ Future<void> _pump() {+ if (_closed || _queue.isEmpty) return Future.value();+ return _draining ??= _drain().whenComplete(() => _draining = null);+ }++ Future<void> _drain() async {+ final context = _resolvedContext ??= await contextFuture.catchError(+ (Object _) => AnalyticsContext.unknown,+ );+ while (_queue.isNotEmpty && !_closed) {+ final queued = _queue.first;+ final event = queued.event;+ final AnalyticsSendResult result;+ try {+ final payload = analyticsPayload(event, context);+ recorder.attempted(queued.logId, payload);+ result = await client.send(payload);+ } on Object catch (error) {+ // The client's contract says it never throws; if it ever does, the+ // queue must not be left spinning on the same event forever.+ _queue.removeFirst();+ recorder.settled(+ queued.logId,+ AnalyticsEventStatus.dropped,+ note: '$error',+ );+ debugPrint('analytics: send failed for "${event.name}" — $error');+ continue;+ }+ switch (result) {+ case AnalyticsSendResult.sent:+ _queue.removeFirst();+ recorder.settled(queued.logId, AnalyticsEventStatus.sent);+ _retryDelay = AnalyticsLimits.retryDelay;+ _warnedFull = false;+ case AnalyticsSendResult.rejected:+ _queue.removeFirst();+ recorder.settled(+ queued.logId,+ AnalyticsEventStatus.refused,+ note: 'the server refused it',+ );+ debugPrint(+ 'analytics: server refused "${event.name}" — the event was dropped',+ );+ case AnalyticsSendResult.retry:+ _scheduleRetry();+ return;+ }+ }+ }++ void _scheduleRetry() {+ if (_retryTimer != null || _closed) return;+ _retryTimer = Timer(_retryDelay, () {+ _retryTimer = null;+ unawaited(_pump());+ });+ final doubled = _retryDelay * 2;+ _retryDelay = doubled > AnalyticsLimits.retryDelayMax+ ? AnalyticsLimits.retryDelayMax+ : doubled;+ }++ void _cancelRetry() {+ _retryTimer?.cancel();+ _retryTimer = null;+ }+}diff --git a/mobile/lib/analytics/analytics_sink.dart b/mobile/lib/analytics/analytics_sink.dartnew file mode 100644index 000000000..44e273326--- /dev/null+++ b/mobile/lib/analytics/analytics_sink.dart@@ -0,0 +1,207 @@+import 'dart:async';+import 'dart:ffi' show Abi;+import 'dart:io';++import 'package:flutter/foundation.dart';+import 'package:package_info_plus/package_info_plus.dart';++import '../logging/debug_surface.dart';+import 'analytics.dart';+import 'analytics_client.dart';+import 'analytics_config.dart';+import 'analytics_event.dart';+import 'analytics_identity.dart';+import 'analytics_log.dart';+import 'analytics_service.dart';++/// The app's one analytics sink.+///+/// A lazily-built singleton rather than a Riverpod provider, for the same+/// reason `terminalFontStore` is: the call sites have no+/// common ancestor short of `MaterialApp` — `main`, `AppNotifier`, a settings+/// pane, a menu item inside a pane header — and most of them are plain widgets+/// that were handed a notifier, not a `Ref`.+///+/// [NoopAnalytics] whenever tracking is off — no key in this build, the+/// environment muted it, the code is under `flutter test`, or the user opted+/// out in `~/.harness/desktop-app/analytics.json` — so a muted app and a test+/// run open no sockets at all rather than queueing into a void.+Analytics get analytics => _analytics ??= _build();++Analytics? _analytics;++/// Replaces the sink, for tests. Returns what was there, so a test can put it+/// back; passing null re-arms the lazy build.+@visibleForTesting+Analytics? setAnalyticsForTest(Analytics? value) {+ final previous = _analytics;+ _analytics = value;+ return previous;+}++Analytics _build() {+ // The environment is asked first, and on purpose: under `flutter test` this+ // returns before anything reads `~/.harness`, so a widget test that happens+ // to track an event touches neither the network nor a real Harness home.+ final config = AnalyticsConfig.resolve();+ if (config.offReason case final reason?) return _muted(reason);+ final identity = AnalyticsIdentityStore();+ if (identity.optedOut) return _muted(kAnalyticsOptedOutReason);+ return QueuedAnalytics(+ client: HttpAnalyticsClient(config),+ identityStore: identity,+ contextFuture: resolveAnalyticsContext(),+ userLookup: () => analyticsAccount.current,+ recorder: analyticsRecorder,+ );+}++/// A muted sink that still shows its work where there is a screen to show it+/// on, and a plain [NoopAnalytics] where there is not.+///+/// A build can be muted for four reasons — no key, `HARNESS_ANALYTICS_DISABLED`,+/// `flutter test`, or the user's own opt-out (see [AnalyticsConfig]) — and a+/// Tracking screen that were permanently empty for any of them is the exact+/// trap that screen exists to spring. Every event still lands in the list,+/// settled as `dropped` with [reason], which turns "nothing is arriving" into a+/// sentence.+///+/// Nothing recorded here leaves the machine: the buffer is in memory, and a+/// build with no [kDebugSurfaceEnabled] keeps none of it. That is what makes it+/// right to record even for a user who opted out — their choice is about what+/// we *send*, and this sends nothing.+Analytics _muted(String reason) => kDebugSurfaceEnabled+ ? MutedAnalytics(analyticsLog, reason)+ : const NoopAnalytics();++/// Where the queue reports its rows: this session's buffer where the Tracking+/// screen exists, nothing at all where it does not.+AnalyticsLog get analyticsRecorder =>+ kDebugSurfaceEnabled ? analyticsLog : const NoopAnalyticsLog();++/// Why a sink is muted when the user turned it off by hand.+const String kAnalyticsOptedOutReason =+ 'Tracking is switched off in ~/.harness/desktop-app/analytics.json.';++/// [Analytics] that records what was tracked and sends none of it.+///+/// Not a subclass of [QueuedAnalytics] with the transport stubbed out: this+/// must not touch [AnalyticsIdentityStore], so a muted build reads no Harness+/// home and mints no ids for a stream that will never carry them.+class MutedAnalytics implements Analytics {+ MutedAnalytics(this.recorder, this.reason, {this.clock = DateTime.now});++ final AnalyticsLog recorder;++ /// The sentence the Tracking screen puts on every row, and the one its header+ /// card leads with.+ final String reason;++ final DateTime Function() clock;++ @override+ void track(String name, {Map<String, Object?> params = const {}}) {+ // Settled the instant it is queued: there is no wire and no retry, so a row+ // that sat at "Waiting" would be describing a queue that does not exist.+ recorder.settled(+ recorder.queued(name, params, clock()),+ AnalyticsEventStatus.dropped,+ note: reason,+ );+ }++ @override+ Future<void> flush() async {}++ @override+ Future<void> close() async {}+}++/// What the Tracking screen's header card reports: where events go, whether+/// they are going at all, and the two ids they are filed under.+@immutable+class AnalyticsStreamStatus {+ const AnalyticsStreamStatus({+ required this.endpoint,+ required this.offReason,+ required this.deviceId,+ required this.sessionId,+ });++ final Uri endpoint;++ /// Why nothing is being sent, or null when the stream is live.+ final String? offReason;++ final String deviceId;++ /// Empty until the first event of a launch has been tracked.+ final String sessionId;++ bool get enabled => offReason == null;+}++/// Reads the live configuration and the ids on disk.+///+/// Injected into the Tracking screen the way `probeDebugEnvironment` is into+/// Settings ▸ Debug, and for the same reason: this reads a real `~/.harness`,+/// which a test must not.+///+/// The opt-out is checked here as well as in [_build] — a card that said+/// "Reporting" over a stream the user switched off would be the dishonest+/// label this screen exists to prevent.+AnalyticsStreamStatus probeAnalyticsStatus() {+ final config = AnalyticsConfig.resolve();+ final store = AnalyticsIdentityStore();+ final ids = store.peek();+ final optedOut = store.optedOut ? kAnalyticsOptedOutReason : null;+ return AnalyticsStreamStatus(+ endpoint: config.endpoint,+ offReason: config.offReason ?? optedOut,+ deviceId: ids.pseudoId,+ sessionId: ids.sessionId,+ );+}++/// Who events are filed under.+///+/// `AppNotifier` writes it when sign-in resolves and clears it on sign-out; the+/// queue reads it fresh per event, so a visit that begins signed out and ends+/// signed in is not reported as anonymous throughout.+final AnalyticsAccount analyticsAccount = AnalyticsAccount();++/// The signed-in account, as the wire wants it. Mutable and global on purpose —+/// see [analyticsAccount].+class AnalyticsAccount {+ ({String? id, String? email}) current = (id: null, email: null);++ void set({String? id, String? email}) => current = (id: id, email: email);++ void clear() => current = (id: null, email: null);+}++/// The machine and build an event happened on, resolved once per launch.+///+/// Never fails: a version lookup that throws costs those fields, not the+/// stream. The queue awaits this once, before its first send, so the first+/// event of a launch already carries the version rather than racing it.+Future<AnalyticsContext> resolveAnalyticsContext() async {+ var version = '';+ var build = '';+ try {+ final info = await PackageInfo.fromPlatform();+ version = info.version;+ build = info.buildNumber;+ } on Object {+ // A bundle we can't read is worth an anonymous version, not a lost event.+ }+ return AnalyticsContext(+ platform: Platform.operatingSystem,+ appVersion: version,+ appBuild: build,+ osVersion: Platform.operatingSystemVersion,+ arch: Abi.current().toString(),+ locale: Platform.localeName,+ release: kReleaseMode,+ );+}diff --git a/mobile/lib/api/access_token_source.dart b/mobile/lib/api/access_token_source.dartnew file mode 100644index 000000000..f0c9f6dd2--- /dev/null+++ b/mobile/lib/api/access_token_source.dart@@ -0,0 +1,6 @@+/// Hands out a usable SSO access token — refreshing first when it is stale, when [force]d, or when+/// the caller just had [failedToken] refused. Only a viewer build holds one; everywhere else the+/// harness CLI does, and signs the requests itself.+abstract interface class AccessTokenSource {+ Future<String> accessToken({bool force = false, String? failedToken});+}diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dartnew file mode 100644index 000000000..cd17ca6a5--- /dev/null+++ b/mobile/lib/api/api_client.dart@@ -0,0 +1,147 @@+import 'package:dio/dio.dart';++import '../auth/auth_session.dart';+import '../core/config.dart';+import '../core/models.dart';+import '../logging/http_log.dart';+import 'access_token_source.dart';+import 'bearer_auth_interceptor.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.+class ApiClient {+ final AppConfig config;+ final AuthSession session;+ final AccessTokenSource? auth;+ late final Dio _dio = _buildDio();++ ApiClient({required this.config, required this.session, this.auth});++ Dio _buildDio() {+ final dio = attachHttpLog(+ Dio(+ BaseOptions(+ baseUrl: auth == null ? config.localCliBaseUrl : config.apiBaseUrl,+ connectTimeout: const Duration(seconds: 15),+ receiveTimeout: const Duration(seconds: 30),+ // Let the API wrapper turn HTTP failures into short, user-facing+ // ApiExceptions. Transport failures still surface as DioExceptions.+ validateStatus: (status) =>+ status != null && status >= 200 && status < 600,+ ),+ ),+ );+ final source = auth;+ if (source != null) {+ dio.interceptors.add(+ BearerAuthInterceptor(source, dio, autonomousEnv: config.autonomousEnv),+ );+ }+ return dio;+ }++ // -- auth (proxied by the local CLI — no credential on this leg) --+ 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) --+ Future<List<Machine>> machines() async {+ final res = await _dio.get('/api/machines');+ final data = unwrapApiResponse(res) as Map<String, dynamic>;+ final list = data['machines'] as List<dynamic>? ?? [];+ return list+ .map((e) => Machine.fromJson(e as Map<String, dynamic>))+ .toList();+ }++ Future<String?> renameMachine({+ required String machineId,+ required String name,+ }) async {+ final res = await _dio.patch(+ '/api/machines/$machineId',+ data: {'name': name},+ options: Options(headers: {'x-adapter-local': '1'}),+ );+ final data = unwrapApiResponse(res) as Map<String, dynamic>;+ return data['name'] as String?;+ }++ Future<void> deleteMachine({required String machineId}) async {+ final res = await _dio.delete(+ '/api/machines/$machineId',+ options: Options(headers: {'x-adapter-local': '1'}),+ );+ unwrapApiResponse(res);+ }+}++class ApiException implements Exception {+ final String message;+ final int? status;+ ApiException(this.message, {this.status});+ @override+ String toString() => message;+}++bool isUnauthorizedError(Object error) =>+ error is DioException && error.response?.statusCode == 401 ||+ error is ApiException && error.status == 401;++/// Unwraps the backend's `{success, data, error}` envelope, which both legs+/// speak: the CLI's loopback server mirrors it, and the viewer's own auth calls+/// (`viewer/direct_auth_api.dart`) read it straight from the backend.+dynamic unwrapApiResponse(Response res) {+ final body = res.data;+ if (body is Map && body['success'] == true) {+ return body['data'];+ }+ final error = body is Map ? body['error'] : null;+ final serverMessage = error is Map ? error['message'] : null;+ throw ApiException(+ serverMessage is String && serverMessage.isNotEmpty+ ? serverMessage+ : 'Request failed (${res.statusCode})',+ status: res.statusCode,+ );+}++/// 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.+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.';+ 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.';+ case DioExceptionType.badResponse:+ return 'the local Harness service answered '+ '${error.response?.statusCode ?? 'with an error'}.';+ case DioExceptionType.badCertificate:+ case DioExceptionType.cancel:+ case DioExceptionType.transformTimeout:+ case DioExceptionType.unknown:+ return error.message ?? error.error?.toString() ?? 'request failed';+ }+ }+ return '$error';+}diff --git a/mobile/lib/api/bearer_auth_interceptor.dart b/mobile/lib/api/bearer_auth_interceptor.dartnew file mode 100644index 000000000..24f5f4f7f--- /dev/null+++ b/mobile/lib/api/bearer_auth_interceptor.dart@@ -0,0 +1,56 @@+import 'package:dio/dio.dart';++import 'access_token_source.dart';++/// Signs each request with the SSO bearer and the environment header the backend routes on, and+/// retries a 401 once with a refreshed token — for a viewer build, what the harness CLI's+/// `controlPlaneAuth` does for a desktop one.+class BearerAuthInterceptor extends Interceptor {+ BearerAuthInterceptor(this._auth, this._dio, {required this.autonomousEnv});++ final AccessTokenSource _auth;+ final Dio _dio;+ final String autonomousEnv;++ static const _tokenKey = 'bearer.token';+ static const _retriedKey = 'bearer.retried';++ @override+ Future<void> onRequest(+ RequestOptions options,+ RequestInterceptorHandler handler,+ ) async {+ try {+ final token = await _auth.accessToken();+ options.headers['authorization'] = 'Bearer $token';+ options.headers['x-autonomous-env'] = autonomousEnv;+ options.extra[_tokenKey] = token;+ handler.next(options);+ } catch (error) {+ handler.reject(DioException(requestOptions: options, error: error));+ }+ }++ @override+ Future<void> onResponse(+ Response<dynamic> response,+ ResponseInterceptorHandler handler,+ ) async {+ final options = response.requestOptions;+ if (response.statusCode != 401 || options.extra[_retriedKey] == true) {+ handler.next(response);+ return;+ }+ try {+ await _auth.accessToken(+ force: true,+ failedToken: options.extra[_tokenKey] as String?,+ );+ options.extra[_retriedKey] = true;+ handler.resolve(await _dio.fetch<dynamic>(options));+ } catch (_) {+ // The refresh itself failed, so the 401 is the honest answer to hand back.+ handler.next(response);+ }+ }+}diff --git a/mobile/lib/app_shell.dart b/mobile/lib/app_shell.dartnew file mode 100644index 000000000..c0ea4f1cb--- /dev/null+++ b/mobile/lib/app_shell.dart@@ -0,0 +1,314 @@+import 'dart:async';+import 'dart:ui' show AppExitResponse;++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_riverpod/flutter_riverpod.dart';++import 'analytics/analytics_lifecycle.dart';+import 'core/crash_log.dart';+import 'screens/login_screen.dart';+import 'state/app_state.dart';+import 'viewer/viewer_services.dart';+import 'ws/terminal_transport_plugin.dart';+import 'shared/theme/app_theme.dart' as grid;+import 'shared/theme/appearance_prefs_store.dart';+import 'terminal/terminal_font_store.dart';+import 'widgets/bootstrapping_screen.dart';+import 'widgets/layout_palette.dart';+import 'widgets/environment_preflight_screen.dart';+import 'widgets/environment_setup_screen.dart';+import 'widgets/flash_firmware_dialog.dart';+import 'core/startup.dart';+import 'logging/app_log.dart';+import 'logging/install.dart';+import 'shortcuts/app_keymap.dart';+import 'widgets/shortcuts_sheet.dart';+import 'widgets/update_notice.dart';++/// The screen an app puts up once someone is signed in — the desktop's swarm of+/// panes, or the phone's one-agent-at-a-time shell. It is the only thing the two+/// entry points disagree about; everything below is shared.+typedef AuthenticatedScreenBuilder = Widget Function(AppNotifier app);++/// Everything both entry points do before their first frame: file logs, the+/// crash log, the keyboard config, the saved appearance, and the native window+/// where there is one.+///+/// Lives here rather than in either `main.dart` so the two cannot drift — the+/// mobile app is a separate package (`../mobile`) that depends on this one, and+/// a second copy of this preamble is exactly how the last mobile build ended up+/// stranded from the desktop it shared a codebase with.+Future<void> startHarness({+ required AuthenticatedScreenBuilder authenticatedScreen,++ /// A viewer build's second wire to each machine (see+ /// [TerminalTransportPlugin]); the desktop passes none.+ TerminalTransportPluginFactory? transportPlugins,+}) async {+ WidgetsFlutterBinding.ensureInitialized();+ harnessTransportPlugins = transportPlugins;+ // Before anything else can fail. The file sinks come first so CrashLog's own+ // install has somewhere to mirror to — see CrashLog.record.+ installFileLogs();+ CrashLog.install();+ appLog.info('app', 'launched');+ final keymap = AppKeymap(store: AppKeymap.fileStore());+ // Keyboard configuration has its own file and watchers. It can load beside+ // the appearance, but both must be ready before the window becomes usable.+ await Future.wait([loadPersistedSettings(), keymap.start()]);+ runApp(+ ProviderScope(+ child: HarnessApp(+ keymap: keymap,+ authenticatedScreen: authenticatedScreen,+ ),+ ),+ );+}++class HarnessApp extends StatelessWidget {+ const HarnessApp({super.key, this.keymap, required this.authenticatedScreen});+ final AppKeymap? keymap;+ final AuthenticatedScreenBuilder authenticatedScreen;++ @override+ Widget build(BuildContext context) {+ // Rebuilds MaterialApp on a font/size change, which is what re-resolves+ // every Grid token with it.+ //+ // `buildAppTheme` bakes `AppControl.*Scaled` into plain numbers at the+ // moment it runs, so a UI size that changed without rebuilding this would+ // repaint nothing at all.+ return ValueListenableBuilder<AppearancePrefs>(+ valueListenable: appearancePrefsStore,+ builder: (context, prefs, _) => _app(prefs),+ );+ }++ Widget _app(AppearancePrefs prefs) {+ grid.AppTheme.palette.value = prefs.palette;+ // ⚠️ ORDER MATTERS, and it is why this is a statement rather than something+ // tucked into the tree below: `buildAppTheme` reads `AppFont.sans` and+ // `AppControl.*Scaled`, so the settings have to be on `AppFont` BEFORE the+ // theme is built, in this same frame.+ //+ // Pushed through the notifier rather than calling `AppFont.apply` directly,+ // so widgets past a `const` boundary — which a top-down rebuild never+ // reaches — are marked dirty too.+ //+ // `codeSize` is passed through unchanged: code type is not on this screen+ // yet, and `apply` takes the whole set, so reading the current value back is+ // how "leave it alone" is spelled.+ final scale = prefs.uiSize / grid.AppFont.uiSizeDefault;+ grid.AppTheme.fonts.apply(+ uiFamily: prefs.uiFamily,+ uiScale: scale,+ codeSize: grid.AppFont.codeSize,+ );+ return MaterialApp(+ title: 'Harness',+ debugShowCheckedModeBanner: false,+ // The design system's own `buildAppTheme` — see the note where a second,+ // hand-written `ThemeData` used to shadow it, in `lib/theme/app_theme.dart`.+ // Harness Desktop is dark-only: one theme, no `darkTheme`/`themeMode` to+ // resolve between.+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ // The UI size reaches every `Text` as a text SCALE rather than as hundreds+ // of edited call sites. `withClampedTextScaling` with both bounds equal IS+ // the way to force a factor — MediaQuery has no "set the scale"+ // constructor that still inherits the platform's other metrics.+ //+ // ⚠️ It is a matched pair with the `AppControl.*Scaled` reads above, not a+ // separate nicety: those grow the BOXES and this grows the TYPE, and+ // `AppControl.fontSize` deliberately has no scaled twin so that the factor+ // is applied exactly once. Ship one without the other and a 19px setting+ // gives 19px-tall buttons wrapped around 13pt labels.+ //+ // ⚠️ The terminal is fenced out of this at five seams — see+ // `terminal_panel.dart`, `terminal_composer.dart`, `engine_identity.dart`+ // and `terminal_section.dart`, and the regression test in+ // `test/terminal_ui_scale_isolation_test.dart`. The terminal keeps its own+ // font settings because its type is a grid a remote program draws into.+ //+ // Outermost inside `builder`, with `_GridTokenScope` inside it: the clamp+ // has to be an ancestor of everything that lays out text, while the scope+ // only reads `Theme.of`, which comes from above the builder either way.+ builder: (context, child) => MediaQuery.withClampedTextScaling(+ minScaleFactor: scale,+ maxScaleFactor: scale,+ child: _GridTokenScope(+ child: keymap == null+ ? child ?? const SizedBox.shrink()+ : KeymapProvider(+ keymap: keymap!,+ child: child ?? const SizedBox.shrink(),+ ),+ ),+ ),+ home: AnalyticsLifecycle(+ child: RootShell(authenticatedScreen: authenticatedScreen),+ ),+ );+ }+}++/// Carries Grid's design tokens past this app's `const` chrome.+///+/// A `const` widget is reference-identical across its parent's rebuild, so a+/// top-down rebuild never reaches one — it would keep the palette it first+/// mounted with. [grid.BrightnessScope] marks the ones that called+/// `AppTheme.watch` dirty directly, across that boundary.+///+/// Pinned to [Brightness.dark] rather than read from `Theme.of(context)`:+/// Harness Desktop is dark-only, and there is no other theme for `Theme.of`+/// to ever resolve to here.+class _GridTokenScope extends StatelessWidget {+ const _GridTokenScope({required this.child});++ final Widget child;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.brightness.value = Brightness.dark;+ return grid.BrightnessScope(child: child);+ }+}++/// Carries "Check for Updates…" from the macOS application menu into Dart.+///+/// The item is installed natively (MainFlutterWindow.swift) so the rest of the+/// menu bar keeps coming from the nib; all this side does is act on the tap.+const _appMenuChannel = MethodChannel('harness/app_menu');++class RootShell extends ConsumerStatefulWidget {+ const RootShell({super.key, required this.authenticatedScreen});++ final AuthenticatedScreenBuilder authenticatedScreen;++ @override+ ConsumerState<RootShell> createState() => _RootShellState();+}++class _RootShellState extends ConsumerState<RootShell>+ with WidgetsBindingObserver {+ bool _menuDialogOpen = false;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ _appMenuChannel.setMethodCallHandler(_onAppMenu);+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ _appMenuChannel.setMethodCallHandler(null);+ super.dispose();+ }++ @override+ Future<AppExitResponse> didRequestAppExit() async {+ // Save the final arrangement, with a bound so an unavailable disk cannot+ // trap the user in the app. Input and tab switching never wait for disk.+ await ref+ .read(appStateProvider)+ .flushPaneLayout()+ .timeout(const Duration(seconds: 1), onTimeout: () {});+ return AppExitResponse.exit;+ }++ Future<void> _onAppMenu(MethodCall call) async {+ if (!mounted) return;+ switch (call.method) {+ case 'checkForUpdates':+ final app = ref.read(appStateProvider);+ await _menuDialog(() async {+ final result = await app.checkForUpdates();+ if (!mounted) return;+ await showUpdateCheckDialog(context, app, result);+ });+ case 'flashFirmware':+ await _menuDialog(() => showFlashFirmwareDialog(context));+ case 'showLayout':+ if (advanceLayoutPalette()) return;+ await _menuDialog(+ () => showLayoutPalette(context, ref.read(appStateProvider)),+ );+ case 'showShortcuts':+ await _menuDialog(() => showShortcutsSheet(context));+ case 'increaseTerminalFontSize':+ await terminalFontStore.increaseSize();+ case 'decreaseTerminalFontSize':+ await terminalFontStore.decreaseSize();+ case 'resetTerminalFontSize':+ await terminalFontStore.reset();+ }+ }++ Future<void> _menuDialog(Future<void> Function() action) async {+ if (_menuDialogOpen || ModalRoute.isCurrentOf(context) == false) return;+ // Reserve before the first frame too: held menu shortcuts can arrive+ // before the new dialog has changed the route's current state.+ _menuDialogOpen = true;+ try {+ await action();+ } finally {+ _menuDialogOpen = false;+ }+ }++ @override+ Widget build(BuildContext context) {+ final app = ref.watch(appStateProvider);+ return ListenableBuilder(+ listenable: app,+ builder: (context, _) {+ final Widget screen;+ switch (app.status) {+ case AppStatus.bootstrapping:+ // `bootstrapping` covers two unrelated moments: the app starting+ // cold, and a sign-in the user just began. The second keeps+ // LoginScreen, which carries the wait as a state of its own+ // button; swapping the window for a separate screen there was a+ // hard cut in the middle of a flow, and it is why that button's+ // spinner was almost never seen.+ //+ // ⚠️ Keyed on `signingIn`, NOT on `pendingAuthorizeUrl`. The URL+ // only exists for the middle stretch of the flow — the CLI has to+ // start before it can print one, and it is cleared again while+ // the post-login restore is still running — so keying on it blew+ // the user's own screen away twice per sign-in: once on the click+ // and again on success.+ screen = app.signingIn+ ? LoginScreen(notifier: app)+ : BootstrappingScreen(statusMessage: app.bootStatusMessage);+ case AppStatus.checkingEnvironment:+ screen = EnvironmentPreflightScreen(+ readiness: app.environmentReadiness,+ );+ case AppStatus.preparingEnvironment:+ screen = EnvironmentSetupScreen(notifier: app);+ case AppStatus.unauthenticated:+ screen = LoginScreen(notifier: app);+ case AppStatus.authenticated:+ screen = widget.authenticatedScreen(app);+ }+ // The band takes a row of its own rather than floating over one. As an+ // overlay it landed on the screen's own head — covering the controls+ // along the top edge, which is the one strip that must stay reachable.+ return Column(+ children: [+ if (app.hasAvailableUpdate &&+ app.status != AppStatus.bootstrapping &&+ app.status != AppStatus.checkingEnvironment &&+ app.status != AppStatus.preparingEnvironment)+ UpdateNotice(notifier: app),+ Expanded(child: screen),+ ],+ );+ },+ );+ }+}diff --git a/mobile/lib/auth/auth_session.dart b/mobile/lib/auth/auth_session.dartnew file mode 100644index 000000000..a0d10af05--- /dev/null+++ b/mobile/lib/auth/auth_session.dart@@ -0,0 +1,78 @@+import '../core/harness_file_store.dart';+import '../core/local_key_value_store.dart';++/// Persists the SSO access + refresh tokens in the Desktop Harness state file.+class AuthSession {+ final LocalKeyValueStore _storage;+ static const _access = 'auth_access_token';+ static const _refresh = 'auth_refresh_token';+ static const _env = 'auth_autonomous_env';+ static const _expiresAt = 'auth_access_token_expires_at';++ AuthSession({LocalKeyValueStore? storage})+ : _storage = storage ?? HarnessFileStore.shared;++ /// Store a newly authenticated session. A missing refresh token clears any+ /// stale token left by a previous account/environment.+ Future<void> saveLogin({+ required String token,+ String? refreshToken,+ String autonomousEnv = 'prod',+ int? expiresIn,+ }) async {+ await _storage.write(_access, token);+ if (refreshToken != null && refreshToken.isNotEmpty) {+ await _storage.write(_refresh, refreshToken);+ } else {+ await _storage.delete(_refresh);+ }+ await _storage.write(_env, autonomousEnv);+ await _saveExpiry(expiresIn);+ }++ /// Store a refreshed access token. Identity providers do not always rotate+ /// the refresh token, so retain the current one when it is omitted.+ Future<void> saveRefresh({+ required String token,+ String? refreshToken,+ required String autonomousEnv,+ int? expiresIn,+ }) async {+ await _storage.write(_access, token);+ if (refreshToken != null && refreshToken.isNotEmpty) {+ await _storage.write(_refresh, refreshToken);+ }+ await _storage.write(_env, autonomousEnv);+ await _saveExpiry(expiresIn);+ }++ Future<String?> accessToken() => _storage.read(_access);+ Future<String?> refreshToken() => _storage.read(_refresh);+ Future<String> autonomousEnv() async => (await _storage.read(_env)) ?? 'prod';+ Future<DateTime?> accessTokenExpiresAt() async {+ final raw = await _storage.read(_expiresAt);+ final milliseconds = int.tryParse(raw ?? '');+ return milliseconds == null+ ? null+ : DateTime.fromMillisecondsSinceEpoch(milliseconds, isUtc: true);+ }++ Future<void> _saveExpiry(int? expiresIn) async {+ if (expiresIn == null || expiresIn <= 0) {+ await _storage.delete(_expiresAt);+ return;+ }+ final expiresAt = DateTime.now().toUtc().add(Duration(seconds: expiresIn));+ await _storage.write(+ _expiresAt,+ expiresAt.millisecondsSinceEpoch.toString(),+ );+ }++ Future<void> clear() async {+ await _storage.delete(_access);+ await _storage.delete(_refresh);+ await _storage.delete(_env);+ await _storage.delete(_expiresAt);+ }+}diff --git a/mobile/lib/auth/cli_link.dart b/mobile/lib/auth/cli_link.dartnew file mode 100644index 000000000..ec9986d5d--- /dev/null+++ b/mobile/lib/auth/cli_link.dart@@ -0,0 +1,363 @@+import 'dart:convert';+import 'dart:io';++import '../core/harness_cli_runner.dart';+import 'peer_link_client.dart';++/// Result of `harness remote-password set --stdin --json` — sets (or replaces) this machine's+/// persistent remote password, the shared secret another machine's `harness link connect` PAKE+/// handshake authenticates against. The app never sees the password's cryptographic use, only+/// pipes it to the CLI on stdin, the same as typing it at a terminal prompt would.+class RemotePasswordSetResult {+ /// Null on success.+ final String? error;++ /// This machine's fingerprint after the password is set — shown so the user can verify it+ /// matches on the connecting side.+ final String? fingerprint;++ const RemotePasswordSetResult({this.error, this.fingerprint});+}++/// Result of `harness remote-password status --json`.+class RemotePasswordStatus {+ /// Null on success. A query failure, not "no password set" — that's [hasPassword] false.+ final String? error;+ final bool hasPassword;+ final String? fingerprint;+ final DateTime? setAt;++ const RemotePasswordStatus({+ this.error,+ this.hasPassword = false,+ this.fingerprint,+ this.setAt,+ });+}++/// Result of `harness link connect <machineId> --stdin --json` — the password-authenticated+/// replacement for the old token-based `import`.+class CliLinkConnectResult {+ /// Null on success.+ final String? error;++ /// The machineId the CLI actually linked — echoed back from its own success line. Null if+ /// [error] is set, or if the CLI's output didn't match the expected shape.+ final String? linkedMachineId;++ /// The linked machine's fingerprint, for the user to verify.+ final String? fingerprint;++ const CliLinkConnectResult({+ this.error,+ this.linkedMachineId,+ this.fingerprint,+ });+}++/// One row of `harness link list`.+class LinkedMachine {+ final String machineId;+ final String fingerprint;++ /// As printed by the CLI: `YYYY-MM-DD HH:MM`.+ final String linkedAt;++ const LinkedMachine({+ required this.machineId,+ required this.fingerprint,+ required this.linkedAt,+ });+}++class CliLinkListResult {+ /// Null on success (an empty list is success with zero rows, not an error).+ final String? error;+ final List<LinkedMachine> machines;++ const CliLinkListResult({this.error, this.machines = const []});+}++class CliLink implements PeerLinkClient {+ final HarnessCliRunner _runner;++ CliLink({HarnessCliRunner? runner}) : _runner = runner ?? HarnessCliRunner();+ static final _listRowPattern = RegExp(+ r'^\s*\d+\.\s+(\S+)\s+(\S+)\s+\(linked\s+([\d-]+\s[\d:]+)\)',+ multiLine: true,+ );++ /// Sets (or replaces) this machine's persistent remote password. Stays valid until changed —+ /// there is no expiry, unlike the old 7-day link tokens.+ Future<RemotePasswordSetResult> setRemotePassword(String password) async {+ final invocation = await _runStdinNdjson(+ ['remote-password', 'set', '--stdin', '--json'],+ password,+ label: 'harness remote-password set',+ );+ if (invocation.error != null) {+ return RemotePasswordSetResult(error: invocation.error);+ }+ final json = invocation.result!;+ if (json['ok'] == true) {+ return RemotePasswordSetResult(+ fingerprint: json['fingerprint'] as String?,+ );+ }+ return RemotePasswordSetResult(+ error: json['error'] as String? ?? 'harness remote-password set failed',+ );+ }++ /// Whether this machine currently has a remote password set, and its fingerprint/set time.+ Future<RemotePasswordStatus> remotePasswordStatus() async {+ final invocation = await _runJson([+ 'remote-password',+ 'status',+ '--json',+ ], label: 'harness remote-password status');+ if (invocation.error != null) {+ return RemotePasswordStatus(error: invocation.error);+ }+ final json = invocation.result!;+ final setAtMs = json['setAt'];+ return RemotePasswordStatus(+ hasPassword: json['hasPassword'] == true,+ fingerprint: json['fingerprint'] as String?,+ setAt: setAtMs is num+ ? DateTime.fromMillisecondsSinceEpoch(setAtMs.toInt())+ : null,+ );+ }++ /// Clears this machine's remote password, revoking remote access for anyone who knew it. Null+ /// on success.+ Future<String?> clearRemotePassword() async {+ final invocation = await _runJson([+ 'remote-password',+ 'clear',+ '--json',+ ], label: 'harness remote-password clear');+ if (invocation.error != null) return invocation.error;+ final json = invocation.result!;+ if (json['ok'] == true) return null;+ return json['error'] as String? ?? 'harness remote-password clear failed';+ }++ /// Connects to [machineId] using the password set with `setRemotePassword` on THAT machine —+ /// the password-authenticated replacement for the old token `import`. [onProgress], if given,+ /// is called with each stage name the CLI reports (`connecting`, `deriving_key`, `exchanging`,+ /// `verifying`) as the handshake proceeds; best-effort UI feedback only, never required for+ /// correctness. [displayName], when given, is how the CLI's error messages name the machine —+ /// otherwise they show the raw [machineId], which is all a terminal user would have.+ @override+ Future<CliLinkConnectResult> connect(+ String machineId,+ String password, {+ void Function(String stage)? onProgress,+ String? displayName,+ }) async {+ final invocation = await _runStdinNdjson(+ [+ 'link',+ 'connect',+ machineId,+ '--stdin',+ '--json',+ if (displayName != null && displayName.isNotEmpty)+ '--name=$displayName',+ ],+ password,+ label: 'harness link connect',+ onLine: (json) {+ final stage = json['stage'];+ if (stage is String) onProgress?.call(stage);+ },+ );+ if (invocation.error != null) {+ return CliLinkConnectResult(error: invocation.error);+ }+ final json = invocation.result!;+ if (json['ok'] == true) {+ return CliLinkConnectResult(+ linkedMachineId: json['machineId'] as String? ?? machineId,+ fingerprint: json['fingerprint'] as String?,+ );+ }+ // `message` is the CLI's human sentence for the code (what it prints without --json); `error`+ // is the bare code and only a fallback for a CLI too old to send one.+ return CliLinkConnectResult(+ error:+ json['message'] as String? ??+ json['error'] as String? ??+ 'harness link connect failed',+ );+ }++ /// Machines this one currently trusts (CLI-to-CLI, not the browser-pairing list).+ @override+ Future<CliLinkListResult> list() async {+ final response = await _run(['link', 'list']);+ if (response.error != null) {+ return CliLinkListResult(error: response.error);+ }+ final result = response.result!;+ final stdoutText = (result.stdout as String).trim();+ if (result.exitCode != 0) {+ return CliLinkListResult(+ error: _errorMessage(result, stdoutText, 'harness link list'),+ );+ }+ return CliLinkListResult(+ machines: [+ for (final m in _listRowPattern.allMatches(stdoutText))+ LinkedMachine(+ machineId: m.group(1)!,+ fingerprint: m.group(2)!,+ linkedAt: m.group(3)!,+ ),+ ],+ );+ }++ /// Removes a linked machine's trust pin. Null on success.+ @override+ Future<String?> unlink(String machineId) async {+ final response = await _run(['link', 'unlink', machineId]);+ if (response.error != null) return response.error;+ final result = response.result!;+ if (result.exitCode == 0) return null;+ return _errorMessage(+ result,+ (result.stdout as String).trim(),+ 'harness link unlink',+ );+ }++ String _errorMessage(+ ProcessResult result,+ String stdoutText,+ String command,+ ) {+ final stderrText = (result.stderr as String).trim();+ final message = stderrText.isNotEmpty ? stderrText : stdoutText;+ return message.isEmpty+ ? '$command failed (exit ${result.exitCode})'+ : message;+ }++ Future<_CliInvocation> _run(List<String> arguments) async {+ try {+ return _CliInvocation(result: await _runner.run(arguments));+ } on ProcessException catch (error) {+ return _CliInvocation(+ error: 'Could not run the Harness CLI: ${error.message}',+ );+ }+ }++ /// One-shot NDJSON invocation (no stdin) — spawns [arguments], runs to completion, and returns+ /// the last valid JSON line decoded (a one-shot `--json` command prints exactly one such line —+ /// `{"ok":true,...}` / `{"ok":false,"error":...}`, or a bare status object with no `ok` key for+ /// commands like `remote-password status` that always succeed if they ran at all), or an error+ /// if the CLI could not be run or never produced a JSON line.+ Future<_ResultInvocation> _runJson(+ List<String> arguments, {+ required String label,+ }) async {+ final response = await _run(arguments);+ if (response.error != null) return _ResultInvocation(error: response.error);+ final result = response.result!;+ final stdoutText = result.stdout as String;+ Map<String, dynamic>? resultJson;+ for (final raw in stdoutText.split('\n')) {+ final line = raw.trim();+ if (line.isEmpty) continue;+ Map<String, dynamic> json;+ try {+ json = jsonDecode(line) as Map<String, dynamic>;+ } catch (_) {+ continue;+ }+ resultJson = json;+ }+ if (resultJson == null) {+ return _ResultInvocation(+ error: _errorMessage(result, stdoutText.trim(), label),+ );+ }+ return _ResultInvocation(result: resultJson);+ }++ /// Streaming NDJSON invocation with piped stdin — spawns [arguments], writes [stdinLine]+ /// followed by a newline, closes stdin, then streams NDJSON off stdout: a line carrying a+ /// `stage` key is a progress event and goes to [onLine]; every other valid JSON line is a+ /// candidate final result (the last one wins — `link connect`/`remote-password set` print+ /// exactly one such line, `{"ok":true,...}` or `{"ok":false,"error":...}`). Mirrors+ /// `CliLogin.login()`'s NDJSON-over-stdout parsing style, plus the stdin write this app's other+ /// CLI invocations don't need.+ Future<_ResultInvocation> _runStdinNdjson(+ List<String> arguments,+ String stdinLine, {+ required String label,+ void Function(Map<String, dynamic> json)? onLine,+ }) async {+ final Process process;+ try {+ process = await _runner.start(arguments);+ } on ProcessException catch (error) {+ return _ResultInvocation(+ error: 'Could not run the Harness CLI: ${error.message}',+ );+ }+ // Drained unconditionally: an unread stderr pipe can fill its OS buffer and block the child+ // process from writing more output at all, which would otherwise look exactly like a hang.+ process.stderr.drain<void>();+ process.stdin.writeln(stdinLine);+ await process.stdin.close();+ Map<String, dynamic>? resultJson;+ final lines = process.stdout+ .transform(utf8.decoder)+ .transform(const LineSplitter());+ await for (final raw in lines) {+ final line = raw.trim();+ if (line.isEmpty) continue;+ Map<String, dynamic> json;+ try {+ json = jsonDecode(line) as Map<String, dynamic>;+ } catch (_) {+ continue;+ }+ if (json.containsKey('stage')) {+ onLine?.call(json);+ } else {+ resultJson = json;+ }+ }+ final exitCode = await process.exitCode;+ if (resultJson == null) {+ return _ResultInvocation(+ error: exitCode != 0+ ? '$label failed (exit $exitCode)'+ : '$label produced no result',+ );+ }+ return _ResultInvocation(result: resultJson);+ }+}++class _CliInvocation {+ final ProcessResult? result;+ final String? error;++ const _CliInvocation({this.result, this.error})+ : assert((result == null) != (error == null));+}++class _ResultInvocation {+ final Map<String, dynamic>? result;+ final String? error;++ const _ResultInvocation({this.result, this.error})+ : assert((result == null) != (error == null));+}diff --git a/mobile/lib/auth/cli_login.dart b/mobile/lib/auth/cli_login.dartnew file mode 100644index 000000000..4a3690c94--- /dev/null+++ b/mobile/lib/auth/cli_login.dart@@ -0,0 +1,168 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import '../core/harness_cli_runner.dart';+import 'sign_in_client.dart';++class CliAuthStatus {+ final bool loggedIn;+ final String? computerId;+ final String? machineId;+ final String? autonomousEnv;++ const CliAuthStatus({+ required this.loggedIn,+ this.computerId,+ this.machineId,+ this.autonomousEnv,+ });++ factory CliAuthStatus.fromJson(Map<String, dynamic> json) => CliAuthStatus(+ loggedIn: json['loggedIn'] == true,+ computerId: json['computerId'] as String?,+ machineId: json['machineId'] as String?,+ autonomousEnv: json['autonomousEnv'] as String?,+ );+}++/// Thrown when the `harness` CLI itself could not be run at all (the managed+/// runtime, installed launcher, and PATH are all unavailable) — distinct from+/// the CLI running fine and reporting "not signed in".+class CliNotAvailableException implements Exception {+ final String message;+ CliNotAvailableException(this.message);+ @override+ String toString() => message;+}++/// Talks to the local `harness` CLI for everything auth-related: whether this computer already has a+/// signed-in session, and driving `harness login --json`'s NDJSON event stream when it does not. The+/// CLI owns the SSO session end to end (`~/.harness/auth/session.json`) — this app never sees, stores,+/// or refreshes an access token itself.+class CliLogin implements SignInClient {+ final HarnessCliRunner _runner;+ Process? _activeProcess;+ int _loginRevision = 0;++ CliLogin({HarnessCliRunner? runner}) : _runner = runner ?? HarnessCliRunner();++ @override+ Future<CliAuthStatus> checkStatus() async {+ final result = await _run(['auth', 'status', '--json']);+ final line = _lastNonEmptyLine(result.stdout as String);+ if (line == null) {+ throw CliNotAvailableException(+ 'Could not run the harness CLI (${(result.stderr as String).trim().isEmpty ? 'exit ${result.exitCode}' : (result.stderr as String).trim()}). '+ 'Make sure it is installed and try again.',+ );+ }+ return CliAuthStatus.fromJson(jsonDecode(line) as Map<String, dynamic>);+ }++ /// Runs `harness login --force --json`. This is only ever reached from [LoginScreen], i.e. the app+ /// has already decided this computer is signed out — so a stale-but-present session file on disk+ /// must not short-circuit into a silent refresh attempt (`loginCommand`'s `readAuthSession() &&+ /// !force` branch), which just re-reports the same failure forever instead of opening a fresh SSO+ /// flow. Calls [onAuthorizeUrl] as soon as the CLI reports the SSO page to show, then resolves once+ /// the CLI's own loopback callback server completes the flow (or throws on failure/cancellation).+ /// The process is killed if [cancel] is called while this is in flight.+ @override+ Future<void> login({+ required void Function(String url) onAuthorizeUrl,+ }) async {+ // A cancelled spawn can finish after a replacement login has started.+ // Each process owns only its attempt, including its eventual cleanup.+ final revision = ++_loginRevision;+ final Process process;+ try {+ process = await _runner.start(['login', '--force', '--json']);+ } catch (error) {+ throw CliNotAvailableException('Could not run the harness CLI: $error');+ }+ if (revision != _loginRevision) {+ unawaited(process.stdout.drain<void>());+ unawaited(process.stderr.drain<void>());+ process.kill();+ throw StateError('Sign-in was cancelled.');+ }+ _activeProcess = process;+ // Drained unconditionally: an unread stderr pipe can fill its OS buffer and block the child+ // process from writing more output at all, which would otherwise look exactly like a hang here.+ process.stderr.drain<void>();+ try {+ final lines = process.stdout+ .transform(utf8.decoder)+ .transform(const LineSplitter());+ var gotResult = false;+ var success = false;+ String? message;+ await for (final raw in lines) {+ if (revision != _loginRevision) continue;+ final line = raw.trim();+ if (line.isEmpty) continue;+ Map<String, dynamic> json;+ try {+ json = jsonDecode(line) as Map<String, dynamic>;+ } catch (_) {+ continue;+ }+ switch (json['type']) {+ case 'authorize_url':+ final url = json['url'];+ if (url is String) onAuthorizeUrl(url);+ case 'result':+ gotResult = true;+ success = json['status'] == 'success';+ message = json['message'] as String?;+ }+ }+ final exitCode = await process.exitCode;+ if (revision != _loginRevision) {+ throw StateError('Sign-in was cancelled.');+ }+ if (!gotResult || !success) {+ throw StateError(+ message ??+ (exitCode != 0+ ? 'Sign-in was cancelled.'+ : 'Sign-in did not complete.'),+ );+ }+ } finally {+ if (identical(_activeProcess, process)) _activeProcess = null;+ }+ }++ /// Aborts this attempt even if its process has not finished starting yet —+ /// reached from the embedded sign-in webview's close button.+ @override+ void cancel() {+ ++_loginRevision;+ final process = _activeProcess;+ _activeProcess = null;+ process?.kill();+ }++ @override+ Future<void> logout() async {+ try {+ await _run(['logout']);+ } catch (_) {+ // Best-effort: local app state is cleared regardless by the caller.+ }+ }++ Future<ProcessResult> _run(List<String> arguments) async {+ try {+ return await _runner.run(arguments);+ } catch (error) {+ throw CliNotAvailableException('Could not run the harness CLI: $error');+ }+ }++ String? _lastNonEmptyLine(String stdout) {+ final lines = stdout.trim().split('\n').where((l) => l.trim().isNotEmpty);+ return lines.isEmpty ? null : lines.last.trim();+ }+}diff --git a/mobile/lib/auth/link_errors.dart b/mobile/lib/auth/link_errors.dartnew file mode 100644index 000000000..7b5d20c98--- /dev/null+++ b/mobile/lib/auth/link_errors.dart@@ -0,0 +1,49 @@+/// cli.ts `humanizeLinkError`: a password-link failure code as the sentence to show. Every branch,+/// the fallback included, wraps the code in words — a bare code must never reach the screen.+String humanizeLinkError(String code, String machineId, {DateTime? retryAt}) {+ if (code == 'RATE_LIMITED') {+ if (retryAt == null) {+ return 'Too many wrong attempts on $machineId. Wait a few minutes and try again.';+ }+ final minutes = (retryAt.difference(DateTime.now()).inSeconds / 60).ceil();+ return minutes > 0+ ? 'Too many wrong attempts on $machineId. Try again in $minutes minute${minutes == 1 ? '' : 's'}.'+ : 'Too many wrong attempts on $machineId. Try again now.';+ }+ const closedPrefix = 'CONNECTION_CLOSED:';+ if (code.startsWith(closedPrefix)) {+ return 'The connection closed unexpectedly (code ${code.substring(closedPrefix.length)}) '+ 'before linking finished. Try again.';+ }+ return switch (code) {+ 'NO_REMOTE_PASSWORD' =>+ 'Machine $machineId has no remote password set. Ask its operator to run '+ '`harness remote-password set` there first.',+ 'BAD_INTENT' =>+ 'The connection request was malformed — this usually means a version mismatch. '+ 'Update harness on both machines and try again.',+ 'WRONG_PASSWORD' =>+ 'That password is wrong. Check it against the other machine and try again.',+ 'TIMEOUT' =>+ "Machine $machineId didn't respond in time. Make sure it's running `harness start` "+ 'and reachable, then try again.',+ 'SEND_FAILED' =>+ 'Could not reach the relay to start linking. Check your network connection and try again.',+ 'DERIVE_FAILED' =>+ 'Could not process the password locally. Try again; if it persists, restart the app and retry.',+ 'SELECT_FAILED' =>+ "Could not find machine $machineId, or it isn't reachable right now. Check that it has "+ 'run `harness start`.',+ 'PAIR_FAILED' =>+ "Linking failed on $machineId's side. Try again; if it persists, check its status there "+ 'with `harness status`.',+ 'PROTOCOL_ERROR' =>+ 'Something unexpected happened during the handshake. Try again; if it persists, update '+ 'harness on the other machine.',+ 'CONNECTION_ERROR' =>+ 'Could not reach the relay. Check your network connection and try again.',+ _ =>+ 'Linking failed ($code). Try again; if it persists, check the other machine is on the '+ 'latest harness version.',+ };+}diff --git a/mobile/lib/auth/peer_link_client.dart b/mobile/lib/auth/peer_link_client.dartnew file mode 100644index 000000000..eb0976fa3--- /dev/null+++ b/mobile/lib/auth/peer_link_client.dart@@ -0,0 +1,21 @@+import 'cli_link.dart';++/// Linking to another machine by its remote password: `harness link connect/list/unlink` through+/// [CliLink], or the same exchange run by the app itself in a viewer build+/// (`viewer/direct_link.dart`).+abstract interface class PeerLinkClient {+ /// [onProgress] gets the CLI's stage names (`connecting`, `deriving_key`, `exchanging`,+ /// `verifying`) — best-effort feedback, never needed for correctness. [displayName] is how an+ /// error names the machine; without it, all an error has to go on is the raw [machineId].+ Future<CliLinkConnectResult> connect(+ String machineId,+ String password, {+ void Function(String stage)? onProgress,+ String? displayName,+ });++ Future<CliLinkListResult> list();++ /// Null on success.+ Future<String?> unlink(String machineId);+}diff --git a/mobile/lib/auth/sign_in_client.dart b/mobile/lib/auth/sign_in_client.dartnew file mode 100644index 000000000..70c80835c--- /dev/null+++ b/mobile/lib/auth/sign_in_client.dart@@ -0,0 +1,16 @@+import 'cli_login.dart';++/// Whether the app is signed in, and how it signs in — the seam between the two kinds of build.+///+/// [CliLogin] asks the local harness CLI, which holds the session. A viewer build has no CLI and+/// holds its own (`viewer/direct_login.dart`).+abstract interface class SignInClient {+ Future<CliAuthStatus> checkStatus();++ /// Resolves once signed in; throws on failure or [cancel]. [onAuthorizeUrl] gets the SSO page.+ Future<void> login({required void Function(String url) onAuthorizeUrl});++ void cancel();++ Future<void> logout();+}diff --git a/mobile/lib/bootstrap/environment_provisioner.dart b/mobile/lib/bootstrap/environment_provisioner.dartnew file mode 100644index 000000000..54855408d--- /dev/null+++ b/mobile/lib/bootstrap/environment_provisioner.dart@@ -0,0 +1,1612 @@+import '../core/host_platform.dart';+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import '../core/harness_cli_runner.dart';++/// The CLI-only installer contract for callers that already own host setup.+/// Desktop verifies system tools, the active Linux clipboard helper and tmux+/// before reaching this command, then performs its own complete verification+/// again after Harness lands.+const String kHarnessDesktopInstallCommand =+ 'curl -fsSL https://cdn.autonomous.ai/harness/cli/install.sh | '+ '/bin/sh -s -- --desktop';++const int _linuxClockSyncFailureExitCode = 31;+const int _linuxAptUpdateFailureExitCode = 32;+const int _linuxAptInstallFailureExitCode = 33;+const String _linuxClockRepairCommand =+ 'if command -v chronyc >/dev/null 2>&1; then '+ 'sudo chronyc makestep; else sudo timedatectl set-ntp true && '+ 'sudo systemctl restart systemd-timesyncd; fi';++enum EnvironmentStep {+ clipboard,+ harness,+ tmux;++ /// Harness Desktop is only ready when every command in this list works.+ bool get isRequired => true;+}++enum EnvironmentSetupPhase {+ preflight,+ review,+ chooseMethod,+ installing,+ waitingForTerminal,+ verifying,+ ready,+ failed,+}++enum EnvironmentSetupMode { automatic, manual }++/// Identifies which host setup owns a visible Terminal handoff. Linux can wait+/// on base/clipboard packages even when tmux itself is already ready, so a+/// resumed failure must not always be attributed to the tmux row.+enum EnvironmentTerminalSetup { linuxHost, tmux }++class EnvironmentFailure {+ final EnvironmentStep? step;+ final String title;+ final String detail;+ final String? command;+ final int? exitCode;++ const EnvironmentFailure({+ this.step,+ required this.title,+ required this.detail,+ this.command,+ this.exitCode,+ });+}++enum EnvironmentStepStatus {+ pending,+ running,+ ready,+ needsTerminal,+ failed,++ /// This host has no native clipboard to prepare (for example, headless+ /// Linux). Unlike [unavailable], this is a satisfied, non-blocking state.+ notApplicable,++ /// The host does not support this dependency. All current steps are required,+ /// so this status remains blocking.+ unavailable,+}++class EnvironmentReadiness {+ final Map<EnvironmentStep, EnvironmentStepStatus> steps;+ final String? message;+ final List<String> output;+ final EnvironmentSetupPhase phase;+ final EnvironmentSetupMode? mode;+ final EnvironmentFailure? failure;+ final String? terminalLogPath;+ final String? terminalResultPath;+ final EnvironmentTerminalSetup? terminalSetup;+ final bool systemReady;+ final bool? homebrewReady;+ final bool? tmuxBinaryReady;+ final List<String> missingLinuxPackages;++ const EnvironmentReadiness({+ required this.steps,+ this.message,+ this.output = const [],+ this.phase = EnvironmentSetupPhase.preflight,+ this.mode,+ this.failure,+ this.terminalLogPath,+ this.terminalResultPath,+ this.terminalSetup,+ this.systemReady = false,+ this.homebrewReady,+ this.tmuxBinaryReady,+ this.missingLinuxPackages = const [],+ });++ factory EnvironmentReadiness.initial() => EnvironmentReadiness(+ steps: {+ for (final step in EnvironmentStep.values)+ step: EnvironmentStepStatus.pending,+ },+ );++ bool get isReady =>+ systemReady &&+ steps.values.every(+ (status) =>+ status == EnvironmentStepStatus.ready ||+ status == EnvironmentStepStatus.notApplicable,+ );++ bool get needsTerminal =>+ phase == EnvironmentSetupPhase.waitingForTerminal ||+ steps.values.any(+ (status) => status == EnvironmentStepStatus.needsTerminal,+ );++ EnvironmentReadiness copyWith({+ Map<EnvironmentStep, EnvironmentStepStatus>? steps,+ String? message,+ List<String>? output,+ EnvironmentSetupPhase? phase,+ EnvironmentSetupMode? mode,+ EnvironmentFailure? failure,+ String? terminalLogPath,+ String? terminalResultPath,+ EnvironmentTerminalSetup? terminalSetup,+ bool? systemReady,+ bool? homebrewReady,+ bool? tmuxBinaryReady,+ List<String>? missingLinuxPackages,+ bool clearFailure = false,+ bool clearTerminalHandoff = false,+ }) => EnvironmentReadiness(+ steps: steps ?? this.steps,+ message: message ?? this.message,+ output: output ?? this.output,+ phase: phase ?? this.phase,+ mode: mode ?? this.mode,+ failure: clearFailure ? null : failure ?? this.failure,+ terminalLogPath: clearTerminalHandoff+ ? null+ : terminalLogPath ?? this.terminalLogPath,+ terminalResultPath: clearTerminalHandoff+ ? null+ : terminalResultPath ?? this.terminalResultPath,+ terminalSetup: clearTerminalHandoff+ ? null+ : terminalSetup ?? this.terminalSetup,+ systemReady: systemReady ?? this.systemReady,+ homebrewReady: homebrewReady ?? this.homebrewReady,+ tmuxBinaryReady: tmuxBinaryReady ?? this.tmuxBinaryReady,+ missingLinuxPackages: missingLinuxPackages ?? this.missingLinuxPackages,+ );+}++typedef ProcessRunner = Future<ProcessResult> Function(+ String executable,+ List<String> arguments, {+ Map<String, String>? environment,+});++typedef TerminalLauncher = Future<void> Function(String scriptPath);++typedef ProcessStarter = Future<Process> Function(+ String executable,+ List<String> arguments, {+ Map<String, String>? environment,+});++/// The progress callback `ensureReady` builds for itself, named so the per-host paths below can be+/// separate methods rather than one very long function.+typedef EmitStep = void Function({+ EnvironmentStep? step,+ EnvironmentStepStatus? status,+ String? message,+ String? output,+});++Future<ProcessResult> _defaultRun(+ String executable,+ List<String> arguments, {+ Map<String, String>? environment,+}) => Process.run(executable, arguments, environment: environment);++Future<Process> _defaultStart(+ String executable,+ List<String> arguments, {+ Map<String, String>? environment,+}) => Process.start(executable, arguments, environment: environment);++/// macOS opens a real Terminal.app window. Linux has no single canonical+/// terminal, so this tries the Debian/Ubuntu `update-alternatives` target+/// first, then the two most common emulators, and gives up only if none of+/// them exist on the box.+Future<void> _defaultOpenTerminal(String scriptPath) async {+ if (Platform.isMacOS) {+ await Process.start('/usr/bin/open', ['-a', 'Terminal', scriptPath]);+ return;+ }+ final candidates = <List<String>>[+ ['x-terminal-emulator', '-e', scriptPath],+ ['gnome-terminal', '--', scriptPath],+ ['xterm', '-e', scriptPath],+ ];+ for (final candidate in candidates) {+ try {+ await Process.start(candidate.first, candidate.skip(1).toList());+ return;+ } on ProcessException {+ continue;+ }+ }+ throw StateError(+ 'Could not find a terminal emulator to launch (tried x-terminal-emulator, '+ 'gnome-terminal, xterm)',+ );+}++/// Prepares the only system dependencies required by the desktop transport.+///+/// Node lives beneath [harnessHome] rather than in Homebrew/nvm/PATH. The+/// CLI launcher is written against that exact binary, so launching Harness+/// from Finder and from Terminal has identical runtime behavior.+class EnvironmentProvisioner {+ final Directory harnessHome;+ final ProcessRunner _run;+ final ProcessStarter? _start;+ final TerminalLauncher _openTerminal;+ final bool _isMacOS;+ final bool _isLinux;+ final bool _isWindows;+ final bool _forceMissingAppleDeveloperTools;+ final Map<String, String> _platformEnvironment;++ EnvironmentProvisioner({+ Directory? harnessHome,+ ProcessRunner? run,+ ProcessStarter? start,+ TerminalLauncher? openTerminal,+ bool? isMacOS,+ bool? isLinux,+ bool? isWindows,+ bool? forceMissingAppleDeveloperTools,+ Map<String, String>? platformEnvironment,+ }) : harnessHome = harnessHome ?? Directory(_defaultHarnessHome()),+ _run = run ?? _defaultRun,+ _start = start ?? (run == null ? _defaultStart : null),+ _openTerminal = openTerminal ?? _defaultOpenTerminal,+ _isMacOS = isMacOS ?? Platform.isMacOS,+ _isLinux = isLinux ?? Platform.isLinux,+ _isWindows = isWindows ?? Platform.isWindows,+ _platformEnvironment = platformEnvironment ?? Platform.environment,+ _forceMissingAppleDeveloperTools =+ forceMissingAppleDeveloperTools ??+ const bool.fromEnvironment(+ 'HARNESS_DESKTOP_FORCE_MISSING_APPLE_DEVELOPER_TOOLS',+ );++ /// HOME, then USERPROFILE. Windows sets only the latter, so a launch from Explorer used to throw+ /// out of this constructor before a single frame could render.+ static String? userHome() {+ final home = Platform.environment['HOME'];+ if (home != null && home.isNotEmpty) return home;+ final profile = Platform.environment['USERPROFILE'];+ if (profile != null && profile.isNotEmpty) return profile;+ return containerHome;+ }++ static String _defaultHarnessHome() {+ final home = userHome();+ if (home == null) {+ throw StateError('Could not resolve the current user home directory');+ }+ return '$home${Platform.pathSeparator}.harness';+ }++ /// Checks the complete environment, and mutates it only when [install] is explicitly true.+ Future<EnvironmentReadiness> ensureReady({+ required void Function(EnvironmentReadiness value) onProgress,+ EnvironmentReadiness? resumeFrom,+ bool install = true,+ EnvironmentSetupMode? mode,+ }) async {+ final retryingFailedSetup =+ install && resumeFrom?.phase == EnvironmentSetupPhase.failed;+ var state = (resumeFrom ?? EnvironmentReadiness.initial()).copyWith(+ phase: install+ ? EnvironmentSetupPhase.installing+ : EnvironmentSetupPhase.preflight,+ mode: mode,+ clearFailure: true,+ clearTerminalHandoff: retryingFailedSetup,+ );+ void emit({+ EnvironmentStep? step,+ EnvironmentStepStatus? status,+ String? message,+ String? output,+ EnvironmentSetupPhase? phase,+ EnvironmentFailure? failure,+ String? terminalLogPath,+ String? terminalResultPath,+ EnvironmentTerminalSetup? terminalSetup,+ bool? systemReady,+ bool? homebrewReady,+ bool? tmuxBinaryReady,+ List<String>? missingLinuxPackages,+ }) {+ final next = Map<EnvironmentStep, EnvironmentStepStatus>.from(+ state.steps,+ );+ if (step != null && status != null) next[step] = status;+ final lines = [...state.output];+ if (output != null && output.trim().isNotEmpty) {+ if (output.startsWith('Terminal log:\n')) {+ lines.removeWhere((line) => line.startsWith('Terminal log:\n'));+ }+ lines.add(output.trim());+ if (lines.length > 200) lines.removeRange(0, lines.length - 200);+ }+ state = EnvironmentReadiness(+ steps: next,+ message: message ?? state.message,+ output: lines,+ phase: phase ?? state.phase,+ mode: mode ?? state.mode,+ failure: failure ?? state.failure,+ terminalLogPath: terminalLogPath ?? state.terminalLogPath,+ terminalResultPath: terminalResultPath ?? state.terminalResultPath,+ terminalSetup: terminalSetup ?? state.terminalSetup,+ systemReady: systemReady ?? state.systemReady,+ homebrewReady: homebrewReady ?? state.homebrewReady,+ tmuxBinaryReady: tmuxBinaryReady ?? state.tmuxBinaryReady,+ missingLinuxPackages:+ missingLinuxPackages ?? state.missingLinuxPackages,+ );+ onProgress(state);+ }++ final previousTerminalLog = state.terminalLogPath;+ var previousTerminalLogText = '';+ EnvironmentTerminalSetup? completedTerminalSetup;+ if (previousTerminalLog != null) {+ try {+ final text = await File(previousTerminalLog).readAsString();+ previousTerminalLogText = text;+ final snapshot = 'Terminal log:\n${text.trim()}';+ if (text.trim().isNotEmpty && !state.output.contains(snapshot)) {+ emit(output: snapshot);+ }+ } on FileSystemException {+ // The terminal may not have created its log yet.+ }+ }+ final previousTerminalResult = state.terminalResultPath;+ var terminalResultPending = false;+ if (previousTerminalResult != null) {+ if (!await File(previousTerminalResult).exists()) {+ terminalResultPending = true;+ // `terminal.exit` is a handoff hint, not the source of truth. Some+ // Linux terminal emulators keep the launched shell/window alive after+ // apt has already finished, and an interrupted EXIT trap can omit the+ // file entirely. Continue into the read-only command probes below so+ // the 5-second poll (and the user's Recheck button) can observe that+ // the host is actually ready instead of waiting forever for a file a+ // cold app launch does not need either.+ emit(+ message: state.message ?? 'Complete the visible prompts in Terminal.',+ phase: EnvironmentSetupPhase.waitingForTerminal,+ );+ }+ try {+ final exitCode = int.tryParse(+ (await File(previousTerminalResult).readAsString()).trim(),+ );+ if (exitCode != null && exitCode != 0) {+ final linuxHost =+ state.terminalSetup == EnvironmentTerminalSetup.linuxHost;+ final clipboardFailed =+ linuxHost &&+ state.steps[EnvironmentStep.clipboard] ==+ EnvironmentStepStatus.needsTerminal;+ final tmuxFailed =+ state.steps[EnvironmentStep.tmux] ==+ EnvironmentStepStatus.needsTerminal;+ if (clipboardFailed) {+ emit(+ step: EnvironmentStep.clipboard,+ status: EnvironmentStepStatus.failed,+ );+ }+ if (tmuxFailed) {+ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.failed,+ );+ }+ final classifiedFailure = linuxHost+ ? _classifiedLinuxPackageFailure(+ exitCode,+ previousTerminalLogText,+ )+ : null;+ emit(+ step: linuxHost ? null : EnvironmentStep.tmux,+ status: linuxHost ? null : EnvironmentStepStatus.failed,+ message: 'The Terminal setup exited with code $exitCode.',+ phase: EnvironmentSetupPhase.failed,+ failure: EnvironmentFailure(+ step: !linuxHost+ ? EnvironmentStep.tmux+ : !state.systemReady+ ? null+ : clipboardFailed+ ? EnvironmentStep.clipboard+ : tmuxFailed+ ? EnvironmentStep.tmux+ : null,+ title:+ classifiedFailure?.title ??+ 'System package installation failed',+ detail:+ classifiedFailure?.detail ??+ 'Terminal exited with code $exitCode. Review the complete log below.',+ command:+ classifiedFailure?.command ??+ (linuxHost+ ? await _linuxHostManualCommand()+ : _manualCommandFor(EnvironmentStep.tmux)),+ exitCode: exitCode,+ ),+ );+ return state;+ }+ if (exitCode == 0) completedTerminalSetup = state.terminalSetup;+ } on FileSystemException {+ // The result can disappear between exists() and readAsString(). The+ // live dependency probes below remain the authoritative fallback.+ }+ }+ onProgress(state);++ if (!_isMacOS && !_isLinux) {+ if (_isWindows) {+ await _verifyWindows(emit);+ return state;+ }+ emit(+ step: EnvironmentStep.harness,+ status: EnvironmentStepStatus.failed,+ message: 'Automatic environment setup is currently available on macOS and Linux only.',+ phase: EnvironmentSetupPhase.failed,+ );+ return state;+ }++ try {+ var linuxMissingBasePackages = <String>[];+ String? linuxMissingClipboardPackage;+ EnvironmentFailure? systemFailure;+ if (_isMacOS) {+ systemFailure = await _systemPreflightFailure();+ } else {+ if (!await _hasWritableHome()) {+ systemFailure = const EnvironmentFailure(+ title: 'Home directory is not writable',+ detail: 'Harness needs to write ~/.harness and ~/.local/bin.',+ );+ } else {+ linuxMissingBasePackages = await _missingLinuxBasePackages();+ linuxMissingClipboardPackage = await _missingLinuxClipboardPackage();+ }+ }+ if (systemFailure != null) {+ emit(+ message: systemFailure.detail,+ phase: EnvironmentSetupPhase.failed,+ failure: systemFailure,+ );+ return state;+ }+ var systemReady = _isMacOS+ ? await _hasAppleDeveloperTools()+ : linuxMissingBasePackages.isEmpty;+ emit(+ systemReady: systemReady,+ missingLinuxPackages: _isLinux+ ? <String>[+ ...linuxMissingBasePackages,+ ?linuxMissingClipboardPackage,+ ]+ : const [],+ output: systemReady+ ? '✓ required system tools · writable home'+ : _isMacOS+ ? '✗ Apple developer tools · xcrun --find clang'+ : '✗ missing Linux base packages · ${linuxMissingBasePackages.join(', ')}',+ );++ final clipboardApplicable = _isLinux && _linuxClipboardCommand() != null;+ var clipboardReady =+ !clipboardApplicable || linuxMissingClipboardPackage == null;+ emit(+ step: EnvironmentStep.clipboard,+ status: clipboardApplicable+ ? clipboardReady+ ? EnvironmentStepStatus.ready+ : EnvironmentStepStatus.failed+ : EnvironmentStepStatus.notApplicable,+ message: clipboardApplicable+ ? clipboardReady+ ? 'Native image clipboard is ready.'+ : '$linuxMissingClipboardPackage is required for native image paste.'+ : _isLinux+ ? 'Native image clipboard is not applicable on a headless Linux host.'+ : null,+ output: clipboardApplicable+ ? clipboardReady+ ? '✓ native image clipboard · ${_linuxClipboardCommand()}'+ : '✗ native image clipboard · $linuxMissingClipboardPackage'+ : _isLinux+ ? '– native image clipboard N/A (headless)'+ : null,+ );++ final homebrewReady = !_isMacOS || await _hasHomebrew();+ var tmuxBinaryReady = await _hasTmux();+ var tmuxReady =+ tmuxBinaryReady && (!_isMacOS || (homebrewReady && systemReady));+ emit(+ step: EnvironmentStep.tmux,+ status: tmuxReady+ ? EnvironmentStepStatus.ready+ : EnvironmentStepStatus.failed,+ message: tmuxReady+ ? (_isMacOS ? 'Homebrew and tmux are ready.' : 'tmux is ready.')+ : _isMacOS && !systemReady+ ? 'Apple developer tools are required.'+ : _isMacOS && !homebrewReady+ ? 'Homebrew is required.'+ : 'tmux is required.',+ output: tmuxReady+ ? (_isMacOS ? '✓ Homebrew · tmux --version' : '✓ tmux --version')+ : _isMacOS && !systemReady+ ? '✗ Apple developer tools · xcrun --find clang'+ : _isMacOS && !homebrewReady+ ? '✗ Homebrew · brew --version'+ : '✗ tmux --version',+ homebrewReady: _isMacOS ? homebrewReady : null,+ tmuxBinaryReady: tmuxBinaryReady,+ );++ final harnessReady = await _hasHarness();+ emit(+ step: EnvironmentStep.harness,+ status: harnessReady+ ? EnvironmentStepStatus.ready+ : EnvironmentStepStatus.failed,+ message: harnessReady+ ? 'Harness CLI and managed Node are ready.'+ : 'Harness CLI or its managed Node runtime is missing.',+ output: harnessReady+ ? '✓ managed Node >= 20 · harness version'+ : '✗ managed Node >= 20 · harness version',+ );++ if (state.isReady) {+ emit(+ message: 'All required tools passed verification.',+ phase: EnvironmentSetupPhase.ready,+ );+ return state;+ }++ if (!install) {+ final linuxMissingPackages = <String>[+ ...linuxMissingBasePackages,+ ?linuxMissingClipboardPackage,+ ];+ if (terminalResultPending &&+ (!systemReady || !clipboardReady || !tmuxReady)) {+ emit(+ message:+ state.message ?? 'Complete the visible prompts in Terminal.',+ phase: EnvironmentSetupPhase.waitingForTerminal,+ );+ return state;+ }+ if (completedTerminalSetup == EnvironmentTerminalSetup.linuxHost &&+ (linuxMissingPackages.isNotEmpty || !tmuxBinaryReady)) {+ emit(+ message: 'The Linux host dependency install finished, but verification still found missing packages.',+ phase: EnvironmentSetupPhase.failed,+ failure: EnvironmentFailure(+ step: !systemReady+ ? null+ : linuxMissingClipboardPackage != null+ ? EnvironmentStep.clipboard+ : EnvironmentStep.tmux,+ title: 'Host dependency verification failed',+ detail:+ 'Still missing: ${[...linuxMissingPackages, if (!tmuxBinaryReady) 'tmux'].join(', ')}. Review the Terminal log, then retry when ready.',+ command: await _linuxHostManualCommand(),+ ),+ );+ return state;+ }+ emit(+ message: _isLinux && linuxMissingPackages.isNotEmpty+ ? 'Linux host packages required: ${linuxMissingPackages.join(', ')}.'+ : 'Review what Harness will install before continuing.',+ phase: EnvironmentSetupPhase.review,+ );+ return state;+ }++ // Strict dependency order: one host-package transaction (base tools,+ // tmux and the active clipboard helper) -> managed Node/Harness.+ if (_isLinux && (!systemReady || !clipboardReady || !tmuxBinaryReady)) {+ var packages = <String>{+ ...linuxMissingBasePackages,+ ?linuxMissingClipboardPackage,+ if (!tmuxBinaryReady) 'tmux',+ }.toList();+ if (!await _hasAptGet()) {+ final command = await _linuxHostManualCommand();+ emit(+ message: 'Automatic Linux package installation supports apt-based distributions only.',+ phase: EnvironmentSetupPhase.failed,+ failure: EnvironmentFailure(+ title: 'Unsupported Linux package manager',+ detail:+ 'Install ${packages.join(', ')} with this distribution\'s package manager, then recheck.',+ command: command,+ ),+ );+ return state;+ }++ ProcessResult? backgroundInstall;+ if (await _canInstallAptUnattended()) {+ if (linuxMissingClipboardPackage != null) {+ emit(+ step: EnvironmentStep.clipboard,+ status: EnvironmentStepStatus.running,+ );+ }+ emit(+ step: tmuxBinaryReady ? null : EnvironmentStep.tmux,+ status: tmuxBinaryReady ? null : EnvironmentStepStatus.running,+ message: 'Installing Linux system packages…',+ );+ try {+ backgroundInstall = await _shellStreaming(+ _linuxAptInstallCommand(packages, nonInteractiveSudo: true),+ onOutput: (line) => emit(+ message:+ line.contains('Enabling automatic time synchronization')+ ? 'Synchronizing the system clock before retrying Ubuntu packages…'+ : null,+ output: line,+ ),+ );+ } catch (error) {+ emit(output: 'Background Linux package install failed: $error');+ }++ linuxMissingBasePackages = await _missingLinuxBasePackages();+ linuxMissingClipboardPackage = await _missingLinuxClipboardPackage();+ systemReady = linuxMissingBasePackages.isEmpty;+ clipboardReady =+ !clipboardApplicable || linuxMissingClipboardPackage == null;+ tmuxBinaryReady = await _hasTmux();+ tmuxReady = tmuxBinaryReady;+ emit(+ step: EnvironmentStep.clipboard,+ status: clipboardApplicable+ ? clipboardReady+ ? EnvironmentStepStatus.ready+ : EnvironmentStepStatus.failed+ : EnvironmentStepStatus.notApplicable,+ missingLinuxPackages: <String>[+ ...linuxMissingBasePackages,+ ?linuxMissingClipboardPackage,+ ],+ tmuxBinaryReady: tmuxBinaryReady,+ );+ final classifiedBackgroundFailure = backgroundInstall == null+ ? null+ : _classifiedLinuxPackageFailure(+ backgroundInstall.exitCode,+ _resultText(backgroundInstall),+ );+ if (classifiedBackgroundFailure != null) {+ if (!tmuxReady) {+ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.failed,+ );+ }+ emit(+ message: classifiedBackgroundFailure.detail,+ phase: EnvironmentSetupPhase.failed,+ systemReady: systemReady,+ failure: EnvironmentFailure(+ step: !systemReady+ ? null+ : !clipboardReady+ ? EnvironmentStep.clipboard+ : !tmuxReady+ ? EnvironmentStep.tmux+ : null,+ title: classifiedBackgroundFailure.title,+ detail: classifiedBackgroundFailure.detail,+ command: classifiedBackgroundFailure.command,+ exitCode: classifiedBackgroundFailure.exitCode,+ ),+ );+ return state;+ }+ if (systemReady && clipboardReady && tmuxReady) {+ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.ready,+ message: 'Linux system packages and tmux are ready.',+ output: '✓ Linux host dependencies installed and verified',+ systemReady: true,+ tmuxBinaryReady: true,+ missingLinuxPackages: const [],+ );+ } else {+ if (backgroundInstall != null) {+ emit(+ output: backgroundInstall.exitCode == 0+ ? 'apt finished, but Linux host dependencies did not pass verification.'+ : 'Background apt install exited ${backgroundInstall.exitCode}: '+ '${_resultText(backgroundInstall)}',+ );+ }+ packages = <String>{+ ...linuxMissingBasePackages,+ ?linuxMissingClipboardPackage,+ if (!tmuxBinaryReady) 'tmux',+ }.toList();+ }+ }++ if (!systemReady || !clipboardReady || !tmuxReady) {+ final terminal = await _launchLinuxHostSetup(packages);+ if (linuxMissingClipboardPackage != null) {+ emit(+ step: EnvironmentStep.clipboard,+ status: EnvironmentStepStatus.needsTerminal,+ );+ }+ if (!tmuxReady) {+ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.needsTerminal,+ );+ }+ emit(+ message: 'Complete the visible Linux package prompts in Terminal. Harness never sees your password.',+ output: backgroundInstall == null+ ? 'Terminal opened to install Linux host dependencies.'+ : 'Background install was incomplete; Terminal opened to finish Linux host dependencies.',+ phase: EnvironmentSetupPhase.waitingForTerminal,+ terminalLogPath: terminal.log.path,+ terminalResultPath: terminal.result.path,+ terminalSetup: EnvironmentTerminalSetup.linuxHost,+ systemReady: systemReady,+ );+ return state;+ }+ }++ if (_isMacOS && systemReady && homebrewReady && !tmuxBinaryReady) {+ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.running,+ message: 'Installing tmux via Homebrew…',+ );+ ProcessResult? installResult;+ try {+ installResult = await _shellStreaming(+ 'brew install tmux',+ onOutput: (line) => emit(output: line),+ );+ } catch (error) {+ emit(output: 'Background tmux install failed: $error');+ }+ tmuxReady = installResult?.exitCode == 0 && await _hasTmux();+ if (tmuxReady) {+ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.ready,+ message: 'Homebrew and tmux are ready.',+ output: '✓ tmux installed via Homebrew',+ homebrewReady: true,+ tmuxBinaryReady: true,+ );+ } else {+ if (installResult != null) {+ emit(+ output: installResult.exitCode == 0+ ? 'Homebrew finished, but tmux did not pass verification.'+ : 'Background tmux install exited ${installResult.exitCode}: '+ '${_resultText(installResult)}',+ );+ }+ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.running,+ message: 'tmux needs attention in Terminal…',+ );+ final terminal = await _launchTmuxSetup();+ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.needsTerminal,+ message: 'Complete the visible Homebrew prompts in Terminal. Harness never sees your password.',+ output: 'Background install failed; Terminal opened to retry tmux.',+ phase: EnvironmentSetupPhase.waitingForTerminal,+ terminalLogPath: terminal.log.path,+ terminalResultPath: terminal.result.path,+ terminalSetup: EnvironmentTerminalSetup.tmux,+ );+ return state;+ }+ } else if (!tmuxReady) {+ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.running,+ message: 'Preparing tmux in a secure terminal…',+ );+ final terminal = await _launchTmuxSetup();+ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.needsTerminal,+ message: 'Complete any password or macOS prompts in Terminal. Harness never sees your password.',+ output: _isMacOS+ ? 'Terminal opened to install Homebrew and tmux.'+ : 'Terminal opened to install tmux.',+ phase: EnvironmentSetupPhase.waitingForTerminal,+ terminalLogPath: terminal.log.path,+ terminalResultPath: terminal.result.path,+ terminalSetup: EnvironmentTerminalSetup.tmux,+ );+ return state;+ }++ if (!harnessReady) {+ emit(+ step: EnvironmentStep.harness,+ status: EnvironmentStepStatus.running,+ message: 'Installing managed Node and Harness CLI…',+ );+ await _ensureHarness((line) => emit(output: line));+ emit(+ step: EnvironmentStep.harness,+ status: EnvironmentStepStatus.ready,+ output: '✓ Harness CLI ready',+ );+ }++ emit(+ message: 'Verifying every required command…',+ phase: EnvironmentSetupPhase.verifying,+ );+ if (_isLinux) {+ final missingBase = await _missingLinuxBasePackages();+ final missingClipboard = await _missingLinuxClipboardPackage();+ final writableHome = await _hasWritableHome();+ if (missingBase.isNotEmpty ||+ missingClipboard != null ||+ !writableHome) {+ if (missingClipboard != null) {+ emit(+ step: EnvironmentStep.clipboard,+ status: EnvironmentStepStatus.failed,+ );+ }+ emit(+ message:+ 'Linux system dependencies did not pass final verification.',+ phase: EnvironmentSetupPhase.failed,+ systemReady: writableHome && missingBase.isEmpty,+ failure: EnvironmentFailure(+ title: 'Linux system verification failed',+ detail: !writableHome+ ? 'The home directory is not writable.'+ : 'Still missing packages: ${[...missingBase, ?missingClipboard].join(', ')}',+ command: await _linuxHostManualCommand(),+ ),+ );+ return state;+ }+ }+ final finalChecks = <EnvironmentStep, Future<bool> Function()>{+ EnvironmentStep.tmux: _isTmuxEnvironmentReady,+ EnvironmentStep.harness: _hasHarness,+ };+ for (final entry in finalChecks.entries) {+ if (!await entry.value()) {+ emit(step: entry.key, status: EnvironmentStepStatus.failed);+ throw StateError(+ '${entry.key.name} did not pass final version verification.',+ );+ }+ }+ emit(message: 'Environment ready.', phase: EnvironmentSetupPhase.ready);+ return state;+ } catch (error) {+ final failed =+ state.steps.entries+ .where((entry) => entry.value == EnvironmentStepStatus.running)+ .map((entry) => entry.key)+ .firstOrNull ??+ state.steps.entries+ .where((entry) => entry.value == EnvironmentStepStatus.failed)+ .map((entry) => entry.key)+ .firstOrNull;+ emit(+ step: failed,+ status: EnvironmentStepStatus.failed,+ message: 'Environment setup failed: $error',+ phase: EnvironmentSetupPhase.failed,+ failure: EnvironmentFailure(+ step: failed,+ title: 'Setup could not finish',+ detail: '$error',+ command: failed == null ? null : _manualCommandFor(failed),+ ),+ );+ return state;+ }+ }++ /// Windows gets a VERIFY pass rather than the install pass above.+ ///+ /// Every installer this class drives is a POSIX shell script — `install.sh` piped into `/bin/sh`,+ /// a `zsh`/`bash` login shell for each probe, `brew`, `apt-get` — and none of it exists here. So+ /// instead of refusing to boot a Windows box that is in fact provisioned, this checks what is+ /// actually on it and names the command for whatever is missing. Windows packaging remains out+ /// of scope for this release.+ Future<void> _verifyWindows(EmitStep emit) async {+ emit(+ step: EnvironmentStep.clipboard,+ status: EnvironmentStepStatus.notApplicable,+ );+ emit(+ step: EnvironmentStep.harness,+ status: EnvironmentStepStatus.running,+ message: 'Checking the Harness CLI…',+ );+ var harnessReady = false;+ try {+ final runner = HarnessCliRunner(+ harnessHome: harnessHome,+ runProcess: _run,+ );+ final status = await runner.run(['auth', 'status', '--json']);+ harnessReady =+ status.exitCode == 0 && (status.stdout as String).trim().isNotEmpty;+ } on ProcessException {+ harnessReady = false;+ } on StateError {+ // No managed node/cli.js pair recorded under ~/.harness yet.+ harnessReady = false;+ }+ if (!harnessReady) {+ emit(+ step: EnvironmentStep.harness,+ status: EnvironmentStepStatus.failed,+ message:+ 'The Harness CLI is not installed for this user. There is no Windows installer yet — '+ 'from a checkout of the CLI run: npm install && npm run bundle && '+ 'bash scripts/install-cli.sh — then click Recheck.',+ );+ return;+ }+ emit(+ step: EnvironmentStep.harness,+ status: EnvironmentStepStatus.ready,+ output: 'Harness CLI ready',+ );++ emit(+ step: EnvironmentStep.tmux,+ status: EnvironmentStepStatus.unavailable,+ output:+ 'tmux does not exist on Windows — terminals come from Herdr instead.',+ );+ }++ Future<EnvironmentFailure?> _systemPreflightFailure() async {+ final tools = _isMacOS+ ? 'command -v sh zsh bash curl tar sed awk shasum >/dev/null'+ : 'command -v sh bash curl tar sed awk sha256sum >/dev/null';+ final base = await _shell(tools);+ if (base.exitCode != 0) {+ return EnvironmentFailure(+ title: 'Required system tools are missing',+ detail: _resultText(base).isEmpty+ ? 'Harness needs curl, tar, sed, awk, checksum tools and a POSIX shell.'+ : _resultText(base),+ command: _isMacOS+ ? 'xcode-select --install'+ : 'sudo apt-get install -y bash curl tar sed gawk coreutils',+ );+ }+ if (!await _hasWritableHome()) {+ return const EnvironmentFailure(+ title: 'Home directory is not writable',+ detail: 'Harness needs to write ~/.harness and ~/.local/bin.',+ );+ }+ return null;+ }++ Future<bool> _hasWritableHome() async {+ final writable = await _shell('test -w "\$HOME"');+ return writable.exitCode == 0;+ }++ /// Base packages the desktop needs before it can hand host setup to the+ /// CLI-only installer. Native clipboard support is reported separately so+ /// the UI can explain it without creating a second install transaction.+ Future<List<String>> _missingLinuxBasePackages() async {+ if (!_isLinux) return const [];+ const commandPackages = <String, String>{+ 'sh': 'dash',+ 'bash': 'bash',+ 'curl': 'curl',+ 'tar': 'tar',+ 'sed': 'sed',+ 'awk': 'gawk',+ 'sha256sum': 'coreutils',+ };+ final missing = <String>[];+ for (final entry in commandPackages.entries) {+ final probe = await _shell('command -v ${entry.key} >/dev/null 2>&1');+ if (probe.exitCode != 0) missing.add(entry.value);+ }+ return missing.toSet().toList();+ }++ /// Clipboard selection intentionally matches osClipboard.ts: Wayland wins+ /// when both display variables exist, X11 is the fallback, and a headless+ /// machine has no native clipboard requirement to satisfy.+ Future<String?> _missingLinuxClipboardPackage() async {+ if (!_isLinux) return null;+ final clipboardCommand = _linuxClipboardCommand();+ final clipboardPackage = _linuxClipboardPackage();+ if (clipboardCommand != null && clipboardPackage != null) {+ final probe = await _shell(+ 'command -v $clipboardCommand >/dev/null 2>&1',+ );+ if (probe.exitCode != 0) return clipboardPackage;+ }+ return null;+ }++ Future<List<String>> _missingLinuxHostPackages() async {+ final packages = <String>{...await _missingLinuxBasePackages()};+ final clipboard = await _missingLinuxClipboardPackage();+ if (clipboard != null) packages.add(clipboard);+ return packages.toList();+ }++ String? _linuxClipboardCommand() {+ if (!_isLinux) return null;+ if ((_platformEnvironment['WAYLAND_DISPLAY'] ?? '').isNotEmpty) {+ return 'wl-copy';+ }+ if ((_platformEnvironment['DISPLAY'] ?? '').isNotEmpty) return 'xclip';+ return null;+ }++ String? _linuxClipboardPackage() => switch (_linuxClipboardCommand()) {+ 'wl-copy' => 'wl-clipboard',+ 'xclip' => 'xclip',+ _ => null,+ };++ Future<bool> _hasAptGet() async {+ final result = await _shell('command -v apt-get >/dev/null 2>&1');+ return result.exitCode == 0;+ }++ Future<bool> _canInstallAptUnattended() async {+ final user = await _shell('id -u');+ if (user.exitCode == 0 && '${user.stdout}'.trim() == '0') return true;+ final sudo = await _shell(+ 'command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1',+ );+ return sudo.exitCode == 0;+ }++ bool _isLinuxClockSkewOutput(String output) {+ final normalized = output.toLowerCase();+ return normalized.contains('is not valid yet') ||+ normalized.contains('certificate is not yet valid');+ }++ EnvironmentFailure? _classifiedLinuxPackageFailure(+ int exitCode,+ String output,+ ) {+ if (exitCode == _linuxClockSyncFailureExitCode ||+ _isLinuxClockSkewOutput(output)) {+ return const EnvironmentFailure(+ title: 'System clock could not be synchronized',+ detail: 'Ubuntu reports that repository metadata is in the future relative to this computer. Enable automatic time synchronization, confirm the clock is correct, then retry.',+ command: _linuxClockRepairCommand,+ exitCode: _linuxClockSyncFailureExitCode,+ );+ }+ if (exitCode == _linuxAptUpdateFailureExitCode) {+ return const EnvironmentFailure(+ title: 'Package repository refresh failed',+ detail: 'Ubuntu could not refresh its package indexes, so Harness stopped instead of retrying with stale package data.',+ command: 'sudo apt-get update',+ exitCode: _linuxAptUpdateFailureExitCode,+ );+ }+ return null;+ }++ String _linuxAptInstallCommand(+ List<String> packages, {+ required bool nonInteractiveSudo,+ }) {+ final names = packages.toSet().join(' ');+ final sudoFlag = nonInteractiveSudo ? '-n ' : '';+ return '''set -o pipefail+export LC_ALL=C+run_as_root() {+ if [ "\$(id -u)" -eq 0 ]; then+ "\$@"+ elif command -v sudo >/dev/null 2>&1; then+ sudo $sudoFlag"\$@"+ else+ echo 'Installing Linux system packages needs root access, but sudo is unavailable.' >&2+ return 126+ fi+}+apt_as_root() {+ run_as_root env DEBIAN_FRONTEND=noninteractive apt-get "\$@"+}+repair_system_clock() {+ if command -v chronyc >/dev/null 2>&1; then+ echo 'Repository metadata is ahead of this computer. Enabling automatic time synchronization with chrony…'+ run_as_root chronyc online >/dev/null 2>&1 || true+ run_as_root chronyc burst 4/4 >/dev/null 2>&1 || true+ clock_attempt=0+ while :; do+ chrony_tracking="\$(chronyc tracking 2>/dev/null || true)"+ if printf '%s\n' "\$chrony_tracking" | grep -Eq 'Leap status[[:space:]]*:[[:space:]]*Normal'; then+ if run_as_root chronyc makestep; then+ echo 'System clock stepped with chrony.'+ return 0+ fi+ echo 'chrony has a synchronized source but could not step the system clock.' >&2+ break+ fi+ clock_attempt=\$((clock_attempt + 1))+ if [ "\$clock_attempt" -ge 15 ]; then+ echo 'chrony did not obtain a synchronized source within 30 seconds.' >&2+ break+ fi+ sleep 2+ done+ fi+ if ! command -v timedatectl >/dev/null 2>&1; then+ echo 'System clock is behind repository metadata, but no usable time synchronization service was found.' >&2+ return $_linuxClockSyncFailureExitCode+ fi+ echo 'Repository metadata is ahead of this computer. Enabling automatic time synchronization…'+ run_as_root timedatectl set-ntp true || return $_linuxClockSyncFailureExitCode+ if command -v systemctl >/dev/null 2>&1; then+ run_as_root systemctl restart systemd-timesyncd >/dev/null 2>&1 || true+ fi+ clock_attempt=0+ while [ "\$(timedatectl show -p NTPSynchronized --value 2>/dev/null || true)" != 'yes' ]; do+ clock_attempt=\$((clock_attempt + 1))+ if [ "\$clock_attempt" -ge 15 ]; then+ echo 'Automatic time synchronization did not become ready within 30 seconds.' >&2+ return $_linuxClockSyncFailureExitCode+ fi+ sleep 2+ done+ echo 'System clock synchronized.'+}+refresh_package_indexes() {+ apt_update_log="\${TMPDIR:-/tmp}/harness-apt-update-\$\$.log"+ if apt_as_root update 2>&1 | tee "\$apt_update_log"; then+ rm -f "\$apt_update_log"+ return 0+ fi+ if grep -Eiq 'is not valid yet|certificate is not yet valid' "\$apt_update_log"; then+ rm -f "\$apt_update_log"+ if ! repair_system_clock; then+ echo 'System clock could not be synchronized automatically.' >&2+ return $_linuxClockSyncFailureExitCode+ fi+ if ! apt_as_root update; then+ echo 'Package repository refresh still failed after clock synchronization.' >&2+ return $_linuxAptUpdateFailureExitCode+ fi+ return 0+ fi+ rm -f "\$apt_update_log"+ echo 'Package repository refresh failed. Harness will not retry with stale package indexes.' >&2+ return $_linuxAptUpdateFailureExitCode+}+install_linux_packages() {+ apt_as_root install -y $names && return 0+ echo 'Refreshing package indexes before retrying…'+ refresh_package_indexes || return \$?+ if ! apt_as_root install -y $names; then+ echo 'Package installation still failed after a successful repository refresh.' >&2+ return $_linuxAptInstallFailureExitCode+ fi+}+if install_linux_packages; then+ :+else+ install_status=\$?+ exit "\$install_status"+fi''';+ }++ Future<String> _linuxHostManualCommand() async {+ final packages = <String>{+ ...await _missingLinuxHostPackages(),+ if (!await _hasTmux()) 'tmux',+ }.join(' ');+ if (packages.isEmpty) return 'Recheck Linux system dependencies.';+ if (!await _hasAptGet()) {+ return 'Install with your distribution package manager: $packages';+ }+ return 'sudo apt-get install -y $packages';+ }++ Future<bool> _hasHarness() async {+ final currentNode = File('${harnessHome.path}/runtime/current-node');+ if (!await currentNode.exists()) return false;+ final nodePath = (await currentNode.readAsString()).trim();+ if (nodePath.isEmpty || !File(nodePath).existsSync()) return false;+ final runtimeRoot = '${harnessHome.absolute.path}/runtime/';+ if (!File(nodePath).absolute.path.startsWith(runtimeRoot)) return false;+ final node = await _run(nodePath, ['--version']);+ if (node.exitCode != 0) return false;+ final match = RegExp(r'^v?(\d+)').firstMatch('${node.stdout}'.trim());+ if (match == null || int.parse(match.group(1)!) < 20) return false;+ try {+ final cli = File('${harnessHome.path}/cli/cli.js');+ if (!await cli.exists()) return false;+ final version = await _run(nodePath, [cli.path, 'version']);+ return version.exitCode == 0;+ } on ProcessException {+ return false;+ } on StateError {+ return false;+ }+ }++ Future<void> _ensureHarness(void Function(String line) onOutput) async {+ final runner = HarnessCliRunner(harnessHome: harnessHome, runProcess: _run);+ if (await _hasHarness()) return;+ // No interpreter is named here. install.sh provisions the same+ // checksum-verified Node under `~/.harness/runtime` when the computer has+ // none, records it in `current-node`, and bakes its absolute path into the+ // `~/.local/bin/harness` launcher — which is what makes a Finder launch,+ // where PATH is launchd's bare `/usr/bin:/bin:/usr/sbin:/sbin`, still find+ // a Node. Doing it there rather than here keeps ONE implementation of that,+ // shared with everyone who installs the CLI from a terminal.+ final install = await _shellStreaming(+ // Served off the CDN-fronted public bucket (autonomous-code: apps/web/scripts/cli-install.sh,+ // published with `make upload-cli-install-sh`), not by the web app. The old web-app URL,+ // https://harness.autonomous.ai/cli/install.sh, still redirects here, but pointing at the CDN+ // URL directly avoids that extra hop.+ // A stale URL is worse here than anywhere else: a 404 piped into bash still exits 0 (measured),+ // so the `install.exitCode != 0` check below would pass and the failure would only surface as+ // the confusing "CLI did not start after installation" a few lines further down.+ 'set -e; $kHarnessDesktopInstallCommand',+ onOutput: onOutput,+ );+ if (install.exitCode != 0) {+ throw StateError(+ 'Harness installer exited ${install.exitCode}: ${_resultText(install)}',+ );+ }+ final verified = await runner.run(['version']);+ if (verified.exitCode != 0 || !await _hasHarness()) {+ throw StateError(+ 'Harness CLI verification exited ${verified.exitCode}: ${_resultText(verified)}',+ );+ }+ }++ Future<({File log, File result})> _launchLinuxHostSetup(+ List<String> packages,+ ) => _launchTerminalSetup(linuxPackages: packages);++ Future<({File log, File result})> _launchTmuxSetup() =>+ _launchTerminalSetup();++ Future<({File log, File result})> _launchTerminalSetup({+ List<String> linuxPackages = const [],+ }) async {+ // Package-manager installs can ask for a password. Always hand them to a+ // visible OS terminal instead of guessing whether this particular run will+ // prompt in a headless Process.run child.+ final script = await _writeTerminalBootstrapScript(+ linuxPackages: linuxPackages,+ );+ await _openTerminal(script.path);+ return (+ log: File('${script.parent.path}/terminal.log'),+ result: File('${script.parent.path}/terminal.exit'),+ );+ }++ Future<bool> _hasTmux() async {+ final result = await _shell('command -v tmux >/dev/null && tmux -V');+ return result.exitCode == 0;+ }++ Future<bool> _hasHomebrew() async {+ final result = await _shell('command -v brew >/dev/null && brew --version');+ return result.exitCode == 0;+ }++ Future<bool> _isTmuxEnvironmentReady() async {+ if (_isMacOS && !await _hasAppleDeveloperTools()) return false;+ if (_isMacOS && !await _hasHomebrew()) return false;+ return _hasTmux();+ }++ /// `xcode-select -p` only proves that a path was selected. It also succeeds+ /// for an incomplete or moved Command Line Tools directory. Resolve a tool+ /// through xcrun so pre-flight reflects whether Homebrew can actually use+ /// the selected Apple toolchain.+ Future<bool> _hasAppleDeveloperTools() async {+ if (_forceMissingAppleDeveloperTools) return false;+ final result = await _shell(+ 'command -v /usr/bin/xcrun >/dev/null 2>&1 && '+ '/usr/bin/xcrun --find clang >/dev/null 2>&1',+ );+ return result.exitCode == 0;+ }++ Future<File> _writeTerminalBootstrapScript({+ List<String> linuxPackages = const [],+ }) async {+ final directory = Directory(+ '${harnessHome.path}/desktop-app-v2/setup-runs/${DateTime.now().millisecondsSinceEpoch}',+ );+ await directory.create(recursive: true);+ await _run('/bin/chmod', ['700', directory.path]);+ if (_isMacOS) {+ final script = File('${directory.path}/install-tmux.command');+ await script.writeAsString('''#!/bin/zsh+set -e+umask 077+LOG_FILE="${directory.path}/terminal.log"+RESULT_FILE="${directory.path}/terminal.exit"+exec > >(tee -a "\$LOG_FILE") 2>&1+finish() {+ status=\$?+ printf '%s\\n' "\$status" > "\$RESULT_FILE"+ if [ "\$status" -ne 0 ]; then+ echo+ echo 'System setup failed. Review the error above, then return to Harness.'+ read -r '?Press Enter to close this window…' || true+ fi+ return "\$status"+}+trap finish EXIT+apple_developer_tools_ready() {+ /usr/bin/xcrun --find clang >/dev/null 2>&1+}+if ! apple_developer_tools_ready; then+ if [ -x /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild ]; then+ echo 'Xcode is installed but is not the active developer directory.'+ echo 'macOS may ask for your password to select it.'+ sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer+ else+ echo 'Apple developer tools are missing. Installing Command Line Tools; finish the macOS dialog to continue.'+ xcode-select --install || true+ fi+ attempts=0+ until apple_developer_tools_ready; do+ attempts=\$((attempts + 1))+ if [ "\$attempts" -ge 200 ]; then+ echo 'Apple developer tools did not become ready within 10 minutes.' >&2+ echo 'Finish the macOS installer, then retry setup.' >&2+ exit 12+ fi+ sleep 3+ done+fi+if ! command -v brew >/dev/null 2>&1; then+ echo 'Installing Homebrew (macOS may ask for your password)…'+ /bin/bash -c "\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"+fi+eval "\$(/opt/homebrew/bin/brew shellenv 2>/dev/null || /usr/local/bin/brew shellenv)"+if ! command -v tmux >/dev/null 2>&1; then+ brew install tmux+fi+echo 'tmux is ready. Return to Harness.'+''', flush: true);+ await _run('/bin/chmod', ['700', script.path]);+ return script;+ }+ final packageList = linuxPackages.isEmpty+ ? const ['tmux']+ : linuxPackages.toSet().toList();+ final packages = packageList.join(' ');+ const packageCommands = <String, String>{+ 'dash': 'sh',+ 'bash': 'bash',+ 'curl': 'curl',+ 'tar': 'tar',+ 'sed': 'sed',+ 'gawk': 'awk',+ 'coreutils': 'sha256sum',+ 'tmux': 'tmux',+ 'xclip': 'xclip',+ 'wl-clipboard': 'wl-copy',+ };+ final verification = packageList+ .map((package) => packageCommands[package])+ .whereType<String>()+ .map(+ (command) => command == 'tmux'+ ? 'command -v tmux >/dev/null 2>&1 && tmux -V'+ : 'command -v $command >/dev/null 2>&1',+ )+ .join('\n');+ final aptInstallCommand = _linuxAptInstallCommand(+ packageList,+ nonInteractiveSudo: false,+ );+ final script = File('${directory.path}/install-linux-dependencies.sh');+ await script.writeAsString('''#!/bin/bash+set -eu+umask 077+LOG_FILE="${directory.path}/terminal.log"+RESULT_FILE="${directory.path}/terminal.exit"+exec > >(tee -a "\$LOG_FILE") 2>&1++finish() {+ status=\$?+ printf '%s\\n' "\$status" > "\$RESULT_FILE"+ if [ "\$status" -ne 0 ]; then+ echo+ echo 'Linux package installation failed. Review the error above, then try again.'+ read -r -p 'Press Enter to close this window…' || true+ fi+ return "\$status"+}+trap finish EXIT++if command -v apt-get >/dev/null 2>&1; then+ echo 'Installing Linux host dependencies (you may be asked for your password)…'+ $aptInstallCommand+ $verification+ echo 'Installed packages: $packages'+ echo 'Linux host dependencies are ready. This window will close automatically in 5 seconds.'+ sleep 5+else+ echo 'Automatic Linux package installation only supports apt-based distributions (Ubuntu/Debian).'+ echo 'Install these packages with your distribution package manager: $packages'+ exit 1+fi+''', flush: true);+ await _run('/bin/chmod', ['700', script.path]);+ return script;+ }++ Future<ProcessResult> _shell(+ String command, {+ Map<String, String>? environment,+ Duration? timeout,+ }) {+ final run = _run(_isMacOS ? '/bin/zsh' : '/bin/bash', [+ '-l',+ '-c',+ // The Homebrew prefixes are named rather than trusted to be on PATH:+ // `-l` is a LOGIN shell but not an interactive one, so it reads+ // `~/.zprofile` and never `~/.zshrc`+ // — which is where `brew shellenv` sits on plenty of machines. A Finder+ // launch then starts from launchd's bare `/usr/bin:/bin:/usr/sbin:/sbin`+ // and this probe reports tmux missing on a computer that has it, then+ // "installs" it through whichever `brew` it can see. Measured: an Apple+ // Silicon Mac with both Homebrews picked up Intel `/usr/local/bin/brew`+ // and built openssl@3 from source under Rosetta, holding the boot open+ // on "Checking tmux…" for as long as that took. Apple Silicon first, so+ // a machine with both never installs through the Intel one. The CLI+ // closed the same gap in `lib/tmuxOnPath.ts`.+ 'export PATH="\$HOME/.local/bin${_isMacOS ? ':/opt/homebrew/bin:/usr/local/bin' : ''}:\$PATH"; $command',+ ], environment: environment);+ if (timeout == null) return run;+ // The child keeps running — Process.run gives us no handle to kill. That is+ // the intent: a slow install finishes in the background and the next launch+ // finds it, while this one stops waiting.+ return run.timeout(+ timeout,+ onTimeout: () => ProcessResult(0, 124, '', 'timed out after $timeout'),+ );+ }++ Future<ProcessResult> _shellStreaming(+ String command, {+ required void Function(String line) onOutput,+ Duration? timeout,+ }) async {+ final shell = _isMacOS ? '/bin/zsh' : '/bin/bash';+ final wrapped =+ 'export PATH="\$HOME/.local/bin${_isMacOS ? ':/opt/homebrew/bin:/usr/local/bin' : ''}:\$PATH"; $command';+ if (_start == null) {+ final result = await _shell(command, timeout: timeout);+ for (final line in '${result.stdout}\n${result.stderr}'.split('\n')) {+ if (line.trim().isNotEmpty) onOutput(line);+ }+ return result;+ }++ final process = await _start(shell, ['-l', '-c', wrapped]);+ final stdoutLines = <String>[];+ final stderrLines = <String>[];+ final stdoutSubscription = process.stdout+ .transform(utf8.decoder)+ .transform(const LineSplitter())+ .listen((line) {+ stdoutLines.add(line);+ onOutput(line);+ });+ final stderrSubscription = process.stderr+ .transform(utf8.decoder)+ .transform(const LineSplitter())+ .listen((line) {+ stderrLines.add(line);+ onOutput(line);+ });+ final stdoutDone = stdoutSubscription.asFuture<void>();+ final stderrDone = stderrSubscription.asFuture<void>();+ var timedOut = false;+ final exit = timeout == null+ ? await process.exitCode+ : await process.exitCode.timeout(+ timeout,+ onTimeout: () {+ timedOut = true;+ process.kill();+ return 124;+ },+ );+ if (timedOut) {+ await stdoutSubscription.cancel();+ await stderrSubscription.cancel();+ } else {+ await Future.wait([stdoutDone, stderrDone]);+ }+ return ProcessResult(+ process.pid,+ exit,+ stdoutLines.join('\n'),+ stderrLines.join('\n'),+ );+ }++ String _manualCommandFor(EnvironmentStep step) => switch (step) {+ EnvironmentStep.clipboard =>+ 'sudo apt-get install -y ${_linuxClipboardPackage() ?? 'xclip or wl-clipboard'}',+ EnvironmentStep.tmux =>+ _isMacOS+ ? 'brew install tmux && tmux -V'+ : 'sudo apt-get install -y tmux && tmux -V',+ EnvironmentStep.harness =>+ '$kHarnessDesktopInstallCommand && harness version',+ };++ String _resultText(ProcessResult result) {+ final text = '${result.stderr}\n${result.stdout}'.trim();+ return text.length <= 700 ? text : text.substring(text.length - 700);+ }+}++extension on Iterable<EnvironmentStep> {+ EnvironmentStep? get firstOrNull => isEmpty ? null : first;+}diff --git a/mobile/lib/clipboard/native_clipboard.dart b/mobile/lib/clipboard/native_clipboard.dartnew file mode 100644index 000000000..0422c3508--- /dev/null+++ b/mobile/lib/clipboard/native_clipboard.dart@@ -0,0 +1,59 @@+import 'dart:io';++import 'package:flutter/services.dart';++/// Flutter's own `Clipboard` (package:flutter/services.dart) only ever exposes `text/plain` — see+/// `widgets/terminal_panel.dart`'s `_paste()`. Reading a real IMAGE off the clipboard (a+/// screenshot, "Copy Image" from a browser, ...) needs a native round trip instead: NSPasteboard on+/// macOS (`macos/Runner/MainFlutterWindow.swift`), the GTK clipboard on Linux+/// (`linux/runner/my_application.cc`). Both answer over the same channel name and method, so this+/// wrapper is the one place call sites need to know about.+class NativeClipboard {+ NativeClipboard._();++ static const MethodChannel _channel = MethodChannel(+ 'harness/clipboard_image',+ );++ /// Reads the system clipboard for an image, returned as PNG bytes.+ ///+ /// Returns `null` on any platform without a native handler for this channel (Windows — the+ /// runner is unexercised, see CLAUDE.md — and any platform that isn't macOS/Linux) or when the+ /// clipboard genuinely holds no image, so call sites can use one check to fall through to+ /// today's text-paste behavior either way.+ static Future<Uint8List?> readImagePng() async {+ if (!Platform.isMacOS && !Platform.isLinux) return null;+ try {+ final bytes = await _channel.invokeMethod<Uint8List>('readImagePng');+ return bytes;+ } on MissingPluginException {+ return null;+ } catch (_) {+ return null;+ }+ }++ /// Writes `pngBytes` onto the system clipboard, replacing whatever was there — the LOCAL half+ /// of native image drag-drop (see `_dropImage` in `widgets/pane_grid.dart`): when the pane's+ /// machine is this same computer, the app puts the bytes on ITS OWN clipboard directly instead+ /// of sending them over the terminal wire, then forwards a Ctrl+V so the engine reads them+ /// exactly as it already does for an ordinary local clipboard paste.+ ///+ /// Returns `false` on any platform without a native handler for this channel, or when the+ /// native side could not decode/write the bytes — callers should treat that as "could not do+ /// the local shortcut" rather than surfacing a crash.+ static Future<bool> writeImagePng(Uint8List pngBytes) async {+ if (!Platform.isMacOS && !Platform.isLinux) return false;+ try {+ final wrote = await _channel.invokeMethod<bool>(+ 'writeImagePng',+ pngBytes,+ );+ return wrote ?? false;+ } on MissingPluginException {+ return false;+ } catch (_) {+ return false;+ }+ }+}diff --git a/mobile/lib/core/agent_preference.dart b/mobile/lib/core/agent_preference.dartnew file mode 100644index 000000000..7f0cf9585--- /dev/null+++ b/mobile/lib/core/agent_preference.dart@@ -0,0 +1,35 @@+import 'local_key_value_store.dart';++/// Remembers an agent choice, independently of a machine, profile or permission.+class AgentPreference {+ AgentPreference(this.storage);+ final LocalKeyValueStore? storage;+ static const _key = 'new_agent_engine';+ String? value;+ Future<void>? _loading;+ Future<void> _writes = Future.value();+ int _revision = 0;++ Future<void> load() => _loading ??= _read();+ Future<void> _read() async {+ final revision = _revision;+ try {+ final stored = await storage?.read(_key);+ if (revision == _revision && revision == 0) value = stored;+ } catch (_) {+ /* A missing preference never blocks a new agent. */+ }+ }++ Future<void> select(String engine) {+ _revision++;+ value = engine;+ return _writes = _writes.then((_) async {+ try {+ await storage?.write(_key, engine);+ } catch (_) {+ /* Keep the current choice usable if persistence fails. */+ }+ });+ }+}diff --git a/mobile/lib/core/app_version.dart b/mobile/lib/core/app_version.dartnew file mode 100644index 000000000..8a2271222--- /dev/null+++ b/mobile/lib/core/app_version.dart@@ -0,0 +1,37 @@+import 'dart:io';++import 'package:package_info_plus/package_info_plus.dart';++/// The version of the build currently running.+///+/// `flutter build linux` has no equivalent of Xcode's Info.plist stamping —+/// there is nowhere inside a Linux build for the release version to live, so+/// [PackageInfo.fromPlatform] would just return `pubspec.yaml`'s placeholder+/// (`1.0.0+1`, deliberately never bumped — see RELEASE.md). The Linux release+/// script (`scripts/upload-desktop-linux.sh`) instead writes a plain+/// `version.txt` next to the built executable; this reads that back when it+/// exists and falls through to [PackageInfo] everywhere else — macOS,+/// Windows, or a Linux dev build with no packaged `version.txt`.+Future<String> runningAppVersion({+ String? executablePath,+ Future<String> Function()? packageInfoVersion,+}) async {+ if (Platform.isLinux) {+ final exe = File(executablePath ?? Platform.resolvedExecutable);+ final versionFile = File('${exe.parent.path}/version.txt');+ try {+ // Read synchronously. It is a dozen bytes sitting next to the executable,+ // and an async read of it never completes inside flutter_test's+ // fake-async zone: every widget test on a Linux host would sit forever on+ // this line and paint the em dash the FutureBuilder falls back to, while+ // the same widget showed a version on macOS (which skips this branch).+ final raw = versionFile.readAsStringSync().trim();+ if (raw.isNotEmpty) return raw;+ } catch (_) {+ // Not a packaged build (no version.txt) — fall through below.+ }+ }+ return packageInfoVersion != null+ ? packageInfoVersion()+ : (await PackageInfo.fromPlatform()).version;+}diff --git a/mobile/lib/core/apple_fonts.dart b/mobile/lib/core/apple_fonts.dartnew file mode 100644index 000000000..3a58f5b49--- /dev/null+++ b/mobile/lib/core/apple_fonts.dart@@ -0,0 +1,11 @@+import 'dart:io' show Platform;++/// Whether this OS ships Apple's system fonts — SF Pro, SF Mono (CoreText's+/// `.AppleSystemUIFont*` aliases) and Menlo.+///+/// The font chains used to ask `Platform.isMacOS`, which sent iOS down the+/// Linux chain: every family there (DejaVu, Ubuntu, Noto) is missing on an+/// iPhone, so the terminal fell through to a proportional face and its grid+/// came apart. iOS resolves the same CoreText faces as a Mac, so it takes the+/// same chain.+bool get hasAppleFonts => Platform.isMacOS || Platform.isIOS;diff --git a/mobile/lib/core/build_identity.dart b/mobile/lib/core/build_identity.dartnew file mode 100644index 000000000..f73f90e23--- /dev/null+++ b/mobile/lib/core/build_identity.dart@@ -0,0 +1 @@+const desktopAppName = 'Harness';diff --git a/mobile/lib/core/codex_profiles.dart b/mobile/lib/core/codex_profiles.dartnew file mode 100644index 000000000..583287bf3--- /dev/null+++ b/mobile/lib/core/codex_profiles.dart@@ -0,0 +1,16 @@+/// A reference to an existing Codex state folder, reported by the harness CLI running on the+/// machine an agent will launch on (`AppNotifier.listCodexProfiles`/`linkCodexProfile`). This app+/// never scans a filesystem itself: discovery runs on that machine, which is what makes it work for+/// a remote machine too. No credentials are copied — this is a path and a display label only.+class LocalCodexProfile {+ const LocalCodexProfile(this.path, this.label);++ final String path;+ final String label;++ factory LocalCodexProfile.fromJson(Map<String, dynamic> json) =>+ LocalCodexProfile(+ json['path'] as String,+ json['label'] as String? ?? json['path'] as String,+ );+}diff --git a/mobile/lib/core/config.dart b/mobile/lib/core/config.dartnew file mode 100644index 000000000..24ba266c2--- /dev/null+++ b/mobile/lib/core/config.dart@@ -0,0 +1,29 @@+/// Runtime configuration for the desktop 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',+ });++ static const AppConfig dev = AppConfig(+ apiBaseUrl: 'https://harness-api.autonomous.ai',+ autonomousEnv: 'prod',+ );++ /// HTTPS->wss, HTTP->ws for the hub endpoint.+ String get wsBaseUrl {+ final uri = Uri.parse(apiBaseUrl);+ final scheme = uri.scheme == 'https' ? 'wss' : 'ws';+ return Uri(+ scheme: scheme,+ host: uri.host,+ port: uri.hasPort ? uri.port : null,+ ).toString().replaceFirst(RegExp(r'/$'), '');+ }+}diff --git a/mobile/lib/core/crash_log.dart b/mobile/lib/core/crash_log.dartnew file mode 100644index 000000000..5131aea05--- /dev/null+++ b/mobile/lib/core/crash_log.dart@@ -0,0 +1,92 @@+import 'dart:io';++import 'package:flutter/foundation.dart';++import '../logging/app_log.dart';+import 'harness_file_store.dart';+import 'test_run.dart';++/// Where a released build writes the errors nobody would otherwise see.+///+/// `debugPrint` and the default `FlutterError` handler both end at stderr, and+/// a `.app` launched from Finder has no stderr anyone reads. The practical+/// result is that every crash so far has reached us as a photograph of the+/// frozen pane — which says what the message was and nothing about where it+/// came from. A stack trace names the line; a screenshot cannot.+///+/// Everything here is best-effort and bounded. Diagnostics must never be the+/// reason something fails.+class CrashLog {+ static const _maxBytes = 256 * 1024;++ @visibleForTesting+ static File? testFile;++ static File get _file =>+ testFile ?? File('${HarnessFileStore.defaultDirectoryPath()}/errors.log');++ static void record(Object error, StackTrace? stackTrace, {String? context}) {+ // Mirrored into the day's app log as well, and the two are not redundant:+ // errors.log answers "what threw" for all time, while the daily log puts the+ // same failure back among the lines that led to it. A crash whose stack+ // names a line still needs its ten preceding lines to be explicable.+ // FileAppLog's burst filter is what keeps a per-frame exception from+ // fsyncing the UI isolate to a halt; this file's own truncation is not+ // enough for that, which is why the mirror goes through appLog rather than+ // the other way round.+ appLog.failure(+ context ?? 'crash',+ 'uncaught',+ error: error,+ stackTrace: stackTrace,+ );+ if (kUnderTest && testFile == null) return;+ try {+ final file = _file;+ // The directory may not exist yet, and the first run is exactly when this+ // matters: an error thrown while the environment is still being+ // provisioned lands before anything has written `~/.harness/desktop-app`.+ // Without this the whole crash log silently did nothing on a fresh+ // machine — the one machine whose crashes we most need the stack for.+ file.parent.createSync(recursive: true);+ // Truncate rather than rotate: this is read by a person looking into a+ // fault that just happened, so the RECENT end is the valuable end, and a+ // second file to manage buys nothing.+ if (file.existsSync() && file.lengthSync() > _maxBytes) {+ file.writeAsStringSync('');+ }+ final where = context == null ? '' : ' [$context]';+ file.writeAsStringSync(+ '${DateTime.now().toIso8601String()}$where $error\n'+ '${stackTrace ?? StackTrace.current}\n\n',+ mode: FileMode.append,+ );+ } catch (_) {+ // See above.+ }+ }++ /// Route the framework's own error channels here as well.+ ///+ /// Both are needed and they catch different things: [FlutterError.onError]+ /// covers build/layout/paint and anything reported through the framework,+ /// while [PlatformDispatcher.onError] is the last stop for errors escaping an+ /// async gap — which is most of this app, since terminal frames, sockets and+ /// timers all arrive that way.+ ///+ /// The default handler is still called, so nothing that used to be printed+ /// stops being printed; this only adds a copy that survives the session.+ static void install() {+ final previousFlutterError = FlutterError.onError;+ FlutterError.onError = (details) {+ record(details.exception, details.stack, context: 'flutter');+ previousFlutterError?.call(details);+ };++ final previousPlatformError = PlatformDispatcher.instance.onError;+ PlatformDispatcher.instance.onError = (error, stack) {+ record(error, stack, context: 'async');+ return previousPlatformError?.call(error, stack) ?? false;+ };+ }+}diff --git a/mobile/lib/core/engine_availability.dart b/mobile/lib/core/engine_availability.dartnew file mode 100644index 000000000..86564cb66--- /dev/null+++ b/mobile/lib/core/engine_availability.dart@@ -0,0 +1,105 @@+/// Whether one engine exists on one machine, as that machine answered it.+///+/// The New Agent dialog lists every engine Harness supports; a machine holds+/// whichever subset someone installed on it. Until this existed the difference+/// only surfaced as a failed create — tmux ran a command that was not there and+/// the pane said `command not found` — which is a late and confusing way to+/// learn that Hermes was never on this box.+///+/// **Answered per machine, never computed here.** A developer's Mac and the+/// Docker rig in the CLI repo routinely disagree (the rig ships exactly one+/// engine on purpose), and so do two laptops on one account. The app asks the+/// machine (`engines_probe`) and renders what comes back; deciding locally+/// would be wrong for precisely the remote case the feature exists for.+library;++class EngineAvailability {+ const EngineAvailability({+ required this.engine,+ required this.installed,+ this.command,+ this.supportsCodexHome = false,+ this.installable = false,+ this.installCommand,+ });++ final String engine;++ /// Does the launch command resolve as an existing executable file, in the+ /// same interactive shell a create launches through?+ ///+ /// That shell is the point: a detached daemon does not carry the user's PATH,+ /// and the probe additionally tests that what resolved is a real file — so a+ /// dangling symlink (a `hermes` pointing into a deleted venv) reads as not+ /// installed, which is the state a bare `command -v` gets wrong.+ final bool installed;++ /// The command that was probed — `command[0]` of a launch. Null when the+ /// machine could not name one, which on a real box means the binary is+ /// ambiguous rather than absent (the `agent` alias Cursor and Grok share).+ final String? command;++ /// Explicit capability: older CLIs otherwise ignore a requested profile.+ final bool supportsCodexHome;++ /// Whether this machine can be offered an install for it. False when the+ /// engine is already there, and false when Harness has no line to cite.+ final bool installable;++ /// The exact line that would run, as the machine that would run it named it.+ /// Shown before the click: installing software on someone's computer — and+ /// [installable] covers remote ones — is not a thing to do unannounced.+ final String? installCommand;++ static EngineAvailability? fromJson(Object? raw) {+ if (raw is! Map) return null;+ final engine = raw['engine'];+ if (engine is! String || engine.isEmpty) return null;+ final command = raw['command'];+ final installCommand = raw['installCommand'];+ return EngineAvailability(+ engine: engine,+ installed: raw['installed'] == true,+ command: command is String && command.isNotEmpty ? command : null,+ supportsCodexHome: engine == 'codex' && raw['supportsCodexHome'] == true,+ installable: raw['installable'] == true,+ installCommand: installCommand is String && installCommand.isNotEmpty+ ? installCommand+ : null,+ );+ }+}++/// One machine's answers, plus enough state to tell "still asking" apart from+/// "asked, and it has nothing".+///+/// Those two must not render the same — the app's rule everywhere else, and it+/// matters most here: labelling a row "not installed" while the probe is still+/// running is a claim the app has not earned, and it would send someone to+/// install an engine they already have.+class MachineEngines {+ MachineEngines();++ final Map<String, EngineAvailability> byEngine = {};++ /// True once a probe has answered at least once. Never reset by a refresh, so+ /// a re-probe leaves the rows already on screen rather than blanking them.+ bool loaded = false;++ /// A probe is in flight. Held so a dialog opening twice does not start two.+ Future<void>? inFlight;++ /// Set when the machine could not answer. The dialog stays usable: an unknown+ /// engine is offered exactly as it was before this feature existed.+ String? error;++ EngineAvailability? operator [](String engine) => byEngine[engine];++ void replace(Iterable<EngineAvailability> entries) {+ byEngine+ ..clear()+ ..addEntries(entries.map((entry) => MapEntry(entry.engine, entry)));+ loaded = true;+ error = null;+ }+}diff --git a/mobile/lib/core/harness_cli_runner.dart b/mobile/lib/core/harness_cli_runner.dartnew file mode 100644index 000000000..0cbc18d69--- /dev/null+++ b/mobile/lib/core/harness_cli_runner.dart@@ -0,0 +1,214 @@+import 'host_platform.dart';+import 'dart:io';++import '../logging/cli_transcript.dart';++/// Runs the Harness CLI owned by this desktop app without depending on a+/// terminal shell, its rc files, or Finder's inherited PATH.+///+/// The normal path is the managed tier: `~/.harness/runtime/current-node` — a+/// private, checksum-verified Node that the `harness` installer provisions and+/// records — paired with the `~/.harness/cli/cli.js` bundle,+/// invoked as `<node> <cli.js> …` with no shell in between. Because both are+/// absolute paths beneath [harnessHome], launching Harness from Finder and from+/// Terminal have identical runtime behavior; PATH never enters into it.+///+/// Behind that come the installed `~/.local/bin/harness` launcher and finally+/// bare `harness` on PATH, which cover a developer-managed install and the+/// window before the first provisioning run has finished.+class HarnessCliRunner {+ final Directory harnessHome;+ final Map<String, String> environment;+ final Future<ProcessResult> Function(+ String executable,+ List<String> arguments, {+ Map<String, String>? environment,+ })+ _runProcess;+ final Future<Process> Function(+ String executable,+ List<String> arguments, {+ Map<String, String>? environment,+ })+ _startProcess;++ HarnessCliRunner({+ Directory? harnessHome,+ Map<String, String>? environment,+ Future<ProcessResult> Function(+ String executable,+ List<String> arguments, {+ Map<String, String>? environment,+ })?+ runProcess,+ Future<Process> Function(+ String executable,+ List<String> arguments, {+ Map<String, String>? environment,+ })?+ startProcess,+ }) : environment = environment ?? Platform.environment,+ harnessHome = harnessHome ?? Directory(_defaultHarnessHome()),+ _runProcess = runProcess ?? Process.run,+ _startProcess = startProcess ?? Process.start;++ static String _defaultHarnessHome() {+ // HOME, then USERPROFILE: Windows sets only the latter, so a launch from Explorer threw here+ // before any UI existed to report it.+ final home = Platform.environment['HOME'];+ final profile = Platform.environment['USERPROFILE'];+ final resolved = home != null && home.isNotEmpty+ ? home+ : (profile != null && profile.isNotEmpty ? profile : containerHome);+ if (resolved == null || resolved.isEmpty) {+ throw StateError('Could not resolve the current user home directory');+ }+ return '$resolved${Platform.pathSeparator}.harness';+ }++ Directory get _runtimeDirectory =>+ Directory('${harnessHome.path}${Platform.pathSeparator}runtime');++ File get _currentNodeFile =>+ File('${_runtimeDirectory.path}${Platform.pathSeparator}current-node');++ File get _cliFile => File(+ '${harnessHome.path}${Platform.pathSeparator}cli${Platform.pathSeparator}cli.js',+ );++ /// Builds the direct invocation used by [run] and [start]. Public for+ /// focused tests and diagnostics; callers should generally call [run].+ Future<HarnessCliInvocation> resolve(List<String> arguments) async {+ final node = await _managedNode();+ if (node != null && await _cliFile.exists()) {+ return HarnessCliInvocation(+ executable: node.path,+ arguments: [_cliFile.path, ...arguments],+ environment: _commandEnvironment(),+ source: HarnessCliSource.managed,+ );+ }++ final home = _home();+ if (home != null && home.isNotEmpty) {+ final launcher = File(+ '$home${Platform.pathSeparator}.local${Platform.pathSeparator}bin${Platform.pathSeparator}harness',+ );+ if (await launcher.exists()) {+ return HarnessCliInvocation(+ executable: launcher.path,+ arguments: arguments,+ environment: _commandEnvironment(),+ source: HarnessCliSource.launcher,+ );+ }+ }++ return HarnessCliInvocation(+ executable: 'harness',+ arguments: arguments,+ environment: _commandEnvironment(),+ source: HarnessCliSource.path,+ );+ }++ Future<ProcessResult> run(List<String> arguments) async {+ final invocation = await resolve(arguments);+ return logProcessRun(+ _displayLine(arguments),+ () => _runProcess(+ invocation.executable,+ invocation.arguments,+ environment: invocation.environment,+ ),+ );+ }++ Future<Process> start(List<String> arguments) async {+ final invocation = await resolve(arguments);+ return logProcessStart(+ _displayLine(arguments),+ () => _startProcess(+ invocation.executable,+ invocation.arguments,+ environment: invocation.environment,+ ),+ );+ }++ /// The invocation as a person reads it — `harness auth status --json`.+ ///+ /// The [arguments] this was asked for, never [HarnessCliInvocation.arguments]:+ /// on the managed tier the real argv is `<node> <cli.js> …`, two absolute+ /// paths of noise in front of the only part that says what ran.+ static String _displayLine(List<String> arguments) =>+ 'harness ${arguments.join(' ')}';++ Future<File?> _managedNode() async {+ try {+ final raw = (await _currentNodeFile.readAsString()).trim();+ if (raw.isEmpty) return null;+ final runtimeRoot =+ '${_runtimeDirectory.absolute.path}${Platform.pathSeparator}';+ if (!raw.startsWith(runtimeRoot)) return null;+ final node = File(raw);+ return await node.exists() ? node : null;+ } on FileSystemException {+ return null;+ }+ }++ String? _home() {+ final home = environment['HOME'];+ if (home != null && home.isNotEmpty) return home;+ final profile = environment['USERPROFILE'];+ return profile != null && profile.isNotEmpty ? profile : null;+ }++ Map<String, String> _commandEnvironment() {+ final home = _home();+ final launcherDirectory = home == null || home.isEmpty+ ? null+ : '$home${Platform.pathSeparator}.local${Platform.pathSeparator}bin';+ final path = environment['PATH'] ?? '';+ // PATH is ';'-separated on Windows. Joining with ':' there does not just fail to prepend the+ // launcher directory — it welds it onto the first real entry and destroys that one too.+ final pathSeparator = Platform.isWindows ? ';' : ':';+ final commandEnvironment = <String, String>{+ ...environment,+ if (launcherDirectory != null)+ 'PATH': path.isEmpty+ ? launcherDirectory+ : '$launcherDirectory$pathSeparator$path',+ };+ final configuredLocale =+ commandEnvironment['LC_ALL'] ??+ commandEnvironment['LC_CTYPE'] ??+ commandEnvironment['LANG'];+ if ((Platform.isMacOS || Platform.isLinux) &&+ (configuredLocale == null ||+ !RegExp(+ r'utf-?8',+ caseSensitive: false,+ ).hasMatch(configuredLocale))) {+ commandEnvironment['LC_ALL'] = 'C.UTF-8';+ }+ return commandEnvironment;+ }+}++enum HarnessCliSource { managed, launcher, path }++class HarnessCliInvocation {+ final String executable;+ final List<String> arguments;+ final Map<String, String> environment;+ final HarnessCliSource source;++ const HarnessCliInvocation({+ required this.executable,+ required this.arguments,+ required this.environment,+ required this.source,+ });+}diff --git a/mobile/lib/core/harness_file_store.dart b/mobile/lib/core/harness_file_store.dartnew file mode 100644index 000000000..ced3f888d--- /dev/null+++ b/mobile/lib/core/harness_file_store.dart@@ -0,0 +1,227 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'host_platform.dart';+import 'viewer_mode.dart';+import 'local_key_value_store.dart';++/// Versioned Harness desktop state stored under the user's Harness home.+///+/// The file contains credentials and E2EE key material. Its parent directory+/// is private to the current user and every file created here is mode 0600 on+/// POSIX platforms. Values are never logged.+class HarnessFileStore implements BatchLocalKeyValueStore {+ static const schemaVersion = 1;+ // Separate from production; the CLI still owns shared authentication and links.+ //+ // A viewer build is a different product holding a different session — its own+ // SSO tokens and its own E2EE identity — so it lives BESIDE the desktop one+ // rather than in it. On a Mac, where the viewer path is developed with+ // `--dart-define=HARNESS_VIEWER_MODE=true`, the two would otherwise overwrite+ // each other's state.+ static final String directoryName = kViewerMode+ ? 'viewer-app-v2'+ : 'desktop-app-v2';+ static const fileName = 'state.json';+ static const lockFileName = 'state.lock';++ static final HarnessFileStore shared = HarnessFileStore();+ static final Map<String, Future<void>> _pathTails = {};++ final Directory directory;++ HarnessFileStore({Directory? directory})+ : directory = directory ?? Directory(defaultDirectoryPath());++ /// [name] names the sibling under `~/.harness`; it defaults to this store's own.+ static String defaultDirectoryPath({+ Map<String, String>? environment,+ String? name,+ }) {+ final env = environment ?? Platform.environment;+ var home = env['HOME'];+ if ((home == null || home.isEmpty) && Platform.isWindows) {+ home = env['USERPROFILE'];+ if (home == null || home.isEmpty) {+ final drive = env['HOMEDRIVE'];+ final path = env['HOMEPATH'];+ if (drive != null && path != null) home = '$drive$path';+ }+ }+ if (home == null || home.isEmpty) home = containerHome;+ if (home == null || home.isEmpty) {+ throw StateError('Could not resolve the current user home directory');+ }+ return _join(_join(home, '.harness'), name ?? directoryName);+ }++ File get stateFile => File(_join(directory.path, fileName));+ File get _lockFile => File(_join(directory.path, lockFileName));++ @override+ Future<String?> read(String key) =>+ _serialized(() async => (await _readDocument())[key]);++ /// One lock and document read for related preferences. The snapshot is scoped+ /// to this call: later reads still observe intervening writes, including+ /// writes from another store or process. Unrequested credentials never leave+ /// this operation.+ @override+ Future<Map<String, String?>> readMany(Iterable<String> keys) {+ final requested = keys.toSet();+ if (requested.isEmpty) return Future.value(const <String, String?>{});+ return _serialized(() async {+ final values = await _readDocument();+ return {for (final key in requested) key: values[key]};+ });+ }++ @override+ Future<void> write(String key, String value) => _serialized(() async {+ final values = await _readDocument();+ values[key] = value;+ await _writeDocument(values);+ });++ @override+ Future<void> delete(String key) => _serialized(() async {+ final values = await _readDocument();+ if (values.remove(key) == null) return;+ await _writeDocument(values);+ });++ Future<T> _serialized<T>(Future<T> Function() operation) {+ final result = Completer<T>();+ final path = directory.absolute.path;+ final previous = _pathTails[path] ?? Future<void>.value();+ late final Future<void> queued;+ queued = previous.then((_) async {+ try {+ result.complete(await _withFileLock(operation));+ } catch (error, stack) {+ result.completeError(error, stack);+ }+ });+ _pathTails[path] = queued;+ unawaited(+ queued.whenComplete(() {+ if (identical(_pathTails[path], queued)) _pathTails.remove(path);+ }),+ );+ return result.future;+ }++ Future<T> _withFileLock<T>(Future<T> Function() operation) async {+ await _ensurePrivateDirectory();+ final lock = await _lockFile.open(mode: FileMode.append);+ try {+ await _makePrivateFile(_lockFile);+ await lock.lock(FileLock.exclusive);+ return await operation();+ } finally {+ try {+ await lock.unlock();+ } finally {+ await lock.close();+ }+ }+ }++ Future<Map<String, String>> _readDocument() async {+ final file = stateFile;+ if (!await file.exists()) return <String, String>{};+ try {+ final decoded = jsonDecode(await file.readAsString());+ if (decoded is! Map<String, dynamic>) {+ throw const FormatException('state root must be an object');+ }+ final version = decoded['version'];+ if (version is int && version > schemaVersion) {+ throw UnsupportedStateVersionException(version);+ }+ if (version != schemaVersion || decoded['values'] is! Map) {+ throw const FormatException('unsupported state document shape');+ }+ final values = <String, String>{};+ for (final entry in (decoded['values'] as Map).entries) {+ if (entry.key is! String || entry.value is! String) {+ throw const FormatException('state values must be strings');+ }+ values[entry.key as String] = entry.value as String;+ }+ return values;+ } on UnsupportedStateVersionException {+ rethrow;+ } on Object {+ await _quarantineCorruptState(file);+ return <String, String>{};+ }+ }++ Future<void> _writeDocument(Map<String, String> values) async {+ final suffix = '${pid}_${DateTime.now().microsecondsSinceEpoch}';+ final temporary = File(_join(directory.path, '.$fileName.$suffix.tmp'));+ try {+ await temporary.writeAsString(+ '${const JsonEncoder.withIndent(' ').convert({'version': schemaVersion, 'values': values})}\n',+ flush: true,+ );+ await _makePrivateFile(temporary);+ await temporary.rename(stateFile.path);+ await _makePrivateFile(stateFile);+ } finally {+ if (await temporary.exists()) await temporary.delete();+ }+ }++ Future<void> _quarantineCorruptState(File file) async {+ final timestamp = DateTime.now().toUtc().toIso8601String().replaceAll(+ RegExp(r'[^0-9A-Za-z]'),+ '',+ );+ var backup = File(_join(directory.path, 'state.corrupt-$timestamp.json'));+ var duplicate = 0;+ while (await backup.exists()) {+ duplicate++;+ backup = File(+ _join(directory.path, 'state.corrupt-$timestamp-$duplicate.json'),+ );+ }+ await file.rename(backup.path);+ await _makePrivateFile(backup);+ }++ Future<void> _ensurePrivateDirectory() async {+ await directory.create(recursive: true);+ await _chmod(directory.path, '700');+ }++ Future<void> _makePrivateFile(File file) => _chmod(file.path, '600');++ /// Windows has no POSIX modes, and a phone neither needs one — the app's+ /// sandbox is already private to it — nor can spawn `/bin/chmod` at all.+ Future<void> _chmod(String path, String mode) async {+ if (Platform.isWindows || isMobileHost) return;+ final result = await Process.run('/bin/chmod', [mode, path]);+ if (result.exitCode != 0) {+ throw FileSystemException('Could not set mode $mode', path);+ }+ }++ static String _join(String left, String right) {+ if (left.endsWith(Platform.pathSeparator)) return '$left$right';+ return '$left${Platform.pathSeparator}$right';+ }+}++class UnsupportedStateVersionException implements Exception {+ final int version;++ const UnsupportedStateVersionException(this.version);++ @override+ String toString() =>+ 'Desktop state schema $version is newer than supported schema '+ '${HarnessFileStore.schemaVersion}; refusing to overwrite it';+}diff --git a/mobile/lib/core/host_platform.dart b/mobile/lib/core/host_platform.dartnew file mode 100644index 000000000..91db6e27e--- /dev/null+++ b/mobile/lib/core/host_platform.dart@@ -0,0 +1,34 @@+import 'dart:io';++/// True where the app is a guest inside a sandboxed container rather than a+/// desktop process of its own: iOS and Android.+bool get isMobileHost => Platform.isIOS || Platform.isAndroid;++/// The app's own container, on the platforms that give a process no `HOME`.+///+/// An app on iOS or Android does not live in a user's home directory; it lives+/// in a private container, and `Platform.environment` there carries no `HOME`+/// to point at it. The container root is the parent of the temporary directory+/// the platform DOES name — `NSTemporaryDirectory()` is `<container>/tmp`, and+/// Android's cache directory is `<data dir>/cache` — which makes it reachable+/// synchronously, without a plugin.+///+/// Synchronously matters: the callers read it from field initializers and from+/// `installFileLogs`, which is deliberately not `async` so that the first lines+/// about starting up are not lost to a directory probe. Not adding a plugin+/// matters too — registering one rewrites the macOS SPM package list for every+/// desktop build as well (see CLAUDE.md).+///+/// `null` off those platforms, so a desktop host with no `HOME` still fails the+/// way it always has rather than quietly writing somewhere unexpected.+///+String? get containerHome {+ if (!isMobileHost) return null;+ final container = Directory.systemTemp.parent.path;+ // An iOS app's container ROOT is not writable; `Library/Application Support`+ // is, and is where Apple expects state that is not user documents. Android's+ // data directory root is writable, so it takes the container as it is.+ return Platform.isIOS+ ? '$container/Library/Application Support'+ : container;+}diff --git a/mobile/lib/core/local_git_projects.dart b/mobile/lib/core/local_git_projects.dartnew file mode 100644index 000000000..d3e4d010b--- /dev/null+++ b/mobile/lib/core/local_git_projects.dart@@ -0,0 +1,337 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:path/path.dart' as p;++import 'models.dart';++/// Compatibility for this computer's older daemon. Reads only Git metadata;+/// directory watches invalidate the cache when a checkout or remote changes.+/// No Git processes, network calls, terminal reads, or work on the render path.+class LocalGitProjects {+ LocalGitProjects({required this.onChanged, DateTime Function()? now})+ : _now = now ?? DateTime.now;+ final void Function() onChanged;+ final DateTime Function() _now;+ static const _cacheAge = Duration(minutes: 1);+ final _entries = <String, _LocalGitEntry>{};+ bool _disposed = false;++ AgentProject? cached(String cwd) => _entries[cwd]?.project;++ Future<void> read(String cwd) {+ if (_disposed || !p.isAbsolute(cwd)) return Future.value();+ final existing = _entries[cwd];+ if (existing != null) {+ if (existing.pending != null) return existing.pending!;+ // Even a live watcher can miss a rename or a coalesced OS event. Check+ // again on ordinary discovery after the TTL; there is no polling timer.+ if (_now().difference(existing.checkedAt) < _cacheAge) {+ return Future.value();+ }+ return _refresh(cwd, existing);+ }+ if (_entries.length >= 256) {+ _entries.remove(_entries.keys.first)?.dispose();+ }+ final entry = _LocalGitEntry();+ _entries[cwd] = entry;+ return _refresh(cwd, entry);+ }++ Future<void> _refresh(String cwd, _LocalGitEntry entry) {+ if (_disposed || entry.disposed) return Future.value();+ if (entry.pending != null) {+ entry.dirty = true;+ return entry.pending!;+ }+ return entry.pending = _refreshEntry(cwd, entry);+ }++ Future<void> _refreshEntry(String cwd, _LocalGitEntry entry) async {+ try {+ do {+ entry.dirty = false;+ await _resolve(cwd, entry);+ } while (entry.dirty && !_disposed && !entry.disposed);+ } finally {+ entry.checkedAt = _now();+ entry.pending = null;+ }+ }++ Future<void> _resolve(String cwd, _LocalGitEntry entry) async {+ final targets = <String, Set<String>>{};+ void watch(String directory, Set<String> names) =>+ (targets[directory] ??= {}).addAll(names);+ try {+ if (!await Directory(cwd).exists()) {+ _publish(entry, null);+ return;+ }+ watch(p.normalize(cwd), {'.git'});+ var root = p.normalize(cwd);+ String? gitDir;+ for (var depth = 0; depth < 32; depth++) {+ final marker = p.join(root, '.git');+ final type = await FileSystemEntity.type(marker);+ if (type == FileSystemEntityType.directory) {+ gitDir = marker;+ break;+ }+ if (type == FileSystemEntityType.file) {+ targets.clear();+ watch(root, {'.git'});+ final pointer = await _text(marker);+ if (pointer?.startsWith('gitdir: ') == true) {+ final path = pointer!.substring(8).trim();+ if (path.isNotEmpty) gitDir = p.normalize(p.join(root, path));+ }+ break;+ }+ final parent = p.dirname(root);+ if (parent == root) break;+ root = parent;+ }+ if (gitDir == null) {+ _publish(entry, null);+ return;+ }+ // The working tree owns the .git pointer (and directory replacement),+ // while HEAD/config may live elsewhere. Keep watching that connection.+ targets.clear();+ watch(root, {'.git'});+ if (!await Directory(gitDir).exists()) {+ _publish(entry, null);+ return;+ }+ watch(gitDir, {'HEAD', 'commondir'});+ final shared = await _text(p.join(gitDir, 'commondir'));+ final common = shared == null+ ? gitDir+ : p.normalize(p.join(gitDir, shared.trim()));+ watch(common, {'config'});+ final head = (await _text(p.join(gitDir, 'HEAD')))?.trim();+ final config = await _text(p.join(common, 'config'));+ if (_disposed || entry.disposed) return;+ final branch = head?.startsWith('ref: refs/heads/') == true+ ? head!.substring(16)+ : head != null && RegExp(r'^[a-fA-F0-9]{40,64}$').hasMatch(head)+ ? 'Detached ${head.substring(0, 7)}'+ : null;+ final project = AgentProject.fromJson({+ 'name': p.basename(root),+ 'cwd': cwd,+ 'root': root,+ 'remote': _origin(config),+ 'branch': branch,+ });+ _publish(entry, project);+ } on FileSystemException {+ // A removed/unreadable working folder must not interfere with discovery.+ _publish(entry, null);+ } finally {+ if (!_disposed && !entry.disposed) _syncWatches(cwd, entry, targets);+ }+ }++ void _publish(_LocalGitEntry entry, AgentProject? project) {+ if (_disposed || entry.disposed || entry.project == project) return;+ entry.project = project;+ onChanged();+ }++ void _invalidate(String cwd, _LocalGitEntry entry) {+ if (_disposed || entry.disposed) return;+ entry.debounce?.cancel();+ entry.debounce = Timer(const Duration(milliseconds: 100), () {+ entry.debounce = null;+ unawaited(_refresh(cwd, entry));+ });+ }++ void _syncWatches(+ String cwd,+ _LocalGitEntry entry,+ Map<String, Set<String>> targets,+ ) {+ entry.watchTargets = targets;+ for (final directory in entry.watchers.keys.toList()) {+ if (!targets.containsKey(directory)) {+ unawaited(entry.watchers.remove(directory)!.cancel());+ }+ }+ entry.retryWatchAt.removeWhere((path, _) => !targets.containsKey(path));+ for (final directory in targets.keys) {+ if (entry.watchers.containsKey(directory) ||+ entry.retryWatchAt[directory]?.isAfter(_now()) == true) {+ continue;+ }+ late StreamSubscription<FileSystemEvent> subscription;+ void lost() {+ if (_disposed ||+ entry.disposed ||+ entry.watchers[directory] != subscription) {+ return;+ }+ entry.watchers.remove(directory);+ unawaited(subscription.cancel());+ // Refresh the data once, but wait for later discovery to retry a+ // failed watch. A permanently unavailable watcher must not loop.+ entry.retryWatchAt[directory] = _now().add(_cacheAge);+ _invalidate(cwd, entry);+ }++ bool related(String path) =>+ p.normalize(path) == directory ||+ entry.watchTargets[directory]?.contains(p.basename(path)) == true;+ try {+ subscription = Directory(directory).watch().listen(+ (event) {+ if (_disposed ||+ entry.disposed ||+ entry.watchers[directory] != subscription) {+ return;+ }+ if (related(event.path) ||+ event is FileSystemMoveEvent &&+ event.destination != null &&+ related(event.destination!)) {+ if (event.isDirectory &&+ (event is FileSystemCreateEvent ||+ event is FileSystemDeleteEvent ||+ event is FileSystemMoveEvent)) {+ // A replacement can reuse the path while the OS watch still+ // follows the old directory. Rebind those subscriptions.+ final changed = {+ p.normalize(event.path),+ if (event is FileSystemMoveEvent && event.destination != null)+ p.normalize(event.destination!),+ };+ for (final watched in entry.watchers.keys.toList()) {+ if (changed.any(+ (path) => path == watched || p.isWithin(path, watched),+ )) {+ unawaited(entry.watchers.remove(watched)!.cancel());+ entry.retryWatchAt.remove(watched);+ }+ }+ }+ _invalidate(cwd, entry);+ }+ },+ onError: (Object _) => lost(),+ onDone: lost,+ cancelOnError: true,+ );+ entry.watchers[directory] = subscription;+ entry.retryWatchAt.remove(directory);+ } on FileSystemException {+ entry.retryWatchAt[directory] = _now().add(_cacheAge);+ } on UnsupportedError {+ entry.retryWatchAt[directory] = _now().add(_cacheAge);+ }+ }+ }++ Future<String?> _text(String path) async {+ try {+ final file = await File(path).open();+ try {+ // Bound the read itself, including a file growing during discovery.+ final bytes = await file.read(64 * 1024 + 1);+ return bytes.length <= 64 * 1024 ? utf8.decode(bytes) : null;+ } finally {+ await file.close();+ }+ } on FileSystemException {+ return null;+ } on FormatException {+ return null;+ }+ }++ String? _origin(String? config) {+ if (config == null) return null;+ var origin = false;+ for (final line in config.split('\n')) {+ final text = line.trim();+ if (text.startsWith('[')) {+ origin = RegExp(+ r'^\[remote\s+"origin"\]$',+ caseSensitive: false,+ ).hasMatch(text);+ } else if (origin) {+ final match = RegExp(+ r'^url\s*=\s*(.+)$',+ caseSensitive: false,+ ).firstMatch(text);+ if (match != null) return canonicalGitRemote(match.group(1)!);+ }+ }+ return null;+ }++ void dispose() {+ _disposed = true;+ for (final entry in _entries.values) {+ entry.dispose();+ }+ _entries.clear();+ }+}++String? canonicalGitRemote(String raw) {+ raw = raw.trim();+ if (raw.startsWith('"') && raw.endsWith('"')) {+ raw = raw.substring(1, raw.length - 1);+ }+ final scp = RegExp(r'^(?:[^@/\s]+@)?([^:/\s]+):([^\s]+)$').firstMatch(raw);+ final uri = Uri.tryParse(+ scp != null && !raw.contains('://')+ ? 'ssh://${scp.group(1)}/${scp.group(2)}'+ : raw,+ );+ if (uri == null ||+ !{'ssh', 'https', 'http', 'git'}.contains(uri.scheme) ||+ uri.host.isEmpty) {+ return null;+ }+ var path = uri.path+ .replaceAll(RegExp(r'^/+|/+$'), '')+ .replaceFirst(RegExp(r'\.git$', caseSensitive: false), '');+ if (path.isEmpty || RegExp(r'[\x00-\x20]').hasMatch(path)) return null;+ final host = uri.host.toLowerCase();+ if (host == 'github.com' || host == 'bitbucket.org') {+ path = path.toLowerCase();+ }+ final defaultPort = switch (uri.scheme) {+ 'ssh' => 22,+ 'git' => 9418,+ 'https' => 443,+ _ => 80,+ };+ final port = uri.hasPort && uri.port != defaultPort ? ':${uri.port}' : '';+ return '$host$port/$path';+}++class _LocalGitEntry {+ DateTime checkedAt = DateTime.fromMillisecondsSinceEpoch(0);+ AgentProject? project;+ Future<void>? pending;+ bool dirty = false;+ final watchers = <String, StreamSubscription<FileSystemEvent>>{};+ Map<String, Set<String>> watchTargets = {};+ final retryWatchAt = <String, DateTime>{};+ Timer? debounce;+ bool disposed = false;+ void dispose() {+ disposed = true;+ debounce?.cancel();+ for (final watcher in watchers.values) {+ unawaited(watcher.cancel());+ }+ watchers.clear();+ }+}diff --git a/mobile/lib/core/local_hostname.dart b/mobile/lib/core/local_hostname.dartnew file mode 100644index 000000000..8d96d271c--- /dev/null+++ b/mobile/lib/core/local_hostname.dart@@ -0,0 +1,15 @@+import 'dart:io';++/// The machine's name exactly as the OS gives it, or null when it has none.+///+/// Guarded because `localHostname` throws where the OS refuses to answer, and+/// its callers run inside builds — not a place to take an exception over a+/// label.+String? localHostnameOrNull() {+ try {+ final host = Platform.localHostname.trim();+ return host.isEmpty ? null : host;+ } catch (_) {+ return null;+ }+}diff --git a/mobile/lib/core/local_key_value_store.dart b/mobile/lib/core/local_key_value_store.dartnew file mode 100644index 000000000..106467ae8--- /dev/null+++ b/mobile/lib/core/local_key_value_store.dart@@ -0,0 +1,26 @@+abstract interface class LocalKeyValueStore {+ Future<String?> read(String key);++ Future<void> write(String key, String value);++ Future<void> delete(String key);+}++/// Stores that can read a group in one operation, preserving a single snapshot.+abstract interface class BatchLocalKeyValueStore implements LocalKeyValueStore {+ /// Returns only the requested keys. Missing values are represented by null.+ Future<Map<String, String?>> readMany(Iterable<String> keys);+}++extension LocalKeyValueStoreBatchRead on LocalKeyValueStore {+ /// Falls back to ordinary reads for stores without a batch operation.+ Future<Map<String, String?>> readMany(Iterable<String> keys) async {+ final store = this;+ if (store is BatchLocalKeyValueStore) return store.readMany(keys);+ final values = <String, String?>{};+ for (final key in keys.toSet()) {+ values[key] = await read(key);+ }+ return values;+ }+}diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dartnew file mode 100644index 000000000..f04bba77d--- /dev/null+++ b/mobile/lib/core/models.dart@@ -0,0 +1,425 @@+/// Data models mirroring the backend/web types.+library;++enum MachineAuthMode { managed, remote, self, provider }++enum ConnectionStatus { disconnected, connecting, connected, reconnecting }++/// Current SSO identity returned by GET /api/auth/me.+class CurrentUserProfile {+ final String? id;+ final String? name;+ final String email;+ final String? avatarUrl;++ const CurrentUserProfile({+ this.id,+ this.name,+ required this.email,+ this.avatarUrl,+ });++ const CurrentUserProfile.local()+ : id = null,+ name = 'Local session',+ email = 'local terminal',+ avatarUrl = null;++ factory CurrentUserProfile.fromMe(Map<String, dynamic> response) {+ final rawUser = response['user'];+ if (rawUser is! Map) {+ throw const FormatException('missing user profile');+ }+ final user = Map<String, dynamic>.from(rawUser);+ final email = user['email'];+ if (email is! String || email.trim().isEmpty) {+ throw const FormatException('missing user email');+ }+ final rawName = user['name'];+ final rawAvatar = response['avatarUrl'];+ return CurrentUserProfile(+ id: user['id'] is String ? user['id'] as String : null,+ name: rawName is String && rawName.trim().isNotEmpty+ ? rawName.trim()+ : null,+ email: email.trim(),+ avatarUrl: rawAvatar is String && rawAvatar.trim().isNotEmpty+ ? rawAvatar.trim()+ : null,+ );+ }++ String get displayName => name ?? email;++ String get initials {+ final source = (name ?? email).trim();+ if (source.isEmpty) return '?';+ final words = source.split(RegExp(r'\s+')).where((word) => word.isNotEmpty);+ final chars = words.take(2).map((word) => word[0].toUpperCase()).join();+ return chars.isEmpty ? '?' : chars;+ }+}++/// Control-plane machine (GET /api/machines).+class Machine {+ final String machineId;++ /// Legacy fixture-only field. Production `/api/machines` no longer exposes machine API keys.+ final String apiKey;+ final String? computerId;+ final MachineAuthMode authMode;+ final String? engine;+ final String? name;+ final String? hostname;+ final String? status;++ const Machine({+ required this.machineId,+ this.apiKey = '',+ this.computerId,+ required this.authMode,+ this.engine,+ this.name,+ this.hostname,+ this.status,+ });++ String get displayName => (name != null && name!.isNotEmpty)+ ? name!+ : 'machine-${machineId.length > 8 ? machineId.substring(0, 8) : machineId}';++ factory Machine.fromJson(Map<String, dynamic> j) => Machine(+ machineId: j['machineId'] as String,+ apiKey: j['apiKey'] as String? ?? '',+ computerId: j['computerId'] as String?,+ authMode: MachineAuthMode.values.firstWhere(+ (m) => m.name == j['authMode'],+ orElse: () => MachineAuthMode.managed,+ ),+ engine: j['engine'] as String?,+ name: j['name'] as String?,+ hostname: j['hostname'] as String?,+ status: j['status'] as String?,+ );++ Machine copyWith({String? name}) => Machine(+ machineId: machineId,+ apiKey: apiKey,+ computerId: computerId,+ authMode: authMode,+ engine: engine,+ name: name ?? this.name,+ hostname: hostname,+ status: status,+ );+}++/// Data-plane agent (RPC agents_list).+class Agent {+ final String id;+ final String? sessionId;+ final String name;+ final String? engine;+ final String? engineDisplayName;+ final String? engineIconHint;+ final String? codexHome;+ final String? parentAgentId;+ final AgentProject? project;+ final String status;+ final String launchState;+ final String? launchError;+ final String? launchDetail;+ final bool terminalAvailable;+ final String? terminalUnavailableReason;++ const Agent({+ required this.id,+ this.sessionId,+ required this.name,+ this.engine,+ this.engineDisplayName,+ this.engineIconHint,+ this.codexHome,+ this.parentAgentId,+ this.project,+ this.status = 'active',+ this.launchState = 'ready',+ this.launchError,+ this.launchDetail,+ this.terminalAvailable = false,+ this.terminalUnavailableReason,+ });++ factory Agent.fromJson(Map<String, dynamic> j) {+ final terminal = j['terminal'];+ final terminalMap = terminal is Map+ ? Map<String, dynamic>.from(terminal)+ : const <String, dynamic>{};+ final runtimes = terminalMap['runtimes'] is List+ ? terminalMap['runtimes'] as List+ : const [];+ final hasTmux = runtimes.any(+ (runtime) => runtime is Map && runtime['backend'] == 'tmux',+ );+ final advertisedAvailable = terminalMap['available'];+ final terminalAvailable = advertisedAvailable is bool+ ? advertisedAvailable+ : hasTmux;+ final launchRaw = j['launch'];+ final launch = launchRaw is Map+ ? Map<String, dynamic>.from(launchRaw)+ : const <String, dynamic>{};+ final launchState = switch (launch['state']) {+ 'starting' => 'starting',+ 'failed' => 'failed',+ _ => 'ready',+ };+ return Agent(+ id: j['id'] as String,+ sessionId: _safeLabel(j['sessionId']),+ name: j['name'] as String? ?? 'agent',+ engine: _safeEngine(j['engine']),+ engineDisplayName: _safeLabel(j['engineDisplayName']),+ engineIconHint: _safeLabel(j['engineIconHint']),+ codexHome: j['engine'] == 'codex' ? _safeCodexHome(j['codexHome']) : null,+ parentAgentId: _safeLabel(j['parentAgentId'] ?? j['parentId']),+ project: AgentProject.fromJson(j['project']),+ status: (j['status'] as String?) ?? 'active',+ launchState: launchState,+ launchError: launchState == 'failed' ? _safeLabel(launch['error']) : null,+ launchDetail: launchState == 'failed'+ ? _safeDetail(launch['detail'])+ : null,+ terminalAvailable: terminalAvailable,+ terminalUnavailableReason: terminalAvailable+ ? null+ : _safeLabel(terminalMap['reason']) ??+ 'terminal unavailable (no verified terminal pane)',+ );+ }++ Agent copyWith({String? name}) => Agent(+ id: id,+ sessionId: sessionId,+ name: name ?? this.name,+ engine: engine,+ engineDisplayName: engineDisplayName,+ engineIconHint: engineIconHint,+ codexHome: codexHome,+ parentAgentId: parentAgentId,+ project: project,+ status: status,+ launchState: launchState,+ launchError: launchError,+ launchDetail: launchDetail,+ terminalAvailable: terminalAvailable,+ terminalUnavailableReason: terminalUnavailableReason,+ );++ static String? _safeEngine(Object? raw) {+ if (raw is! String || raw.isEmpty || raw.length > 64) return null;+ return RegExp(r'^[a-zA-Z0-9._-]+$').hasMatch(raw) ? raw : null;+ }++ static String? _safeCodexHome(Object? raw) {+ if (raw is! String ||+ !raw.startsWith('/') ||+ raw.length > 4096 ||+ RegExp(r'[\x00-\x1f\x7f]').hasMatch(raw)) {+ return null;+ }+ return raw;+ }++ static String? _safeLabel(Object? raw) {+ if (raw is! String || raw.isEmpty) return null;+ return raw.length <= 80 ? raw : raw.substring(0, 80);+ }++ static String? _safeDetail(Object? raw) {+ if (raw is! String || raw.isEmpty) return null;+ final clean = raw.replaceAll(RegExp(r'[\u0000-\u001f\u007f]'), ' ').trim();+ if (clean.isEmpty) return null;+ return clean.length <= 500 ? clean : clean.substring(0, 500);+ }+}++/// What the daemon answered when asked where a typed task belongs (⌘B).+///+/// `candidates` is the pick followed by EVERY other agent the daemon weighed — ranked where the router+/// ranked them, in rail order after that. Not a shortlist: when the router is unsure the right agent is+/// often the one it put fourth, and a picker that cannot show it leaves no way forward but Esc.+/// The window reads it only when `confidence` is too low to act on — the whole point of the number+/// being on the wire.+class RouteAnswer {+ const RouteAnswer({+ required this.agentId,+ required this.machineId,+ required this.name,+ required this.confidence,+ required this.reason,+ required this.candidates,+ this.weighed = 0,+ this.machines = 0,+ this.via = '',+ });++ final String agentId;++ /// Which computer the pick lives on. Names are for reading; this is what opens the pane.+ final String machineId;+ final String name;+ final double confidence;+ final String reason;+ final List<RouteCandidate> candidates;++ /// How many agents were weighed, and across how many computers.+ ///+ /// Shown WHILE the router thinks, because the question during those seconds is not "how long" — it is+ /// "did it even look at the agent I mean". The daemon caps the list it weighs, so this is the only+ /// place that can answer it.+ final int weighed;+ final int machines;++ /// 'model' when a classifier answered, 'heuristic' when name matching stood in for it, '' when the+ /// daemon did not say.+ ///+ /// Both land under the threshold BY DESIGN — an unsure model and a router that could not run must both+ /// stop and ask — which is exactly why the window needs to tell them apart: "not sure which agent" and+ /// "the router could not run" send a person to different next moves.+ final String via;++ /// True when nobody was picked at all — an empty machine, or a daemon that could not answer.+ bool get isEmpty => agentId.isEmpty;++ /// Read with `is`, never with `as`.+ ///+ /// `json['x'] as String?` does not answer null for a number — it THROWS, and this frame crosses a+ /// socket, so the shape is whatever the other end sent. An exception here surfaces as a palette+ /// spinner that never comes down, which is the one failure the person cannot act on. A malformed field+ /// has to read as "nobody was picked" instead.+ static RouteAnswer fromJson(Map<String, dynamic> json) => RouteAnswer(+ agentId: _str(json['agentId']),+ machineId: _str(json['machineId']),+ name: _str(json['name']),+ confidence: json['confidence'] is num+ ? (json['confidence'] as num).toDouble()+ : 0,+ reason: _str(json['reason']),+ weighed: json['weighed'] is num ? (json['weighed'] as num).toInt() : 0,+ machines: json['machines'] is num ? (json['machines'] as num).toInt() : 0,+ via: _str(json['via']),+ candidates: [+ for (final entry+ in (json['candidates'] is List+ ? json['candidates'] as List<dynamic>+ : const []))+ if (entry is Map<String, dynamic>) RouteCandidate.fromJson(entry),+ ],+ );+}++class RouteCandidate {+ const RouteCandidate({+ required this.agentId,+ required this.machineId,+ required this.name,+ required this.machine,+ required this.recent,+ this.engine = '',+ this.confidence = 0,+ });++ final String agentId;++ /// Which computer to open the pane on. Names are for reading; this is for acting.+ final String machineId;+ final String name;++ /// Which computer it runs on. The candidate list spans every machine, so two agents named "api" on two+ /// of them are the same row twice without this.+ final String machine;++ /// What that agent was last doing — the line under its name when the window has to ask.+ final String recent;++ /// Which CLI it runs on. The picker wears the same engine mark the rail does, so a row here and the+ /// same agent in the rail are recognisably one thing rather than two lists that happen to share names.+ final String engine;++ /// How well the router thought this one fits, 0..1. DISPLAY ONLY.+ ///+ /// Nothing is dispatched on it — the pick is [RouteAnswer.agentId] and the number that gates it is+ /// [RouteAnswer.confidence]. 0 means the router said nothing about this candidate, and the picker+ /// draws no bar rather than an empty one, because an empty bar reads as "no fit" and this is "no+ /// answer".+ final double confidence;++ static RouteCandidate fromJson(Map<String, dynamic> json) => RouteCandidate(+ agentId: _str(json['agentId']),+ machineId: _str(json['machineId']),+ name: _str(json['name']),+ machine: _str(json['machine']),+ recent: _str(json['recent']),+ engine: _str(json['engine']),+ confidence: json['confidence'] is num+ ? (json['confidence'] as num).toDouble().clamp(0, 1)+ : 0,+ );+}++String _str(Object? value) => value is String ? value : '';++/// Context reported by the owning daemon. Missing on older daemons.+class AgentProject {+ const AgentProject({+ required this.name,+ required this.cwd,+ this.root,+ this.remote,+ this.branch,+ });+ final String name;+ final String cwd;+ final String? root;+ final String? remote;+ final String? branch;++ String identity(String machineId) =>+ remote != null ? 'repo:$remote' : 'folder:$machineId:${root ?? cwd}';++ @override+ bool operator ==(Object other) =>+ other is AgentProject &&+ name == other.name &&+ cwd == other.cwd &&+ root == other.root &&+ remote == other.remote &&+ branch == other.branch;+ @override+ int get hashCode => Object.hash(name, cwd, root, remote, branch);++ static AgentProject? fromJson(Object? raw) {+ if (raw is! Map) return null;+ String? field(String key, [int max = 4096]) {+ final v = raw[key];+ return v is String &&+ v.isNotEmpty &&+ v.length <= max &&+ !RegExp(r'[\x00-\x1f\x7f]').hasMatch(v)+ ? v+ : null;+ }++ final name = field('name', 256);+ final cwd = field('cwd');+ if (name == null || cwd == null) return null;+ return AgentProject(+ name: name,+ cwd: cwd,+ root: field('root'),+ remote: field('remote'),+ branch: field('branch', 256),+ );+ }+}diff --git a/mobile/lib/core/retry.dart b/mobile/lib/core/retry.dartnew file mode 100644index 000000000..17080d4e8--- /dev/null+++ b/mobile/lib/core/retry.dart@@ -0,0 +1,24 @@+import 'dart:async';++/// Retries [attempt] with a short doubling backoff, for a transient failure that a moment's wait+/// might clear — not for a real refusal. [isRetryable] decides which errors qualify; the default+/// retries none, so a call site always states its intent explicitly.+Future<T> withRetry<T>(+ Future<T> Function() attempt, {+ int maxAttempts = 3,+ Duration initialDelay = const Duration(milliseconds: 500),+ bool Function(Object error) isRetryable = _never,+}) async {+ var delay = initialDelay;+ for (var tries = 1; ; tries++) {+ try {+ return await attempt();+ } catch (error) {+ if (tries >= maxAttempts || !isRetryable(error)) rethrow;+ await Future.delayed(delay);+ delay *= 2;+ }+ }+}++bool _never(Object _) => false;diff --git a/mobile/lib/core/serial_port_lease.dart b/mobile/lib/core/serial_port_lease.dartnew file mode 100644index 000000000..7717d2371--- /dev/null+++ b/mobile/lib/core/serial_port_lease.dart@@ -0,0 +1,74 @@+import 'dart:async';+import 'dart:io';++import 'harness_file_store.dart';++/// Held while something outside the daemon needs the dial's USB serial port to itself.+///+/// Exists because two parts of this app want that port and neither knew about the other. Flashing+/// runs `harness stop` first — a serial port on macOS is exclusive, so the daemon has to let go — and+/// then writes for the better part of a minute. Meanwhile the app supervises that same daemon on a+/// five-second timer and starts it again the moment it notices it is gone. The daemon comes up,+/// reopens the dial, and esptool loses the port mid-write: the flash dies a few tens of kilobytes in+/// with "No more data to read from the serial port", which reads like broken hardware and is not.+///+/// A counter rather than a boolean so overlapping holders cannot release each other's claim, and+/// [hold] releases in a `finally` so a thrown or cancelled flash cannot leave supervision switched+/// off for the rest of the session — which would be a worse bug than the one this fixes, and a+/// silent one.+abstract final class SerialPortLease {+ static int _holders = 0;++ /// True while the daemon must not be started, because it would take the port.+ static bool get held => _holders > 0;++ /// How long a flag left behind by a flash that could not clean up is believed.+ ///+ /// A write takes a couple of minutes; ten is generous and still bounded. Without a bound, a script+ /// killed with -9 would switch daemon supervision off for the rest of the machine's life — a worse+ /// fault than the one this prevents, and a silent one.+ static const _staleAfter = Duration(minutes: 10);++ /// Whether a flash started OUTSIDE this app is holding the port.+ ///+ /// The in-process counter only knows about flashes this app started. Someone running+ /// `harness flash` in a terminal while the app is open hits exactly the same collision — the app+ /// restarts the daemon underneath them and their flash dies — and that is the case that matters+ /// most, because it is how a device already in someone's hands gets updated.+ ///+ /// The flasher writes this file before it stops the daemon and removes it when it starts it again.+ static bool heldByAnotherProcess({Map<String, String>? environment}) {+ try {+ // Honours the same override the flasher script reads, so the two sides cannot end up looking+ // in different places.+ final env = environment ?? Platform.environment;+ final dir =+ env['HARNESS_FLASHER_CACHE'] ??+ HarnessFileStore.defaultDirectoryPath(+ environment: environment,+ name: 'flasher',+ );+ final file = File('$dir/flashing');+ if (!file.existsSync()) return false;+ final started = int.tryParse(file.readAsStringSync().trim());+ if (started == null) return false;+ final age = DateTime.now().difference(+ DateTime.fromMillisecondsSinceEpoch(started * 1000),+ );+ return !age.isNegative && age < _staleAfter;+ } catch (_) {+ // Unreadable is not "being flashed": failing open here only risks the collision this guards+ // against, while failing closed would strand the daemon on any filesystem hiccup.+ return false;+ }+ }++ static Future<T> hold<T>(Future<T> Function() action) async {+ _holders++;+ try {+ return await action();+ } finally {+ _holders--;+ }+ }+}diff --git a/mobile/lib/core/snapshot_store.dart b/mobile/lib/core/snapshot_store.dartnew file mode 100644index 000000000..cfa7990ef--- /dev/null+++ b/mobile/lib/core/snapshot_store.dart@@ -0,0 +1,103 @@+/// Where a feature keeps one JSON blob between launches.+///+/// A seam for the same reason [LocalKeyValueStore] is one: a widget test mounts+/// the real screen and drives the real store, and neither may touch a real+/// `~/.harness`. ⚠️ **Under `testWidgets` this is not merely untidy — it hangs.**+/// The test body runs in a fake-async zone that never completes a real+/// `File.writeAsString`, so a store that awaited one inside a widget test would+/// block until the shell was killed rather than failing. That is the bug this+/// interface exists to make impossible, so keep `dart:io` on the far side of it.+///+/// Deliberately NOT `LocalKeyValueStore`, which is `state.json` — one small+/// document holding settings and credentials, rewritten under a file lock on+/// every key. What lands here is derived bulk (a usage snapshot runs to+/// megabytes), and putting that in `state.json` would make every theme flip+/// rewrite it.+library;++import 'dart:io';++import 'harness_file_store.dart';++abstract interface class SnapshotStore {+ /// The blob as it was written, or null when there is none.+ ///+ /// Never throws: an unreadable snapshot is a snapshot that is not there, and+ /// a screen that failed to open because last week's cache was truncated would+ /// be a worse bug than recomputing it.+ Future<String?> read();++ Future<void> write(String contents);++ /// Forget it entirely — what switching a feature off does.+ Future<void> clear();+}++/// The real one: `~/.harness/desktop-app/<name>.json`.+///+/// Written to a temporary file and renamed, so a crash mid-write leaves the+/// previous snapshot rather than half of a new one.+class FileSnapshotStore implements SnapshotStore {+ FileSnapshotStore(this.name, {Directory? directory})+ : directory =+ directory ?? Directory(HarnessFileStore.defaultDirectoryPath());++ /// The basename, without `.json`.+ final String name;+ final Directory directory;++ File get file => File('${directory.path}/$name.json');++ @override+ Future<String?> read() async {+ try {+ final snapshot = file;+ if (!await snapshot.exists()) return null;+ return await snapshot.readAsString();+ } on Object {+ return null;+ }+ }++ @override+ Future<void> write(String contents) async {+ try {+ await directory.create(recursive: true);+ final temporary = File('${file.path}.tmp');+ await temporary.writeAsString(contents, flush: true);+ await temporary.rename(file.path);+ } on Object {+ // A snapshot that could not be written costs the next launch a recompute+ // and nothing else, so it must not turn good work into a failure.+ }+ }++ @override+ Future<void> clear() async {+ try {+ if (await file.exists()) await file.delete();+ } on FileSystemException {+ // Whatever it held is off the screen either way, and the next write+ // replaces the file.+ }+ }+}++/// The same contract with no disk under it — for tests, and for a build that+/// deliberately keeps nothing.+class MemorySnapshotStore implements SnapshotStore {+ MemorySnapshotStore([this.contents]);++ String? contents;++ bool get isEmpty => contents == null;++ @override+ Future<String?> read() async => contents;++ @override+ Future<void> write(String value) async => contents = value;++ @override+ Future<void> clear() async => contents = null;+}diff --git a/mobile/lib/core/startup.dart b/mobile/lib/core/startup.dartnew file mode 100644index 000000000..45c4ddbe8--- /dev/null+++ b/mobile/lib/core/startup.dart@@ -0,0 +1,40 @@+import '../shared/theme/appearance_prefs_store.dart';+import '../stats/harness_stats.dart';+import '../terminal/terminal_font_store.dart';+import '../terminal/terminal_theme_store.dart';++/// Every preference that has to be in place BEFORE the first frame.+///+/// Extracted from `main()` so it can be tested. A store that is never loaded still passes every one+/// of its own tests — it round-trips through disk perfectly — and silently forgets the user's+/// choice at the next launch. Nothing else in the suite would notice, because the only thing wrong+/// is a missing call in the entrypoint. This is that call, in a place a test can reach.+///+/// They are awaited before `runApp` rather than loaded lazily: reading them after the first frame+/// would paint the defaults and then snap to the saved values, which reads as a flicker on every+/// launch.+///+/// The parameters exist for tests; the app passes nothing and gets the singletons the widgets read.+Future<void> loadPersistedSettings({+ TerminalFontStore? terminalFont,+ TerminalThemeStore? terminalTheme,+ AppearancePrefsStore? appearance,+ HarnessStats? stats,+}) async {+ // Independent stores may load together, but all must finish before runApp.+ // Font and appearance share a serialized file store; each reads its related+ // preferences as one snapshot. Stats uses a separate file and can overlap.+ await Future.wait([+ (terminalFont ?? terminalFontStore).load(),+ // Beside the font, and for the same reason: loading the scheme after the+ // first frame paints every pane on the default ground and then snaps it to+ // the saved one, which reads as a flash of the wrong colour at every launch.+ (terminalTheme ?? terminalThemeStore).load(),+ // Every control box uses these values. A late load would move the whole+ // window's geometry after its first frame, as well as changing its palette.+ (appearance ?? appearancePrefsStore).load(),+ // Counters begin moving with the first agent event. Loading them later+ // could overwrite a new event with the old count from disk.+ (stats ?? harnessStats).load(),+ ]);+}diff --git a/mobile/lib/core/test_run.dart b/mobile/lib/core/test_run.dartnew file mode 100644index 000000000..b2d627535--- /dev/null+++ b/mobile/lib/core/test_run.dart@@ -0,0 +1,19 @@+import 'dart:io';++/// True inside `flutter test`, which sets `FLUTTER_TEST` for every test process.+///+/// Widget tests here mount real screens and drive real controllers, so anything+/// that would reach outside the process on construction has to ask first. Two+/// separate reasons, and a thing that polls has both:+///+/// * **It must not act.** A test must not open a socket, shell out, or read a+/// real `~/.harness` — the run would depend on the machine it happens to be+/// on, and on whoever is signed in there.+/// * **It must not tick.** `pumpAndSettle` waits for the frame queue to go+/// quiet, and a `Timer.periodic` never lets it, so one background poll times+/// out every test that mounts the widget holding it.+///+/// One definition rather than a `FLUTTER_TEST` literal at each site: the two+/// call sites are asking the same question, and a second copy is a second thing+/// to get wrong.+final bool kUnderTest = Platform.environment.containsKey('FLUTTER_TEST');diff --git a/mobile/lib/core/viewer_mode.dart b/mobile/lib/core/viewer_mode.dartnew file mode 100644index 000000000..431d0c562--- /dev/null+++ b/mobile/lib/core/viewer_mode.dart@@ -0,0 +1,17 @@+import 'dart:io';++/// Whether this build is a VIEWER: a window onto the user's machines and nothing more.+///+/// No harness CLI runs beside it and no agent is ever hosted here, so every machine — this computer+/// included, if it is a Harness machine at all — is reached through the relay, with this app+/// terminating the end-to-end encryption the CLI terminates everywhere else (see `lib/viewer/`).+///+/// True on iOS, Android and Windows, where the CLI cannot run: tmux is not optional to it, and a+/// phone will not host a Node runtime or spawn a process at all. On macOS and Linux only with+/// `--dart-define=HARNESS_VIEWER_MODE=true`, which is how the path is developed and tested on a Mac+/// against real machines.+final bool kViewerMode =+ const bool.fromEnvironment('HARNESS_VIEWER_MODE') ||+ Platform.isIOS ||+ Platform.isAndroid ||+ Platform.isWindows;diff --git a/mobile/lib/e2ee/bytes.dart b/mobile/lib/e2ee/bytes.dartnew file mode 100644index 000000000..732c55a6e--- /dev/null+++ b/mobile/lib/e2ee/bytes.dart@@ -0,0 +1,63 @@+import 'dart:convert';+import 'dart:math';+import 'dart:typed_data';++/// Byte helpers for the E2EE port — the Dart side of core.ts's "portable helpers".++/// A source of random bytes. Production code takes the default ([secureRandomBytes]); tests pass+/// the seeded generator core.test.ts uses, so key material matches the CLI's vectors.+typedef Rng = Uint8List Function(int length);++final Random _secure = Random.secure();++Uint8List secureRandomBytes(int length) {+ final out = Uint8List(length);+ for (var i = 0; i < length; i++) {+ out[i] = _secure.nextInt(256);+ }+ return out;+}++String b64e(List<int> bytes) => base64Encode(bytes);++Uint8List b64d(String text) => base64Decode(text);++Uint8List utf8Bytes(String text) => Uint8List.fromList(utf8.encode(text));++Uint8List concatBytes(List<List<int>> parts) {+ final builder = BytesBuilder(copy: false);+ for (final part in parts) {+ builder.add(part);+ }+ return builder.takeBytes();+}++/// core.ts `lvCat`: every part prefixed with its 4-byte big-endian length, so no two different+/// transcripts can encode to the same bytes. A [String] part is its UTF-8.+Uint8List lvCat(List<Object> parts) {+ final builder = BytesBuilder(copy: false);+ for (final part in parts) {+ final bytes = switch (part) {+ String text => utf8Bytes(text),+ List<int> raw => raw,+ _ => throw ArgumentError.value(part, 'part', 'must be a String or bytes'),+ };+ builder+ ..add((ByteData(4)..setUint32(0, bytes.length)).buffer.asUint8List())+ ..add(bytes);+ }+ return builder.takeBytes();+}++/// Equality that does not stop at the first differing byte — for MAC tags.+bool ctEqual(List<int> a, List<int> b) {+ if (a.length != b.length) return false;+ var diff = 0;+ for (var i = 0; i < a.length; i++) {+ diff |= a[i] ^ b[i];+ }+ return diff == 0;+}++String hexOf(List<int> bytes) =>+ bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();diff --git a/mobile/lib/e2ee/cpace.dart b/mobile/lib/e2ee/cpace.dartnew file mode 100644index 000000000..31bc573b1--- /dev/null+++ b/mobile/lib/e2ee/cpace.dart@@ -0,0 +1,103 @@+import 'dart:typed_data';++import 'bytes.dart';+import 'keys.dart';+import 'primitives.dart';+import 'ristretto.dart';+import 'ristretto_field.dart';++/// The CPace-style PAKE over ristretto255 — core.ts's cpace*, kcKeys, pairKey and pairBind*.+///+/// Roles as core.ts names them: 'a' is the machine being joined, 'b' is the one joining (this app).++const _cpaceDsi = 'e2e-cpace-ristretto255-v1';++/// core.ts `randScalar`: uniform in [1, L) from 64 random bytes.+BigInt randScalar(Rng rng) {+ for (var i = 0; i < 8; i++) {+ final scalar = bytesToNumberLe(rng(64)) % curveOrder;+ if (scalar != BigInt.zero) return scalar;+ }+ throw StateError('randScalar: exhausted');+}++/// A CPace half: the secret [scalar] this side keeps, and the [share] it sends (core.ts's y and Y).+typedef CpaceStart = ({BigInt scalar, Uint8List share});++CpaceStart cpaceStart(RistrettoPoint generator, [Rng rng = secureRandomBytes]) {+ final scalar = randScalar(rng);+ return (scalar: scalar, share: generator.multiply(scalar).toBytes());+}++/// K = peerShare^scalar. Throws on an invalid or identity point — attack input, never a typo.+Uint8List cpaceShared(List<int> peerShare, BigInt scalar) {+ final shared = RistrettoPoint.fromBytes(peerShare).multiply(scalar);+ if (shared.equals(RistrettoPoint.zero)) {+ throw StateError('cpace: identity shared point');+ }+ return shared.toBytes();+}++Uint8List cpaceIsk(+ List<int> sid,+ List<int> shared,+ List<int> shareA,+ List<int> shareB,+) => sha512(+ lvCat([+ '${_cpaceDsi}_ISK',+ sid,+ shared,+ lvCat([shareA, 'a']),+ lvCat([shareB, 'b']),+ ]),+);++Uint8List transcriptHash(+ List<int> sid,+ String ci,+ List<int> shareA,+ List<int> shareB,+) => sha512(lvCat([sid, ci, lvCat([shareA, 'a']), lvCat([shareB, 'b'])]));++/// Key-confirmation MAC keys: [adapter] proves the joined machine's side, [web] the joiner's.+({Uint8List adapter, Uint8List web}) kcKeys(List<int> isk, String ci) {+ final kc = hkdfSha256(+ isk,+ salt: utf8Bytes(ci),+ info: utf8Bytes('e2e-kc-v1'),+ length: 64,+ );+ return (+ adapter: Uint8List.sublistView(kc, 0, 32),+ web: Uint8List.sublistView(kc, 32, 64),+ );+}++Uint8List macTag(List<int> key, List<int> transcript) =>+ hmacSha256(key, transcript);++bool macVerify(List<int> key, List<int> transcript, List<int> tag) =>+ ctEqual(macTag(key, transcript), tag);++/// Seals the identity exchange inside the PAKE.+Uint8List pairKey(List<int> isk, String ci) => hkdfSha256(+ isk,+ salt: utf8Bytes(ci),+ info: utf8Bytes('e2e-id-v1'),+ length: 32,+);++Future<Uint8List> pairBindSig(E2eeIdentity identity, List<int> transcript) =>+ identity.sign(concatBytes([utf8Bytes('e2e-pair-bind'), transcript]));++Future<bool> pairBindVerify(+ List<int> pub,+ List<int> transcript,+ List<int> sig,+) =>+ verifySignature(+ pub,+ concatBytes([utf8Bytes('e2e-pair-bind'), transcript]),+ sig,+ );diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dartnew file mode 100644index 000000000..7ea7196f7--- /dev/null+++ b/mobile/lib/e2ee/envelope.dart@@ -0,0 +1,115 @@+import 'dart:convert';+import 'dart:typed_data';++import 'bytes.dart';+import 'primitives.dart';++/// core.ts's frame-payload envelope: `{__e2e: {v, k, n, ct, epoch?}}` stands in for a frame's+/// payload while its `type` stays readable, so the relay can route what it cannot read.++const int e2eVersion = 1;++/// Frames this client must send as ciphertext — core.ts `ENCRYPTED_DOWN_TYPES`. test/e2ee/ holds it+/// to the CLI's own list, because a type missing here fails nowhere: the frame simply leaves in the+/// clear, and for terminal_* the relay then drops it as TERMINAL_FRAME_REJECTED.+const Set<String> encryptedDownTypes = {+ 'message',+ 'question_response',+ 'agents_list',+ 'sessions_list',+ 'session_get',+ 'models_list',+ 'agent_create',+ 'agent_delete',+ 'agent_restart',+ 'agent_recent',+ 'agent_update',+ 'agent_files',+ 'agent_read_file',+ 'fs_list_dir',+ 'codex_profiles_list',+ 'codex_profile_link',+ 'device_e2ee_pair',+ 'e2ee_pairings_list',+ 'e2ee_pairing_unpair',+ 'e2ee_pairings_unpair_all',+ 'e2ee_browser_link_create',+ 'terminal_capabilities',+ 'terminal_open',+ 'terminal_alive',+ 'terminal_ack',+ 'terminal_input',+ 'terminal_resize',+ 'terminal_resync',+ 'terminal_close',+ 'terminal_scroll',+ 'terminal_chunked_upload_begin',+ 'terminal_chunked_upload_cancel',+ 'p2p_offer',+ 'p2p_answer',+ 'p2p_ice_candidate',+ 'p2p_abort',+ 'p2p_promote',+};++Uint8List _aad(int v, String type, String dbSessionId, String k, String epoch) =>+ utf8Bytes('$v|$type|$dbSessionId|$k|$epoch');++/// Seals [payload] under [key]: [k] is 'p' (pairwise session) or 'g' (the machine's group key,+/// which also carries an [epoch]).+Map<String, Object?> wrapPayload(+ List<int> key,+ String k,+ int counter,+ String frameType,+ String? dbSessionId,+ Object? payload, {+ String? epoch,+}) {+ final aad = _aad(e2eVersion, frameType, dbSessionId ?? '', k, epoch ?? '');+ final sealed = aeadSeal(key, counter, aad, utf8Bytes(jsonEncode(payload)));+ return {+ '__e2e': {+ 'v': e2eVersion,+ 'k': k,+ 'n': counter,+ 'ct': b64e(sealed),+ 'epoch': ?epoch,+ },+ };+}++/// The payload object [wrapPayload] sealed; null when it does not open — a wrong key or counter, or+/// an AAD (type, session, epoch) other than the one it was sealed under.+Map<String, dynamic>? unwrapPayload(+ List<int> key,+ Map<String, dynamic> env,+ String frameType,+ String? dbSessionId,+) {+ final v = env['v'], k = env['k'], n = env['n'], ct = env['ct'];+ final epoch = env['epoch'] ?? '';+ if (v is! int || k is! String || n is! int || ct is! String || epoch is! String) {+ return null;+ }+ final Uint8List sealed;+ try {+ sealed = b64d(ct);+ } on FormatException {+ return null;+ }+ final clear = aeadOpen(key, n, _aad(v, frameType, dbSessionId ?? '', k, epoch), sealed);+ return clear == null ? null : jsonObjectOf(clear);+}++bool isWrapped(Object? payload) => payload is Map && payload.containsKey('__e2e');++/// UTF-8 JSON that must be an object; null for anything else.+Map<String, dynamic>? jsonObjectOf(List<int> utf8Json) {+ try {+ final value = jsonDecode(utf8.decode(utf8Json));+ return value is Map<String, dynamic> ? value : null;+ } on FormatException {+ return null;+ }+}diff --git a/mobile/lib/e2ee/keys.dart b/mobile/lib/e2ee/keys.dartnew file mode 100644index 000000000..63559c859--- /dev/null+++ b/mobile/lib/e2ee/keys.dart@@ -0,0 +1,144 @@+import 'dart:typed_data';++import 'package:cryptography/cryptography.dart';+import 'package:cryptography/dart.dart';++import 'bytes.dart';+import 'primitives.dart';++/// Long-lived identity (Ed25519) and per-connection ephemeral (X25519) keys — core.ts `Identity`,+/// `Ephemeral` and `sessionKeys`, plus the hello/welcome signatures that bind them.+///+/// Signing and verifying are async where core.ts's are not: the pure-Dart Ed25519 has no+/// synchronous API. Nothing that signs touches a nonce counter — only the handshake and the link+/// sign anything — so the await costs no ordering guarantee.++final _ed25519 = DartEd25519();+const _x25519 = DartX25519();++/// This app's Ed25519 identity. [seed] is the 32-byte RFC 8032 private key (core.ts's `priv`).+///+/// Every machine this app links to pins [pub], so it is minted once and persisted — a new one+/// means linking every machine again.+class E2eeIdentity {+ E2eeIdentity._(this.seed, this.pub);++ final Uint8List seed;+ final Uint8List pub;++ static Future<E2eeIdentity> fromSeed(List<int> seed) async {+ final keyPair = await _ed25519.newKeyPairFromSeed(seed);+ final pub = await keyPair.extractPublicKey();+ return E2eeIdentity._(Uint8List.fromList(seed), Uint8List.fromList(pub.bytes));+ }++ static Future<E2eeIdentity> generate([Rng rng = secureRandomBytes]) =>+ fromSeed(rng(32));++ Future<Uint8List> sign(List<int> message) async {+ final signature = await _ed25519.sign(+ message,+ keyPair: SimpleKeyPairData(+ seed,+ publicKey: SimplePublicKey(pub, type: KeyPairType.ed25519),+ type: KeyPairType.ed25519,+ ),+ );+ return Uint8List.fromList(signature.bytes);+ }+}++/// False for a bad signature AND for input too malformed to check, as core.ts's `verify`.+Future<bool> verifySignature(+ List<int> pub,+ List<int> message,+ List<int> signature,+) async {+ try {+ return await _ed25519.verify(+ message,+ signature: Signature(+ signature,+ publicKey: SimplePublicKey(pub, type: KeyPairType.ed25519),+ ),+ );+ } catch (_) {+ return false;+ }+}++/// core.ts `fingerprint`: sha256(pub)'s first 8 bytes as four dot-separated hex groups — what the+/// person compares against the other machine's `harness remote-password status`.+String fingerprint(List<int> pub) {+ final hex = hexOf(sha256(pub).sublist(0, 8)).toUpperCase();+ return '${hex.substring(0, 4)}·${hex.substring(4, 8)}·'+ '${hex.substring(8, 12)}·${hex.substring(12, 16)}';+}++/// A per-connection X25519 key.+class Ephemeral {+ Ephemeral._(this._keyPair, this.pub);++ final SimpleKeyPairData _keyPair;+ final Uint8List pub;++ static Future<Ephemeral> generate([Rng rng = secureRandomBytes]) async {+ final keyPair =+ await _x25519.newKeyPairFromSeed(rng(32)) as SimpleKeyPairData;+ return Ephemeral._(keyPair, Uint8List.fromList(keyPair.publicKey.bytes));+ }++ Uint8List sharedSecret(List<int> peerPub) {+ final secret =+ _x25519.sharedSecretSync(+ keyPairData: _keyPair,+ remotePublicKey: SimplePublicKey(+ peerPub,+ type: KeyPairType.x25519,+ ),+ )+ as SecretKeyData;+ return Uint8List.fromList(secret.bytes);+ }+}++typedef SessionKeys = ({Uint8List c2s, Uint8List s2c});++/// core.ts `sessionKeys`. Both ends pass the SAME (webEphPub, adapterEphPub) order, whichever end+/// they are.+SessionKeys sessionKeys(+ Ephemeral eph,+ List<int> peerEphPub,+ String machineId,+ List<int> webEphPub,+ List<int> adapterEphPub,+) {+ final session = hkdfSha256(+ eph.sharedSecret(peerEphPub),+ salt: lvCat([machineId, webEphPub, adapterEphPub]),+ info: utf8Bytes('e2e-sess-v1'),+ length: 64,+ );+ return (+ c2s: Uint8List.sublistView(session, 0, 32),+ s2c: Uint8List.sublistView(session, 32, 64),+ );+}++Future<Uint8List> helloSig(+ E2eeIdentity identity,+ String machineId,+ List<int> ephPub,+) => identity.sign(lvCat(['e2e-hello-v1', machineId, ephPub]));++Future<bool> welcomeVerify(+ List<int> peerPub,+ String machineId,+ List<int> webEphPub,+ List<int> adapterEphPub,+ List<int> sig,+) => verifySignature(+ peerPub,+ lvCat(['e2e-welcome-v1', machineId, webEphPub, adapterEphPub]),+ sig,+);diff --git a/mobile/lib/e2ee/password_pake.dart b/mobile/lib/e2ee/password_pake.dartnew file mode 100644index 000000000..ae62819dc--- /dev/null+++ b/mobile/lib/e2ee/password_pake.dart@@ -0,0 +1,48 @@+import 'dart:isolate';+import 'dart:typed_data';++import 'package:unorm_dart/unorm_dart.dart' as unorm;++import 'bytes.dart';+import 'primitives.dart';+import 'ristretto.dart';+import 'scrypt.dart';++/// passwordPake.ts — the generator and channel binding of the remote-password link: `harness+/// remote-password set` on the machine, the same password typed on this device.++const _pwDsi = 'e2e-cpace-ristretto255-pw-v1';++// passwordPake.ts's cost parameters. A security control: never lowered to make anything faster.+const _scryptN = 1 << 17;+const _scryptR = 8;+const _scryptP = 1;+const _scryptDkLen = 32;++/// passwordPake.ts `stretchPassword`: NFKC-fold the password, then scrypt it salted per machine,+/// so one password set on two machines yields two unrelated keys.+///+/// Runs on its own isolate — about a second of CPU and 128 MB, which on the UI isolate would+/// freeze the very frame telling the person to wait.+Future<Uint8List> stretchPassword(String password, String machineId) {+ final secret = utf8Bytes(unorm.nfkc(password));+ final salt = sha256(utf8Bytes('e2e-remote-password-salt-v1|$machineId'));+ return Isolate.run(+ () => scrypt(+ secret,+ salt,+ n: _scryptN,+ r: _scryptR,+ p: _scryptP,+ dkLen: _scryptDkLen,+ ),+ );+}++/// The channel binding. The joiner is always named `machine` — the CLI's own joiner is one, and to+/// the machine being joined this app must look exactly like it.+String pwContext(String machineId) =>+ 'autonomous-e2e-pw-pair|agent:$machineId|a:adapter|b:machine';++RistrettoPoint pwCpaceGenerator(List<int> stretched, List<int> sid, String ci) =>+ hashToRistretto255(lvCat([_pwDsi, stretched, sid, ci]), utf8Bytes(_pwDsi));diff --git a/mobile/lib/e2ee/primitives.dart b/mobile/lib/e2ee/primitives.dartnew file mode 100644index 000000000..3580418c1--- /dev/null+++ b/mobile/lib/e2ee/primitives.dart@@ -0,0 +1,105 @@+import 'dart:typed_data';++import 'package:cryptography/cryptography.dart';+import 'package:cryptography/dart.dart';++import 'bytes.dart';++/// Hashes, HMAC, HKDF and the ChaCha20-Poly1305 AEAD — what core.ts takes from noble, each one held+/// byte-for-byte against the CLI by test/e2ee/.+///+/// All synchronous on purpose, like core.ts: a nonce counter read before an `await` and spent after+/// one is exactly how two frames end up sealed under the same nonce.++const _sha256 = DartSha256();+const _sha512 = DartSha512();+const _hmacSha256 = DartHmac(DartSha256());+const _aead = DartChacha20.poly1305Aead();+const _aeadTagBytes = 16;++Uint8List sha256(List<int> data) =>+ Uint8List.fromList(_sha256.hashSync(data).bytes);++Uint8List sha512(List<int> data) =>+ Uint8List.fromList(_sha512.hashSync(data).bytes);++Uint8List hmacSha256(List<int> key, List<int> data) => Uint8List.fromList(+ _hmacSha256+ .calculateMacSync(+ data,+ secretKeyData: SecretKeyData(key),+ nonce: const <int>[],+ )+ .bytes,+);++/// RFC 5869 HKDF-SHA256 — noble's `hkdf(sha256, ikm, salt, info, length)`.+Uint8List hkdfSha256(+ List<int> ikm, {+ List<int> salt = const <int>[],+ List<int> info = const <int>[],+ required int length,+}) {+ // An empty salt means HashLen zero bytes (RFC 5869 §2.2). HMAC zero-pads its key to the block+ // size either way, so this is what noble computes for both an absent and an empty salt.+ final prk = hmacSha256(salt.isEmpty ? Uint8List(32) : salt, ikm);+ final okm = BytesBuilder(copy: false);+ var block = Uint8List(0);+ for (var counter = 1; okm.length < length; counter++) {+ block = hmacSha256(prk, [...block, ...info, counter]);+ okm.add(block);+ }+ return Uint8List.sublistView(okm.takeBytes(), 0, length);+}++/// core.ts `counterNonce`: the counter as 8 big-endian bytes, then 4 zero bytes.+Uint8List counterNonce(int counter) {+ final nonce = Uint8List(12);+ ByteData.sublistView(nonce).setUint64(0, counter);+ return nonce;+}++/// ChaCha20-Poly1305 under a counter nonce: ciphertext followed by its 16-byte tag, the layout+/// noble's `encrypt` produces.+Uint8List aeadSeal(+ List<int> key,+ int counter,+ List<int> aad,+ List<int> plaintext,+) {+ final box = _aead.encryptSync(+ plaintext,+ secretKey: SecretKeyData(key),+ nonce: counterNonce(counter),+ aad: aad,+ );+ return concatBytes([box.cipherText, box.mac.bytes]);+}++/// The inverse of [aeadSeal]; null when the tag does not verify — a wrong key, counter or AAD, or+/// a flipped byte.+Uint8List? aeadOpen(+ List<int> key,+ int counter,+ List<int> aad,+ List<int> sealed,+) {+ if (sealed.length < _aeadTagBytes) return null;+ final split = sealed.length - _aeadTagBytes;+ try {+ final clear = _aead.decryptSync(+ SecretBox(+ sealed.sublist(0, split),+ nonce: counterNonce(counter),+ mac: Mac(sealed.sublist(split)),+ ),+ secretKey: SecretKeyData(key),+ aad: aad,+ );+ return Uint8List.fromList(clear);+ } on SecretBoxAuthenticationError {+ return null;+ } on ArgumentError {+ return null;+ }+}diff --git a/mobile/lib/e2ee/relay_session_crypto.dart b/mobile/lib/e2ee/relay_session_crypto.dartnew file mode 100644index 000000000..8970c14d7--- /dev/null+++ b/mobile/lib/e2ee/relay_session_crypto.dart@@ -0,0 +1,195 @@+import 'dart:typed_data';++import '../terminal/terminal_binary.dart';+import 'bytes.dart';+import 'envelope.dart';+import 'keys.dart';+import 'primitives.dart';+import 'replay_window.dart';+import 'terminal_cipher.dart';++/// The client end of one E2EE session with a remote machine — relayClient.ts `RelaySessionCrypto`.+///+/// On macOS and Linux the harness CLI runs this role for the app and hands it plaintext. Where+/// there is no CLI (iOS, Windows) the app runs it itself, against the same machine code that+/// answers the CLI and the web client — to the machine, this app IS such a client.+///+/// One per connection: `e2e_hello` → `e2e_welcome` sets up the keys, and a reconnect is a new+/// ephemeral, new keys and fresh counters.+class RelaySessionCrypto {+ RelaySessionCrypto._(+ this.machineId,+ this._identity,+ this._peerPub,+ this._eph,+ this._helloSig,+ );++ /// Signs the hello up front, so [helloFrame] is ready the moment the relay acks the select.+ /// [ephemeral] is for tests; production mints a fresh one per connection.+ static Future<RelaySessionCrypto> start({+ required String machineId,+ required E2eeIdentity identity,+ required List<int> peerPub,+ Ephemeral? ephemeral,+ }) async {+ final eph = ephemeral ?? await Ephemeral.generate();+ return RelaySessionCrypto._(+ machineId,+ identity,+ Uint8List.fromList(peerPub),+ eph,+ await helloSig(identity, machineId, eph.pub),+ );+ }++ final String machineId;+ final E2eeIdentity _identity;+ final Uint8List _peerPub;+ final Ephemeral _eph;+ final Uint8List _helloSig;++ Uint8List? _c2s;+ Uint8List? _s2c;+ Uint8List? _terminalC2s;+ Uint8List? _terminalS2c;+ int _c2sCounter = 0;+ int _terminalC2sCounter = 0;+ final _s2cRecv = ReplayWindow();+ final _terminalS2cRecv = ReplayWindow();+ Uint8List? _groupKey;+ String _epoch = '';+ final Map<String, int> _groupRecv = {};+ int _terminalP2pVersion = 0;++ bool get ready => _c2s != null && _s2c != null;++ /// The machine's `features.terminalP2p` — 0 when it offers no P2P terminal channel.+ int get terminalP2pVersion => _terminalP2pVersion;++ Map<String, dynamic> helloFrame() => {+ 'type': 'e2e_hello',+ 'payload': {+ 'identityPub': b64e(_identity.pub),+ 'ephPub': b64e(_eph.pub),+ 'sig': b64e(_helloSig),+ },+ };++ /// Takes the machine's `e2e_welcome`; true once the session is usable. False means the machine+ /// did not prove it holds the identity this app pinned for it, or the welcome did not open.+ Future<bool> handleWelcome(Map<String, dynamic> payload) async {+ try {+ final adapterEphPub = _bytesField(payload, 'ephPub');+ final sig = _bytesField(payload, 'sig');+ final enc = _bytesField(payload, 'enc');+ if (adapterEphPub == null || sig == null || enc == null) return false;+ if (!await welcomeVerify(_peerPub, machineId, _eph.pub, adapterEphPub, sig)) {+ return false;+ }+ final keys = sessionKeys(_eph, adapterEphPub, machineId, _eph.pub, adapterEphPub);+ final opened = aeadOpen(keys.s2c, 0, utf8Bytes('e2e-welcome'), enc);+ final initial = opened == null ? null : jsonObjectOf(opened);+ final groupKey = initial?['groupKey'], epoch = initial?['epoch'];+ if (groupKey is! String || groupKey.isEmpty || epoch is! String || epoch.isEmpty) {+ return false;+ }+ _groupKey = b64d(groupKey);+ _epoch = epoch;+ _c2s = keys.c2s;+ _s2c = keys.s2c;+ _terminalC2s = deriveTerminalBinaryKey(keys.c2s);+ _terminalS2c = deriveTerminalBinaryKey(keys.s2c);+ final features = initial!['features'];+ final p2p = features is Map ? features['terminalP2p'] : null;+ _terminalP2pVersion = p2p is int ? p2p : 0;+ return true;+ } on FormatException {+ return false;+ } on ArgumentError {+ return false;+ }+ }++ /// Takes an `e2e_rekey` — the machine rotated its group key, which it does when it revokes a+ /// client. False when it does not open.+ bool handleRekey(Map<String, dynamic> payload) {+ final s2c = _s2c;+ final n = payload['n'], enc = payload['enc'];+ if (s2c == null || n is! int || enc is! String || enc.isEmpty) return false;+ try {+ final opened = aeadOpen(s2c, n, utf8Bytes('e2e-rekey'), b64d(enc));+ final next = opened == null ? null : jsonObjectOf(opened);+ final groupKey = next?['groupKey'], epoch = next?['epoch'];+ if (groupKey is! String || groupKey.isEmpty || epoch is! String || epoch.isEmpty) {+ return false;+ }+ _groupKey = b64d(groupKey);+ _epoch = epoch;+ return true;+ } on FormatException {+ return false;+ }+ }++ /// Seals the payload of a frame whose type must not cross the relay in the clear; any other+ /// frame goes as it is.+ Map<String, dynamic> wrapOutgoing(Map<String, dynamic> frame) {+ final type = frame['type'], c2s = _c2s;+ if (type is! String || c2s == null || !encryptedDownTypes.contains(type)) {+ return frame;+ }+ final payload = wrapPayload(c2s, 'p', _c2sCounter++, type, null, frame['payload']);+ return {...frame, 'payload': payload};+ }++ /// The frame with its payload opened; a frame that was never sealed passes as it is. Null means+ /// drop it — stale, replayed or not authentic — and never hand it on.+ Map<String, dynamic>? unwrapIncoming(Map<String, dynamic> frame) {+ final payload = frame['payload'];+ if (payload is! Map || !isWrapped(payload)) return frame;+ final env = payload['__e2e'], type = frame['type'];+ if (env is! Map<String, dynamic> || type is! String) return null;+ final n = env['n'];+ if (n is! int) return null;+ final dbSessionId = frame['dbSessionId'] as String?;+ if (env['k'] == 'g') {+ final groupKey = _groupKey, epoch = env['epoch'];+ if (groupKey == null || epoch != _epoch) return null;+ if (n <= (_groupRecv[_epoch] ?? -1)) return null;+ final clear = unwrapPayload(groupKey, env, type, dbSessionId);+ if (clear == null) return null;+ _groupRecv[_epoch] = n;+ return {...frame, 'payload': clear};+ }+ final s2c = _s2c;+ if (s2c == null || !_s2cRecv.allows(n)) return null;+ final clear = unwrapPayload(s2c, env, type, dbSessionId);+ if (clear == null) return null;+ _s2cRecv.commit(n);+ return {...frame, 'payload': clear};+ }++ Uint8List? encryptTerminal(TerminalBinaryFrame frame) {+ final key = _terminalC2s;+ if (key == null) return null;+ final sealed = sealTerminalBinary(key, _terminalC2sCounter, frame);+ if (sealed != null) _terminalC2sCounter++;+ return sealed;+ }++ /// Null means drop — stale, replayed or not authentic.+ TerminalBinaryFrame? decryptTerminal(Uint8List raw) {+ final key = _terminalS2c;+ if (key == null) return null;+ final opened = openTerminalBinary(key, raw);+ if (opened == null || !_terminalS2cRecv.allows(opened.counter)) return null;+ _terminalS2cRecv.commit(opened.counter);+ return opened.frame;+ }+}++Uint8List? _bytesField(Map<String, dynamic> payload, String key) {+ final value = payload[key];+ return value is String && value.isNotEmpty ? b64d(value) : null;+}diff --git a/mobile/lib/e2ee/replay_window.dart b/mobile/lib/e2ee/replay_window.dartnew file mode 100644index 000000000..3f22ff5a7--- /dev/null+++ b/mobile/lib/e2ee/replay_window.dart@@ -0,0 +1,40 @@+/// replayWindow.ts: the counters of one key domain are accepted each once, in any order, within+/// [e2eeReplayWindowSize] of the highest seen. The machine can deliver a stream's frames over two+/// transports (P2P and the relay) that reorder against each other, so "strictly increasing" would+/// drop authentic frames.+const int e2eeReplayWindowSize = 4096;++/// JavaScript's `Number.MAX_SAFE_INTEGER` — the CLI refuses any counter above it, so this does too.+const int maxSafeInteger = 9007199254740991;++class ReplayWindow {+ int _highest = -1;+ int _prunedThrough = -1;+ final Set<int> _seen = {};++ bool allows(int counter) =>+ counter >= 0 &&+ counter <= maxSafeInteger &&+ !_seen.contains(counter) &&+ (_highest < 0 || counter > _highest - e2eeReplayWindowSize);++ void commit(int counter) {+ _seen.add(counter);+ if (counter <= _highest) return;+ _highest = counter;+ final oldest = _highest - e2eeReplayWindowSize;+ if (oldest <= _prunedThrough) return;+ // A counter far ahead makes the whole old set stale — clear it rather than walk a gap a+ // hostile peer chose the size of.+ if (oldest - _prunedThrough > e2eeReplayWindowSize) {+ _seen+ ..clear()+ ..add(counter);+ } else {+ for (var value = _prunedThrough + 1; value <= oldest; value++) {+ _seen.remove(value);+ }+ }+ _prunedThrough = oldest;+ }+}diff --git a/mobile/lib/e2ee/ristretto.dart b/mobile/lib/e2ee/ristretto.dartnew file mode 100644index 000000000..72d732f2c--- /dev/null+++ b/mobile/lib/e2ee/ristretto.dart@@ -0,0 +1,178 @@+import 'dart:typed_data';++import 'bytes.dart';+import 'primitives.dart';+import 'ristretto_field.dart';++/// ristretto255 points and hash-to-group — core.ts's `RistrettoPoint` and `hashToRistretto255`,+/// which both CPace generators (the 6-character code and the remote password) are built from.++/// An edwards25519 point in extended coordinates (a = −1).+class EdwardsPoint {+ const EdwardsPoint(this.x, this.y, this.z, this.t);++ final BigInt x, y, z, t;++ static final EdwardsPoint zero = EdwardsPoint(+ BigInt.zero,+ BigInt.one,+ BigInt.one,+ BigInt.zero,+ );++ static final BigInt _k = fmod(edwardsD * BigInt.two);++ /// add-2008-hwcd-3.+ EdwardsPoint add(EdwardsPoint o) {+ final a = fmod((y - x) * (o.y - o.x));+ final b = fmod((y + x) * (o.y + o.x));+ final c = fmod(t * _k * o.t);+ final d = fmod(z * BigInt.two * o.z);+ final e = fmod(b - a), f = fmod(d - c), g = fmod(d + c), h = fmod(b + a);+ return EdwardsPoint(fmod(e * f), fmod(g * h), fmod(f * g), fmod(e * h));+ }++ /// dbl-2008-hwcd.+ EdwardsPoint double() {+ final a = fmod(x * x);+ final b = fmod(y * y);+ final c = fmod(BigInt.two * z * z);+ final d = fmod(-a);+ final e = fmod((x + y) * (x + y) - a - b);+ final g = fmod(d + b), f = fmod(g - c), h = fmod(d - b);+ return EdwardsPoint(fmod(e * f), fmod(g * h), fmod(f * g), fmod(e * h));+ }++ EdwardsPoint multiply(BigInt scalar) {+ var result = zero;+ var addend = this;+ for (var k = scalar; k > BigInt.zero; k = k >> 1) {+ if (k.isOdd) result = result.add(addend);+ addend = addend.double();+ }+ return result;+ }+}++class RistrettoPoint {+ const RistrettoPoint(this.ep);++ final EdwardsPoint ep;++ static final RistrettoPoint zero = RistrettoPoint(EdwardsPoint.zero);++ /// Decodes a canonical 32-byte encoding; throws [ArgumentError] on anything else, as noble's+ /// `fromHex` does — the peer's CPace share is untrusted input.+ factory RistrettoPoint.fromBytes(List<int> bytes) {+ if (bytes.length != 32) throw ArgumentError('ristretto255: not 32 bytes');+ final s = bytes255ToNumberLe(bytes);+ if (!ctEqual(numberToBytesLe(s, 32), bytes) || isNegativeLe(s)) {+ throw ArgumentError('ristretto255: non-canonical encoding');+ }+ final s2 = fmod(s * s);+ final u1 = fmod(BigInt.one + edwardsA * s2);+ final u2 = fmod(BigInt.one - edwardsA * s2);+ final u2Sq = fmod(u2 * u2);+ final v = fmod(edwardsA * edwardsD * u1 * u1 - u2Sq);+ final inv = uvRatio(BigInt.one, fmod(v * u2Sq));+ final dx = fmod(inv.value * u2);+ final dy = fmod(inv.value * dx * v);+ var x = fmod((s + s) * dx);+ if (isNegativeLe(x)) x = fmod(-x);+ final y = fmod(u1 * dy);+ final t = fmod(x * y);+ if (!inv.isValid || isNegativeLe(t) || y == BigInt.zero) {+ throw ArgumentError('ristretto255: invalid encoding');+ }+ return RistrettoPoint(EdwardsPoint(x, y, BigInt.one, t));+ }++ Uint8List toBytes() {+ var x = ep.x, y = ep.y;+ final z = ep.z, t = ep.t;+ final u1 = fmod(fmod(z + y) * fmod(z - y));+ final u2 = fmod(x * y);+ final invSqrt = uvRatio(BigInt.one, fmod(u1 * u2 * u2)).value;+ final d1 = fmod(invSqrt * u1);+ final d2 = fmod(invSqrt * u2);+ final zInv = fmod(d1 * d2 * t);+ BigInt d;+ if (isNegativeLe(t * zInv)) {+ final rotatedX = fmod(y * sqrtM1);+ y = fmod(x * sqrtM1);+ x = rotatedX;+ d = fmod(d1 * invSqrtAMinusD);+ } else {+ d = d2;+ }+ if (isNegativeLe(x * zInv)) y = fmod(-y);+ var s = fmod((z - y) * d);+ if (isNegativeLe(s)) s = fmod(-s);+ return numberToBytesLe(s, 32);+ }++ RistrettoPoint multiply(BigInt scalar) => RistrettoPoint(ep.multiply(scalar));++ RistrettoPoint add(RistrettoPoint other) => RistrettoPoint(ep.add(other.ep));++ bool equals(RistrettoPoint other) {+ final a = ep, b = other.ep;+ return fmod(a.x * b.y) == fmod(a.y * b.x) ||+ fmod(a.y * b.y) == fmod(a.x * b.x);+ }+}++/// RFC 9496 Elligator map (noble `calcElligatorRistrettoMap`).+EdwardsPoint _elligator(BigInt r0) {+ final r = fmod(sqrtM1 * r0 * r0);+ final ns = fmod((r + BigInt.one) * oneMinusDSq);+ var c = fmod(-BigInt.one);+ final den = fmod((c - edwardsD * r) * fmod(r + edwardsD));+ final ratio = uvRatio(ns, den);+ var s = ratio.value;+ var sPrime = fmod(s * r0);+ if (!isNegativeLe(sPrime)) sPrime = fmod(-sPrime);+ if (!ratio.isValid) {+ s = sPrime;+ c = r;+ }+ final nt = fmod(c * (r - BigInt.one) * dMinusOneSq - den);+ final s2 = fmod(s * s);+ final w0 = fmod((s + s) * den);+ final w1 = fmod(nt * sqrtAdMinusOne);+ final w2 = fmod(BigInt.one - s2);+ final w3 = fmod(BigInt.one + s2);+ return EdwardsPoint(fmod(w0 * w3), fmod(w2 * w1), fmod(w1 * w3), fmod(w0 * w2));+}++/// noble `hashToRistretto255`: expand_message_xmd(SHA-512) to 64 bytes, then the one-way map.+RistrettoPoint hashToRistretto255(List<int> message, List<int> dst) {+ final uniform = expandMessageXmd(message, dst, 64);+ final r1 = _elligator(bytes255ToNumberLe(uniform.sublist(0, 32)));+ final r2 = _elligator(bytes255ToNumberLe(uniform.sublist(32, 64)));+ return RistrettoPoint(r1.add(r2));+}++/// RFC 9380 §5.3.1 expand_message_xmd with SHA-512 (b_in_bytes 64, s_in_bytes 128).+Uint8List expandMessageXmd(List<int> message, List<int> dst, int length) {+ if (dst.length > 255) throw ArgumentError('expand_message_xmd: DST too long');+ final ell = (length + 63) ~/ 64;+ final dstPrime = [...dst, dst.length];+ final b0 = sha512([+ ...Uint8List(128),+ ...message,+ (length >> 8) & 0xff,+ length & 0xff,+ 0,+ ...dstPrime,+ ]);+ final out = BytesBuilder(copy: false);+ var previous = sha512([...b0, 1, ...dstPrime]);+ out.add(previous);+ for (var i = 2; i <= ell; i++) {+ final mixed = [for (var j = 0; j < 64; j++) b0[j] ^ previous[j]];+ previous = sha512([...mixed, i, ...dstPrime]);+ out.add(previous);+ }+ return Uint8List.sublistView(out.takeBytes(), 0, length);+}diff --git a/mobile/lib/e2ee/ristretto_field.dart b/mobile/lib/e2ee/ristretto_field.dartnew file mode 100644index 000000000..c56925424--- /dev/null+++ b/mobile/lib/e2ee/ristretto_field.dart@@ -0,0 +1,91 @@+import 'dart:typed_data';++/// Arithmetic over GF(2^255 − 19) for ristretto255 (RFC 9496), ported from the noble-curves code+/// core.ts runs. Pure BigInt and NOT constant-time: it only ever touches the one-shot CPace+/// exchange of a link attempt, never a session key or a frame.++final BigInt fieldP = BigInt.parse(+ '7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed',+ radix: 16,+);++/// The prime order L of the ristretto255 group.+final BigInt curveOrder = BigInt.parse(+ '1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed',+ radix: 16,+);++final BigInt edwardsD = BigInt.parse(+ '52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3',+ radix: 16,+);++/// a = −1, reduced.+final BigInt edwardsA = fieldP - BigInt.one;++final BigInt sqrtM1 = BigInt.parse(+ '19681161376707505956807079304988542015446066515923890162744021073123829784752',+);+final BigInt sqrtAdMinusOne = BigInt.parse(+ '25063068953384623474111414158702152701244531502492656460079210482610430750235',+);+final BigInt invSqrtAMinusD = BigInt.parse(+ '54469307008909316920995813868745141605393597292927456921205312896311721017578',+);+final BigInt oneMinusDSq = BigInt.parse(+ '1159843021668779879193775521855586647937357759715417654439879720876111806838',+);+final BigInt dMinusOneSq = BigInt.parse(+ '40440834346308536858101042469323190826248399146238708352240133220865137265952',+);++final BigInt _mask255 = (BigInt.one << 255) - BigInt.one;+final BigInt _pMinus5Over8 = (fieldP - BigInt.from(5)) >> 3;++/// Dart's BigInt `%` is Euclidean, so this is always in [0, p).+BigInt fmod(BigInt n) => n % fieldP;++BigInt bytesToNumberLe(List<int> bytes) {+ var n = BigInt.zero;+ for (var i = bytes.length - 1; i >= 0; i--) {+ n = (n << 8) | BigInt.from(bytes[i]);+ }+ return n;+}++Uint8List numberToBytesLe(BigInt n, int length) {+ final out = Uint8List(length);+ var rest = n;+ for (var i = 0; i < length; i++) {+ out[i] = (rest & BigInt.from(0xff)).toInt();+ rest = rest >> 8;+ }+ return out;+}++/// noble `bytes255ToNumberLE`: the low 255 bits, reduced.+BigInt bytes255ToNumberLe(List<int> bytes) =>+ fmod(bytesToNumberLe(bytes) & _mask255);++bool isNegativeLe(BigInt n) => fmod(n).isOdd;++typedef SqrtRatio = ({bool isValid, BigInt value});++/// noble `uvRatio`: sqrt(u/v) when it exists. On failure the value is still a root of something,+/// because the Elligator map below uses it either way.+SqrtRatio uvRatio(BigInt u, BigInt v) {+ final v3 = fmod(v * v * v);+ final v7 = fmod(v3 * v3 * v);+ final pow = fmod(u * v7).modPow(_pMinus5Over8, fieldP);+ var x = fmod(u * v3 * pow);+ final vx2 = fmod(v * x * x);+ final root1 = x;+ final root2 = fmod(x * sqrtM1);+ final useRoot1 = vx2 == fmod(u);+ final useRoot2 = vx2 == fmod(-u);+ final noRoot = vx2 == fmod(-u * sqrtM1);+ if (useRoot1) x = root1;+ if (useRoot2 || noRoot) x = root2;+ if (isNegativeLe(x)) x = fmod(-x);+ return (isValid: useRoot1 || useRoot2, value: x);+}diff --git a/mobile/lib/e2ee/scrypt.dart b/mobile/lib/e2ee/scrypt.dartnew file mode 100644index 000000000..a2f003255--- /dev/null+++ b/mobile/lib/e2ee/scrypt.dart@@ -0,0 +1,167 @@+import 'dart:typed_data';++import 'bytes.dart';+import 'primitives.dart';++/// RFC 7914 scrypt — the stretch `harness remote-password` puts on a password (N=2^17, r=8, p=1).+///+/// Written over 32-bit words rather than taken from pointycastle, whose Salsa core works byte by+/// byte: this runs 2^17 × 2 block mixes over 128 MB once per link attempt, on a phone, and that is+/// the whole of the wait the person sees.+Uint8List scrypt(+ List<int> password,+ List<int> salt, {+ required int n,+ required int r,+ required int p,+ required int dkLen,+}) {+ if (n < 2 || (n & (n - 1)) != 0) throw ArgumentError('scrypt: N must be a power of 2');+ if (r < 1 || p < 1) throw ArgumentError('scrypt: r and p must be positive');+ final blockWords = 32 * r;+ final b = _bytesToWords(_pbkdf2Once(password, salt, 128 * r * p));+ final v = Uint32List(blockWords * n);+ final x = Uint32List(blockWords);+ final y = Uint32List(blockWords);+ final mix = Uint32List(16);+ for (var i = 0; i < p; i++) {+ _roMix(b, i * blockWords, r, n, v, x, y, mix);+ }+ return _pbkdf2Once(password, _wordsToBytes(b), dkLen);+}++/// PBKDF2-HMAC-SHA256 with one iteration — all scrypt ever asks of it.+Uint8List _pbkdf2Once(List<int> password, List<int> salt, int length) {+ final out = BytesBuilder(copy: false);+ for (var block = 1; out.length < length; block++) {+ out.add(hmacSha256(password, [+ ...salt,+ (block >> 24) & 0xff,+ (block >> 16) & 0xff,+ (block >> 8) & 0xff,+ block & 0xff,+ ]));+ }+ return Uint8List.sublistView(out.takeBytes(), 0, length);+}++void _roMix(+ Uint32List b,+ int offset,+ int r,+ int n,+ Uint32List v,+ Uint32List x,+ Uint32List y,+ Uint32List mix,+) {+ final words = 32 * r;+ x.setRange(0, words, b, offset);+ for (var i = 0; i < n; i++) {+ v.setRange(i * words, (i + 1) * words, x);+ _blockMix(x, y, mix, r);+ }+ final mask = n - 1;+ final last = (2 * r - 1) * 16;+ for (var i = 0; i < n; i++) {+ final base = (x[last] & mask) * words;+ for (var k = 0; k < words; k++) {+ x[k] ^= v[base + k];+ }+ _blockMix(x, y, mix, r);+ }+ b.setRange(offset, offset + words, x);+}++/// BlockMix_{Salsa20/8, r}: [b] in, [b] out (shuffled even blocks first), [y] as scratch.+void _blockMix(Uint32List b, Uint32List y, Uint32List mix, int r) {+ mix.setRange(0, 16, b, (2 * r - 1) * 16);+ for (var i = 0; i < 2 * r; i++) {+ for (var k = 0; k < 16; k++) {+ mix[k] ^= b[i * 16 + k];+ }+ _salsa20x8(mix);+ final target = ((i & 1) == 0 ? i >> 1 : r + (i >> 1)) * 16;+ y.setRange(target, target + 16, mix);+ }+ b.setRange(0, 32 * r, y);+}++int _rotl(int value, int shift) {+ final v = value & 0xffffffff;+ return ((v << shift) | (v >> (32 - shift))) & 0xffffffff;+}++/// The Salsa20/8 core of RFC 7914 §3, in place.+void _salsa20x8(Uint32List b) {+ var x0 = b[0], x1 = b[1], x2 = b[2], x3 = b[3];+ var x4 = b[4], x5 = b[5], x6 = b[6], x7 = b[7];+ var x8 = b[8], x9 = b[9], x10 = b[10], x11 = b[11];+ var x12 = b[12], x13 = b[13], x14 = b[14], x15 = b[15];+ for (var i = 0; i < 8; i += 2) {+ x4 ^= _rotl(x0 + x12, 7);+ x8 ^= _rotl(x4 + x0, 9);+ x12 ^= _rotl(x8 + x4, 13);+ x0 ^= _rotl(x12 + x8, 18);+ x9 ^= _rotl(x5 + x1, 7);+ x13 ^= _rotl(x9 + x5, 9);+ x1 ^= _rotl(x13 + x9, 13);+ x5 ^= _rotl(x1 + x13, 18);+ x14 ^= _rotl(x10 + x6, 7);+ x2 ^= _rotl(x14 + x10, 9);+ x6 ^= _rotl(x2 + x14, 13);+ x10 ^= _rotl(x6 + x2, 18);+ x3 ^= _rotl(x15 + x11, 7);+ x7 ^= _rotl(x3 + x15, 9);+ x11 ^= _rotl(x7 + x3, 13);+ x15 ^= _rotl(x11 + x7, 18);+ x1 ^= _rotl(x0 + x3, 7);+ x2 ^= _rotl(x1 + x0, 9);+ x3 ^= _rotl(x2 + x1, 13);+ x0 ^= _rotl(x3 + x2, 18);+ x6 ^= _rotl(x5 + x4, 7);+ x7 ^= _rotl(x6 + x5, 9);+ x4 ^= _rotl(x7 + x6, 13);+ x5 ^= _rotl(x4 + x7, 18);+ x11 ^= _rotl(x10 + x9, 7);+ x8 ^= _rotl(x11 + x10, 9);+ x9 ^= _rotl(x8 + x11, 13);+ x10 ^= _rotl(x9 + x8, 18);+ x12 ^= _rotl(x15 + x14, 7);+ x13 ^= _rotl(x12 + x15, 9);+ x14 ^= _rotl(x13 + x12, 13);+ x15 ^= _rotl(x14 + x13, 18);+ }+ // A Uint32List store keeps the low 32 bits, which is the mod-2^32 add the spec wants.+ b[0] += x0;+ b[1] += x1;+ b[2] += x2;+ b[3] += x3;+ b[4] += x4;+ b[5] += x5;+ b[6] += x6;+ b[7] += x7;+ b[8] += x8;+ b[9] += x9;+ b[10] += x10;+ b[11] += x11;+ b[12] += x12;+ b[13] += x13;+ b[14] += x14;+ b[15] += x15;+}++Uint32List _bytesToWords(Uint8List bytes) {+ final view = ByteData.sublistView(bytes);+ return Uint32List.fromList([+ for (var i = 0; i < bytes.length; i += 4) view.getUint32(i, Endian.little),+ ]);+}++Uint8List _wordsToBytes(Uint32List words) {+ final out = ByteData(words.length * 4);+ for (var i = 0; i < words.length; i++) {+ out.setUint32(i * 4, words[i], Endian.little);+ }+ return concatBytes([out.buffer.asUint8List()]);+}diff --git a/mobile/lib/e2ee/terminal_cipher.dart b/mobile/lib/e2ee/terminal_cipher.dartnew file mode 100644index 000000000..48302dfab--- /dev/null+++ b/mobile/lib/e2ee/terminal_cipher.dart@@ -0,0 +1,87 @@+import 'dart:typed_data';++import '../terminal/terminal_binary.dart';+import 'bytes.dart';+import 'primitives.dart';+import 'replay_window.dart';++/// HTRM v3 — terminalBinary.ts's encrypted binary terminal frame, the only form terminal bytes take+/// on the relay. The plaintext inside is the same one the loopback HTRL frame carries+/// ([encodeTerminalPlain]), which is what lets the transport convert between the two and leave+/// every terminal session unaware of which it is on.+///+/// Header (20 bytes): `HTRM` | version | kind | flags | 0 | u64 counter | u32 ciphertext length.+/// The first 16 bytes are the AAD; the counter is the nonce.++const int terminalBinaryVersion = 3;+const int terminalBinaryHeaderBytes = 20;+const int _aadBytes = 16;+const int _tagBytes = 16;+const int _flagZlib = 1;+final Uint8List _magic = Uint8List.fromList(const [0x48, 0x54, 0x52, 0x4d]);++/// Binary frames get their own key, so their nonces never collide with the JSON frames'.+Uint8List deriveTerminalBinaryKey(List<int> sessionKey) => hkdfSha256(+ sessionKey,+ info: utf8Bytes('harness-terminal-binary-v3'),+ length: 32,+);++Uint8List? sealTerminalBinary(+ List<int> key,+ int counter,+ TerminalBinaryFrame frame,+) {+ if (counter < 0 || counter > maxSafeInteger) return null;+ final plaintext = encodeTerminalPlain(frame);+ if (plaintext == null) return null;+ final header = Uint8List(terminalBinaryHeaderBytes)..setRange(0, 4, _magic);+ header[4] = terminalBinaryVersion;+ header[5] = frame.kind.code;+ header[6] = frame.compressed ? _flagZlib : 0;+ final view = ByteData.sublistView(header)..setUint64(8, counter);+ final ciphertext = aeadSeal(+ key,+ counter,+ Uint8List.sublistView(header, 0, _aadBytes),+ plaintext,+ );+ if (ciphertext.length > maxTerminalPayloadBytesFor(frame.kind)) return null;+ view.setUint32(16, ciphertext.length);+ return concatBytes([header, ciphertext]);+}++/// The frame inside [raw] and the counter it was sealed under; null for anything malformed or+/// unauthentic. Replay is the caller's to check — the counter is returned for that.+({int counter, TerminalBinaryFrame frame})? openTerminalBinary(+ List<int> key,+ Uint8List raw,+) {+ if (raw.length < terminalBinaryHeaderBytes + _tagBytes) return null;+ for (var i = 0; i < _magic.length; i++) {+ if (raw[i] != _magic[i]) return null;+ }+ final kind = TerminalBinaryKind.fromCode(raw[5]);+ if (raw[4] != terminalBinaryVersion || kind == null || raw[7] != 0) {+ return null;+ }+ final view = ByteData.sublistView(raw);+ final counter = view.getUint64(8);+ final length = view.getUint32(16);+ if (counter < 0 ||+ counter > maxSafeInteger ||+ length < _tagBytes ||+ length > maxTerminalPayloadBytesFor(kind) ||+ raw.length != terminalBinaryHeaderBytes + length) {+ return null;+ }+ final plaintext = aeadOpen(+ key,+ counter,+ Uint8List.sublistView(raw, 0, _aadBytes),+ Uint8List.sublistView(raw, terminalBinaryHeaderBytes),+ );+ if (plaintext == null) return null;+ final frame = decodeTerminalPlain(kind, raw[6], plaintext);+ return frame == null ? null : (counter: counter, frame: frame);+}diff --git a/mobile/lib/flash/flasher.dart b/mobile/lib/flash/flasher.dartnew file mode 100644index 000000000..19be36d5b--- /dev/null+++ b/mobile/lib/flash/flasher.dart@@ -0,0 +1,195 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import '../core/harness_cli_runner.dart';+import '../core/serial_port_lease.dart';++/// What a line of flasher output is.+///+/// The script prints a flat stream; the shape is carried by the prefix. `>> `+/// opens a step, an indented line details the step in progress, and anything on+/// stderr is trouble. Nothing here re-orders or drops a line — the raw log stays+/// the record, and this only decides what the UI emphasises.+enum FlashLineKind { step, detail, warning, error }++class FlashLine {+ final String text;+ final FlashLineKind kind;++ const FlashLine(this.text, this.kind);++ /// The step title without its `>> ` marker, for the step list.+ String get title => text.startsWith('>> ') ? text.substring(3) : text;+}++/// Outcome of a finished run.+class FlashResult {+ final int exitCode;+ final bool cancelled;++ const FlashResult({required this.exitCode, this.cancelled = false});++ bool get ok => exitCode == 0 && !cancelled;+}++/// What `--detect-only` found.+class FlashProbe {+ /// Ports the script recognised as an ESP32-S3.+ final List<String> ports;++ /// Set when it refused for a reason the user can act on.+ final String? problem;++ /// Everything it printed, kept for the log pane.+ final List<FlashLine> log;++ const FlashProbe({required this.ports, required this.log, this.problem});++ bool get found => ports.isNotEmpty;+}++/// Runs the published flasher through the installed `harness` CLI.+///+/// The app deliberately does NOT fetch or cache `flash-circle.sh` itself.+/// `harness flash` already owns which script to run and how to get it, and the+/// script owns every number that decides whether a board survives the write —+/// the chip, the app offset, the otadata region, the sha256 checks. A second+/// copy of any of that here is a bricked board the day the two disagree. This+/// class owns one thing: turning that command's output into something a window+/// can draw.+class Flasher {+ Flasher({this.startProcess = harnessCliStart});++ /// Overridden in tests.+ final Future<Process> Function(List<String> arguments) startProcess;++ Process? _running;+ bool _cancelled = false;++ bool get isRunning => _running != null;++ /// Looks for a plugged-in board without touching it.+ ///+ /// `--detect-only` returns before the script would stop the Harness daemon,+ /// so opening the dialog costs nothing: no daemon bounce, no write, no+ /// download.+ Future<FlashProbe> probe() async {+ final log = <FlashLine>[];+ final ports = <String>[];+ String? problem;++ final code = await _run(['flash', '--detect-only'], (line) {+ log.add(line);+ final text = line.text;+ const marker = '>> board: ';+ if (text.startsWith(marker)) {+ ports.add(text.substring(marker.length).trim());+ } else if (text.startsWith('more than one ESP32-S3')) {+ problem = 'more than one board is connected';+ } else if (text.contains('no permission')) {+ problem = 'no permission to open the serial port';+ }+ });++ if (code != 0 && problem == null) {+ problem = _errorFrom(log) ?? 'could not look for a board';+ }+ return FlashProbe(ports: ports, log: log, problem: problem);+ }++ /// Writes the latest release to [port], or to whatever the script picks.+ ///+ /// `--yes` is not optional. The script asks for confirmation on `/dev/tty`,+ /// and an app launched from Finder has none — without it the run dies with+ /// "not a terminal" before writing anything. The dialog's Flash button IS+ /// that confirmation.+ Future<FlashResult> flash({String? port, void Function(FlashLine)? onLine}) {+ final command = ['flash', '--yes'];+ if (port != null && port.isNotEmpty) command.addAll(['--port', port]);+ // Held for the WHOLE run, not just the write. The script stops the daemon itself and starts it+ // again at the end; between those two the port belongs to esptool, and the app's own daemon+ // supervisor — a five-second timer that restarts anything it finds missing — would otherwise take+ // it back and kill the flash a few tens of kilobytes in.+ return SerialPortLease.hold(() async {+ final code = await _run(command, (line) => onLine?.call(line));+ return FlashResult(exitCode: code, cancelled: _cancelled);+ });+ }++ /// Asks a running flash to stop, and lets it unwind.+ ///+ /// SIGTERM, never SIGKILL. The script arms+ /// `trap start_harness_after_flash EXIT INT TERM`, and that trap is the only+ /// thing that brings the Harness daemon back after the script stopped it to+ /// free the serial port. Killing it outright leaves the computer with no+ /// daemon and the dial dark — worse than never having flashed at all.+ void cancel() {+ final process = _running;+ if (process == null) return;+ _cancelled = true;+ process.kill(ProcessSignal.sigterm);+ }++ Future<int> _run(+ List<String> command,+ void Function(FlashLine) onLine,+ ) async {+ if (_running != null) throw StateError('a flash is already running');+ _cancelled = false;+ final process = await startProcess(command);+ _running = process;+ try {+ final pumps = <Future<void>>[+ _pump(process.stdout, onLine, stderr: false),+ _pump(process.stderr, onLine, stderr: true),+ ];+ final code = await process.exitCode;+ // Drain first: the last lines can still be in flight when the process+ // has already gone, and losing them loses the reason it failed.+ await Future.wait(pumps);+ return code;+ } finally {+ _running = null;+ }+ }++ Future<void> _pump(+ Stream<List<int>> source,+ void Function(FlashLine) onLine, {+ required bool stderr,+ }) {+ return source+ .transform(utf8.decoder)+ .transform(const LineSplitter())+ .forEach((raw) => onLine(classifyFlashLine(raw, stderr: stderr)));+ }++ static String? _errorFrom(List<FlashLine> log) {+ for (final line in log.reversed) {+ if (line.kind == FlashLineKind.error) {+ return line.text.replaceFirst(RegExp(r'^error:\s*'), '');+ }+ }+ return null;+ }+}++/// Decides what a raw output line is.+///+/// Pure, so the rule can be tested without spawning anything.+FlashLine classifyFlashLine(String raw, {required bool stderr}) {+ final text = raw.trimRight();+ if (text.startsWith('error:')) return FlashLine(text, FlashLineKind.error);+ if (text.startsWith('>> ')) return FlashLine(text, FlashLineKind.step);+ // Indented lines detail the running step. On stderr they are the script's+ // warnings — same shape, but they must not read as routine.+ if (stderr) return FlashLine(text, FlashLineKind.warning);+ return FlashLine(text, FlashLineKind.detail);+}++/// Starts `harness flash` with the managed runtime. [HarnessCliRunner] also+/// puts the legacy launcher directory on PATH for the child script, so the+/// flasher can stop and restart its daemon reliably without zsh.+Future<Process> harnessCliStart(List<String> arguments) =>+ HarnessCliRunner().start(arguments);diff --git a/mobile/lib/logging/app_log.dart b/mobile/lib/logging/app_log.dartnew file mode 100644index 000000000..bf5f5d650--- /dev/null+++ b/mobile/lib/logging/app_log.dart@@ -0,0 +1,150 @@+import 'error_burst_filter.dart';+import 'log_file.dart';++/// Severity of an [AppLog] event, in ascending order.+enum AppLogLevel { debug, info, warn, error }++/// The app's own diagnostic logger — a durable, human-readable timeline written+/// to `~/.harness/logs/app-YYYYMMDD.log`.+///+/// Ported from Grid, with one change: Riverpod out, a singleton in. The call+/// sites here are `main`, `AppNotifier`, `WsConn` and the CLI runner, and most+/// were never handed a `Ref` — the same reasoning that made `analytics` a+/// singleton (see `analytics/analytics.dart`).+///+/// **Distinct from [CrashLog], and both are kept.** `CrashLog` answers "what+/// threw", in one file, forever, with a full stack; this answers "what was the+/// app *doing*", per day, pruned after two weeks. A crash whose stack names a+/// line still needs the ten lines before it to be explicable — that is what this+/// is for. `installFileLogs` wires errors into both.+///+/// [category] is a short, stable tag grouping related events — `app`+/// (lifecycle), `ws` (the socket this app lives on), `cli`, `api`, `flutter` —+/// so the timeline can be skimmed or filtered by concern.+abstract interface class AppLog {+ /// Append one structured event. [error]/[stackTrace] are included when present+ /// (the stack trace is indented on following lines).+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ });+}++/// Level-named conveniences over [AppLog.record], kept as extensions so every+/// [AppLog] implementation gets them for free without re-declaring the surface.+extension AppLogX on AppLog {+ void debug(String category, String message) =>+ record(AppLogLevel.debug, category, message);++ void info(String category, String message) =>+ record(AppLogLevel.info, category, message);++ void warn(String category, String message, {Object? error}) =>+ record(AppLogLevel.warn, category, message, error: error);++ void failure(+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) => record(+ AppLogLevel.error,+ category,+ message,+ error: error,+ stackTrace: stackTrace,+ );+}++/// [AppLog] backed by a per-day file under `~/.harness/logs`. Writes are+/// synchronous and flushed (see [DailyLogFile]); IO errors are swallowed.+class FileAppLog implements AppLog {+ FileAppLog(this._file, {ErrorBurstFilter? burst, DateTime Function()? clock})+ : _burst = burst ?? ErrorBurstFilter(),+ _clock = clock ?? DateTime.now;++ final DailyLogFile _file;++ /// Injected so the stamp this writes is a thing a test can assert, rather than+ /// a thing a test has to watch happen. Same reason [ErrorBurstFilter] takes one.+ final DateTime Function() _clock;++ /// Applied to ERROR only. An exception thrown from `build` or a frame callback+ /// repeats every frame, and each copy costs an fsync on the UI isolate — which+ /// is how a glitch becomes a hang. Lower levels are things this app chose to+ /// say once, so they are not filtered.+ final ErrorBurstFilter _burst;++ @override+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) {+ // The body is built WITHOUT the timestamp, and the stamp is put on last.+ // ErrorBurstFilter signs an error by its first line, so handing it a stamped+ // line would make every copy a different error the moment the clock ticked —+ // suppression would work inside one second and never report a count.+ final body = StringBuffer(+ '${_levelTag(level)} ${_categoryTag(category)} $message',+ );+ if (error != null) body.write(' err=$error');++ if (level != AppLogLevel.error) {+ _file.append('[${logStamp(_clock())}] $body');+ _appendStack(stackTrace);+ return;+ }+ final admitted = _burst.admit(body.toString());+ if (admitted == null) return;+ _file.append('[${logStamp(_clock())}] $admitted');+ _appendStack(stackTrace);+ }++ void _appendStack(StackTrace? stackTrace) {+ if (stackTrace == null) return;+ _file.append(+ stackTrace+ .toString()+ .trimRight()+ .split('\n')+ .map((l) => ' $l')+ .join('\n'),+ );+ }++ /// Five-wide upper-case level so message columns line up.+ static String _levelTag(AppLogLevel level) => switch (level) {+ AppLogLevel.debug => 'DEBUG',+ AppLogLevel.info => 'INFO ',+ AppLogLevel.warn => 'WARN ',+ AppLogLevel.error => 'ERROR',+ };++ /// Pad short categories to a common width for a readable second column.+ static String _categoryTag(String category) =>+ category.length >= 7 ? category : category.padRight(7);+}++/// No-op [AppLog]. The default, so a `flutter test` run never writes into a real+/// `~/.harness` — the same rule analytics follows, and for the same reason.+class NoopAppLog implements AppLog {+ const NoopAppLog();++ @override+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) {}+}++/// The app-log sink. Muted until [installFileLogs] swaps in the file sink.+AppLog appLog = const NoopAppLog();diff --git a/mobile/lib/logging/cli_log.dart b/mobile/lib/logging/cli_log.dartnew file mode 100644index 000000000..ab2edfa2b--- /dev/null+++ b/mobile/lib/logging/cli_log.dart@@ -0,0 +1,94 @@+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/cli_transcript.dart b/mobile/lib/logging/cli_transcript.dartnew file mode 100644index 000000000..82b8b2a1f--- /dev/null+++ b/mobile/lib/logging/cli_transcript.dart@@ -0,0 +1,129 @@+/// Records a child process into [cliLog] — the transcript both the daily file+/// and Settings ▸ Debug are built from.+///+/// One place, used by [HarnessCliRunner]: "the CLI did something unexpected"+/// is the most common shape of a fault here, since the app itself holds almost+/// no logic.+///+/// **A command line and its output are logged; its environment is not.** A+/// secret handed to a child belongs in its environment precisely so it stays+/// out of argv, and writing the environment here would undo that. What the+/// child *prints* can still carry one — `harness auth status --json` prints a+/// session — so every line goes through [redactSecretsInText] first.+library;++import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'cli_log.dart';+import 'redact.dart';++/// Output lines kept per invocation. Enough to see what a command answered,+/// short of pasting a whole `--json` catalogue into the day's log.+const int _maxOutputLines = 40;++/// Longest single line kept. A base64 blob buries the lines either side of it.+const int _maxLineChars = 500;++/// Runs [call] as one logged invocation of [command].+///+/// [command] is the display line — `harness auth status --json` — not the real+/// argv, which for the managed tier is `<node> <cli.js> …` and reads as noise.+Future<ProcessResult> logProcessRun(+ String command,+ Future<ProcessResult> Function() call,+) async {+ final entry = cliLog.begin(redactSecretsInText(command));+ final started = DateTime.now();+ try {+ final result = await call();+ _writeOutput(entry, result);+ entry.end(+ exitCode: result.exitCode,+ duration: DateTime.now().difference(started),+ );+ return result;+ } on Object catch (error) {+ // A missing binary is a ProcessException, and it is the single most useful+ // line this log can hold — so it is recorded before it is rethrown.+ entry.end(error: '$error', duration: DateTime.now().difference(started));+ rethrow;+ }+}++/// Opens a section for a long-running child and closes it when the child exits.+///+/// Its output is not captured: the caller owns those streams (that is why it+/// asked for a [Process]), and a second listener would steal the bytes it is+/// reading. So a streamed command records that it started, and how it ended.+Future<Process> logProcessStart(+ String command,+ Future<Process> Function() call,+) async {+ final entry = cliLog.begin(redactSecretsInText(command));+ final started = DateTime.now();+ final Process process;+ try {+ process = await call();+ } on Object catch (error) {+ entry.end(error: '$error', duration: DateTime.now().difference(started));+ rethrow;+ }+ unawaited(+ process.exitCode+ .then(+ (code) => entry.end(+ exitCode: code,+ duration: DateTime.now().difference(started),+ ),+ )+ // The child's fate is the caller's business; this listener only reports+ // it, so its own failure must not become an unhandled error.+ .catchError(+ (Object error) => entry.end(+ error: '$error',+ duration: DateTime.now().difference(started),+ ),+ ),+ );+ return process;+}++/// Writes a finished command's stdout and stderr into its section, redacted,+/// clipped, and stderr tagged.+void _writeOutput(CliLogEntry entry, ProcessResult result) {+ var budget = _maxOutputLines;+ budget = _writeStream(entry, result.stdout, budget, isError: false);+ budget = _writeStream(entry, result.stderr, budget, isError: true);+}++int _writeStream(+ CliLogEntry entry,+ Object? stream,+ int budget, {+ required bool isError,+}) {+ if (budget <= 0) return budget;+ final text = stream is String ? stream : '${stream ?? ''}';+ final lines = const LineSplitter()+ .convert(redactSecretsInText(text))+ .where((line) => line.trim().isNotEmpty)+ .toList();+ for (final line in lines.take(budget)) {+ entry.output(+ line.length > _maxLineChars+ ? '${line.substring(0, _maxLineChars)}…'+ : line,+ isError: isError,+ );+ }+ final kept = lines.length < budget ? lines.length : budget;+ if (lines.length > kept) {+ entry.output(+ '… ${lines.length - kept} more lines not kept',+ isError: isError,+ );+ }+ return budget - kept;+}diff --git a/mobile/lib/logging/debug_surface.dart b/mobile/lib/logging/debug_surface.dartnew file mode 100644index 000000000..08095bb8b--- /dev/null+++ b/mobile/lib/logging/debug_surface.dart@@ -0,0 +1,17 @@+import 'package:flutter/foundation.dart';++/// Whether this build shows its developer surfaces: Settings ▸ Debug and its+/// ⌘D shortcut, Settings ▸ Tracking, and the two in-memory buffers that feed+/// them (`logStream`, `analyticsLog`).+///+/// A debug build has it; a release build does not. The log *files* are written+/// either way — a shipped app that has no stderr anyone reads is exactly the+/// one whose logs matter (see `logging/app_log.dart`) — but the screen that+/// reads them back is developer furniture, and the ring buffer behind it is+/// memory a user's session should not spend.+///+/// `HARNESS_DEBUG_SURFACE=true` turns it on in a release build, for the one+/// case that is otherwise unreachable: reproducing a fault on a packaged app,+/// where a debug build's timing is not the timing being complained about.+const bool kDebugSurfaceEnabled =+ kDebugMode || bool.fromEnvironment('HARNESS_DEBUG_SURFACE');diff --git a/mobile/lib/logging/error_burst_filter.dart b/mobile/lib/logging/error_burst_filter.dartnew file mode 100644index 000000000..f81086d6c--- /dev/null+++ b/mobile/lib/logging/error_burst_filter.dart@@ -0,0 +1,69 @@+/// Decides whether one more copy of a repeating error is worth writing down.+///+/// An exception thrown from `build`, `paint` or a frame callback doesn't happen+/// once — it repeats *every frame*, and [DailyLogFile] appends each copy with an+/// `fsync` on the UI isolate. That is how a glitch turns into a hang: on+/// 2026-08-06 a tooltip assertion inside the mouse tracker repeated 11,406 times+/// in two and a half minutes, wrote 19MB of identical stack traces, and the app+/// had to be killed. The first copy carries the diagnosis; the rest only need to+/// be counted.+///+/// Errors are matched on their first line, so the same failure with a slightly+/// different tail still counts as one burst.+///+/// Pure and clock-injected: the rule is tested rather than watched.+class ErrorBurstFilter {+ ErrorBurstFilter({+ this.window = const Duration(seconds: 30),+ DateTime Function() clock = DateTime.now,+ // The field is private, so an initialising formal would name the+ // PARAMETER `_clock` — which no caller outside this library could pass.+ // The clock is injected by tests.+ // ignore: prefer_initializing_formals+ }) : _clock = clock;++ /// How long an error stays suppressed after a copy of it is written.+ final Duration window;++ final DateTime Function() _clock;++ /// When each error was last written, and how many copies were swallowed since.+ final Map<String, ({DateTime at, int suppressed})> _seen = {};++ /// Past this many distinct errors the map is cleared wholesale: a guard+ /// against floods must not become the leak it was meant to prevent.+ static const int _maxTracked = 256;++ /// How many distinct errors are currently being tracked — the one thing worth+ /// asserting about the bound above.+ int get trackedCount => _seen.length;++ /// The text to log for [message], or null when this copy should be dropped.+ ///+ /// The returned text is [message] itself, with a count appended when copies+ /// were swallowed while it was suppressed — so the log says "this happened+ /// 3,000 times", never just "this happened".+ String? admit(String message) {+ final now = _clock();+ final key = _signature(message);+ final last = _seen[key];+ if (last != null && now.difference(last.at) < window) {+ _seen[key] = (at: last.at, suppressed: last.suppressed + 1);+ return null;+ }+ if (_seen.length >= _maxTracked) _seen.clear();+ _seen[key] = (at: now, suppressed: 0);+ final swallowed = last?.suppressed ?? 0;+ return swallowed == 0+ ? message+ : '$message [+$swallowed identical since the last copy]';+ }++ /// The first line, capped: enough to tell two failures apart without hashing a+ /// whole stack trace on every frame of a burst.+ static String _signature(String message) {+ final end = message.indexOf('\n');+ final line = end < 0 ? message : message.substring(0, end);+ return line.length <= 200 ? line : line.substring(0, 200);+ }+}diff --git a/mobile/lib/logging/http_log.dart b/mobile/lib/logging/http_log.dartnew file mode 100644index 000000000..aa332442e--- /dev/null+++ b/mobile/lib/logging/http_log.dart@@ -0,0 +1,70 @@+import 'package:dio/dio.dart';++import 'app_log.dart';+import 'redact.dart';++/// The app's HTTP calls, in the same timeline as everything else it does.+///+/// One line per finished request — `GET /api/machines → 200 (118ms)` — under+/// the `api` category, which is what makes it a lens of its own in Settings ▸+/// Debug. The shape is deliberately Grid's (`CommandLogNotifier._mirrorToAppLog`),+/// so the two products' logs read alike.+///+/// **Headers and bodies are not logged.** An `Authorization` header is a live+/// credential; a body can carry one too. A URL can carry+/// one in its query, so the line goes through [redactSecretsInText] first.+///+/// Successful calls log at `debug`, because the status rail polls every 60s+/// and a day of that is not news; a failure logs at `warn`, where it+/// joins the Failed lens.+Dio attachHttpLog(Dio dio) {+ dio.interceptors.add(_HttpLogInterceptor());+ return dio;+}++/// Key under which the request's start time rides along on its own options —+/// the only place an interceptor can keep per-request state.+const String _startedAtKey = 'harnessLogStartedAt';++class _HttpLogInterceptor extends Interceptor {+ @override+ void onRequest(RequestOptions options, RequestInterceptorHandler handler) {+ options.extra[_startedAtKey] = DateTime.now();+ handler.next(options);+ }++ @override+ void onResponse(+ Response<dynamic> response,+ ResponseInterceptorHandler handler,+ ) {+ final status = response.statusCode;+ // `validateStatus` lets 4xx and 5xx through as responses in both of this+ // app's clients, so "it answered" is not the same as "it worked".+ final failed = status == null || status < 200 || status >= 300;+ final line =+ '${_line(response.requestOptions)} → $status'+ '${_took(response.requestOptions)}';+ failed ? appLog.warn('api', line) : appLog.debug('api', line);+ handler.next(response);+ }++ @override+ void onError(DioException error, ErrorInterceptorHandler handler) {+ appLog.warn(+ 'api',+ '${_line(error.requestOptions)} → failed${_took(error.requestOptions)}',+ error: error.message ?? error.type.name,+ );+ handler.next(error);+ }++ static String _line(RequestOptions options) =>+ redactSecretsInText('${options.method} ${options.uri}');++ static String _took(RequestOptions options) {+ final started = options.extra[_startedAtKey];+ if (started is! DateTime) return '';+ return ' (${DateTime.now().difference(started).inMilliseconds}ms)';+ }+}diff --git a/mobile/lib/logging/install.dart b/mobile/lib/logging/install.dartnew file mode 100644index 000000000..03df5fa28--- /dev/null+++ b/mobile/lib/logging/install.dart@@ -0,0 +1,35 @@+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`.+const String kAppLogBase = 'app';+const String kCliLogBase = 'cli';++/// Point [appLog] and [cliLog] 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+/// write into a real Harness home no matter which code path it exercises — the+/// same rule analytics follows.+///+/// Deliberately not `async`: the first lines this app writes are the ones about+/// starting up, and awaiting a directory probe here would lose them.+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+ // copy is already written.+ appLog = FanoutAppLog([file, StreamAppLog(logStream)]);+ cliLog = FanoutCliLog([cli, StreamCliLog(logStream)]);+}diff --git a/mobile/lib/logging/log_file.dart b/mobile/lib/logging/log_file.dartnew file mode 100644index 000000000..453407a14--- /dev/null+++ b/mobile/lib/logging/log_file.dart@@ -0,0 +1,141 @@+import 'dart:developer' as developer;+import 'dart:io';++import '../core/harness_file_store.dart';++/// Best-effort append-only diagnostic log split into one file per calendar day+/// (`<base>-YYYYMMDD.log`) inside a directory.+///+/// Ported from Grid (`autonomous-grid-app/lib/infrastructure/logging/`) rather+/// than reinvented — same rotation rules, same swallow-everything discipline,+/// so a log line means the same thing in both products. Keep the two in step.+///+/// Why per-day: a single ever-growing file eventually becomes too big to open or+/// send us, and a size-based `.old` rotation keeps only the last slice. Dating+/// the file caps each day's size on its own and lets anything past+/// [retentionDays] be pruned automatically, so the directory stays bounded+/// without ever discarding the current session.+///+/// Writes are synchronous and flushed so a line survives even if the app is+/// force-quit mid-write, and every IO error is swallowed — diagnostic logging+/// must never break the flow it only observes.+class DailyLogFile {+ DailyLogFile(+ this.directory,+ this.base, {+ this.retentionDays = 14,+ DateTime Function() clock = DateTime.now,+ // The field is private, so an initialising formal would name the+ // PARAMETER `_clock` — which no caller outside this library could pass.+ // The clock is injected by tests.+ // ignore: prefer_initializing_formals+ }) : _clock = clock;++ /// The app's own log directory, `~/.harness/logs`.+ ///+ /// Through [HarnessFileStore.defaultDirectoryPath] rather than a second path+ /// helper: one place already knows how to find `~/.harness` on every platform+ /// this ships to, including the Windows fallbacks.+ static Directory get defaultDirectory =>+ Directory(HarnessFileStore.defaultDirectoryPath(name: 'logs'));++ /// Directory holding the dated files. Created on demand.+ final Directory directory;++ /// Filename stem shared by every day's file — `app` → `app-YYYYMMDD.log`.+ final String base;++ /// Keep at most this many days of this base's files; older ones are deleted+ /// the first time a new day is written. A value `<= 0` disables pruning.+ final int retentionDays;++ final DateTime Function() _clock;++ /// `YYYYMMDD` of the file we last wrote, so pruning only runs when the day+ /// actually rolls over — not on every append.+ String? _activeDay;++ /// The file the next [append] would write to, for the current wall-clock day.+ /// Exposed so callers (and tests) can read back what was just written.+ File get currentFile => _fileFor(_clock());++ File _fileFor(DateTime day) =>+ File('${directory.path}/${dailyLogName(base, day)}');++ /// Append [block] followed by a newline to today's file. Creates the directory+ /// on demand and prunes stale days on the first write after midnight; any+ /// failure is swallowed.+ void append(String block) {+ try {+ final now = _clock();+ final day = _ymd(now);+ final file = _fileFor(now);+ file.parent.createSync(recursive: true);+ if (day != _activeDay) {+ _activeDay = day;+ _pruneOlderThan(now);+ }+ file.writeAsStringSync('$block\n', mode: FileMode.append, flush: true);+ } catch (e) {+ // Best-effort: never surface an IO failure into the caller's flow.+ _debugLog('DailyLogFile.append failed: $e');+ }+ }++ /// Delete this base's dated files older than [retentionDays] before [now].+ void _pruneOlderThan(DateTime now) {+ if (retentionDays <= 0) return;+ try {+ final cutoff = _ymd(now.subtract(Duration(days: retentionDays)));+ final prefix = '$base-';+ for (final entry in directory.listSync()) {+ if (entry is! File) continue;+ final name = entry.uri.pathSegments.last;+ if (!name.startsWith(prefix) || !name.endsWith('.log')) continue;+ final day = name.substring(prefix.length, name.length - 4);+ if (day.length == 8 &&+ int.tryParse(day) != null &&+ day.compareTo(cutoff) < 0) {+ entry.deleteSync();+ }+ }+ } catch (e) {+ // Pruning is best-effort; on failure the old files simply stay put.+ _debugLog('DailyLogFile._pruneOlderThan failed: $e');+ }+ }+}++/// Debug-only diagnostic for a swallowed log-sink IO failure. A log sink cannot+/// route its own failure through the app's log stack without recursing, so this+/// uses `dart:developer` directly — the one deliberate exception. `assert`+/// strips it from release builds, so it never adds noise to a shipped app.+void _debugLog(String message) {+ assert(() {+ developer.log(message);+ return true;+ }());+}++/// The dated filename for [base] on [day]: `app` → `app-20260907.log`.+String dailyLogName(String base, DateTime day) => '$base-${_ymd(day)}.log';++/// `YYYY-MM-DD HH:MM:SS` — a full wall-clock stamp for section headers.+String logStamp(DateTime t) =>+ '${t.year}-${_pad2(t.month)}-${_pad2(t.day)} ${logClock(t)}';++/// `HH:MM:SS` — a compact clock stamp for per-line entries.+String logClock(DateTime t) =>+ '${_pad2(t.hour)}:${_pad2(t.minute)}:${_pad2(t.second)}';++/// A short human duration: `${m}m${s}s` past a minute, else `${s}s`.+String logDuration(Duration d) {+ final s = d.inSeconds;+ return s >= 60 ? '${s ~/ 60}m${s % 60}s' : '${s}s';+}++/// `YYYYMMDD` — the compact calendar-day stamp used in daily log filenames.+String _ymd(DateTime t) =>+ '${t.year.toString().padLeft(4, '0')}${_pad2(t.month)}${_pad2(t.day)}';++String _pad2(int n) => n.toString().padLeft(2, '0');diff --git a/mobile/lib/logging/log_stream.dart b/mobile/lib/logging/log_stream.dartnew file mode 100644index 000000000..8b866d91d--- /dev/null+++ b/mobile/lib/logging/log_stream.dart@@ -0,0 +1,217 @@+import 'dart:async';+import 'dart:collection';++import 'package:flutter/foundation.dart';++import 'app_log.dart';++/// How a [LogEntry] ended, as the Debug list draws it.+enum LogStatus { running, ok, failed, warned, event }++/// One thing the app did, held in memory for Settings ▸ Debug.+///+/// The same events the file sinks write — this is a *mirror* of them, not a+/// second stream (see `log_stream_sinks.dart`), so what the screen shows and+/// what a support bundle would carry can never disagree.+///+/// Deliberately mutable, unlike Grid's `GridCommandLog`, which is immutable and+/// re-created through `copyWith` because Riverpod compares state objects. This+/// buffer is a [ChangeNotifier]: a command that is still running collects its+/// output lines and its exit code in place, and the one notification that+/// follows is what the list rebuilds on.+class LogEntry {+ LogEntry({+ required this.id,+ required this.at,+ required this.level,+ required this.category,+ required this.message,+ this.error,+ this.stackTrace,+ this.command,+ });++ /// Monotonic within a session — also the id [LogStream] updates a running+ /// command by.+ final int id;++ final DateTime at;++ /// `app`, `ws`, `cli`, `api`, `flutter` — [AppLog]'s own tag, which is what+ /// the Debug screen's lenses are built from.+ final String category;++ /// The line as the log file holds it, minus the stamp and the level.+ final String message;++ /// Decided when a command ends, so a non-zero exit reads as an error without+ /// the caller having to say so twice.+ AppLogLevel level;++ final String? error;+ final String? stackTrace;++ /// Present only for a CLI invocation — the transcript behind [message].+ final LogCommand? command;++ LogStatus get status {+ final invocation = command;+ if (invocation == null) {+ return switch (level) {+ AppLogLevel.error => LogStatus.failed,+ AppLogLevel.warn => LogStatus.warned,+ _ => LogStatus.event,+ };+ }+ if (invocation.running) return LogStatus.running;+ return invocation.failed ? LogStatus.failed : LogStatus.ok;+ }++ /// Whether opening the row would show anything the row itself does not.+ bool get hasDetail =>+ error != null ||+ stackTrace != null ||+ (command?.output.isNotEmpty ?? false);+}++/// One CLI invocation's transcript: its output as it arrives, and how it ended.+class LogCommand {+ /// Output lines, oldest first. `!` lines are stderr, tagged at the sink so+ /// the detail dialog can colour them without a second list.+ final List<String> output = [];++ bool running = true;+ int? exitCode;+ Duration? duration;+ String? error;++ /// Set once [LogStream.maxOutputLines] is reached — said out loud rather than+ /// trailing off, so nobody reads a clipped transcript as the whole one.+ bool clipped = false;++ bool get failed => error != null || (exitCode != null && exitCode != 0);+}++/// 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+/// 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`+/// and no notifier between them.+class LogStream extends ChangeNotifier {+ LogStream({this.maxEntries = 500, this.maxOutputLines = 300});++ /// How many entries the buffer keeps. Past this the oldest are dropped: this+ /// is the tail of a session, and the whole day is on disk.+ final int maxEntries;++ /// Per-command output cap. An installer prints a progress line per second;+ /// two hundred of those is the app's memory, not a debug aid.+ final int maxOutputLines;++ final List<LogEntry> _entries = [];+ int _seq = 0;+ bool _notifyScheduled = false;++ /// Newest first — the order the Debug list reads in, so the newest line is+ /// the one on screen without scrolling.+ late final UnmodifiableListView<LogEntry> entries = UnmodifiableListView(+ _entries,+ );++ /// Records one event. Returns its id, which [appendOutput] and [finish] take.+ int add(+ AppLogLevel level,+ String category,+ String message, {+ String? error,+ String? stackTrace,+ LogCommand? command,+ }) {+ final id = ++_seq;+ _entries.insert(+ 0,+ LogEntry(+ id: id,+ at: DateTime.now(),+ level: level,+ category: category,+ message: message,+ error: error,+ stackTrace: stackTrace,+ command: command,+ ),+ );+ if (_entries.length > maxEntries) {+ _entries.removeRange(maxEntries, _entries.length);+ }+ _scheduleNotify();+ return id;+ }++ /// Appends one line of a running command's output.+ void appendOutput(int id, String line, {bool isError = false}) {+ final command = _commandFor(id);+ if (command == null) return;+ if (command.output.length >= maxOutputLines) {+ command.clipped = true;+ return;+ }+ command.output.add('${isError ? '! ' : ' '}$line');+ _scheduleNotify();+ }++ /// Closes a command out. A non-zero exit or an [error] also raises the+ /// entry's level, so it lands in the Failed lens without a second call.+ void finish(int id, {int? exitCode, Duration? duration, String? error}) {+ final entry = _entryFor(id);+ final command = entry?.command;+ if (entry == null || command == null || !command.running) return;+ command+ ..running = false+ ..exitCode = exitCode+ ..duration = duration+ ..error = error;+ if (command.failed) entry.level = AppLogLevel.error;+ _scheduleNotify();+ }++ void clear() {+ if (_entries.isEmpty) return;+ _entries.clear();+ _scheduleNotify();+ }++ LogEntry? _entryFor(int id) {+ // A command finishes near where it started, and the newest entries are at+ // the front — so this walks a handful of rows, not the buffer.+ for (final entry in _entries) {+ if (entry.id == id) return entry;+ }+ return null;+ }++ LogCommand? _commandFor(int id) {+ final command = _entryFor(id)?.command;+ return command != null && command.running ? command : null;+ }++ /// One notification per microtask, however many lines arrived in it.+ ///+ /// A CLI command's output lands line by line and a busy socket writes several+ /// frames per frame of UI; notifying on each would rebuild the Debug list+ /// dozens of times for one visible change.+ void _scheduleNotify() {+ if (_notifyScheduled) return;+ _notifyScheduled = true;+ scheduleMicrotask(() {+ _notifyScheduled = false;+ notifyListeners();+ });+ }+}++/// The app's in-memory log mirror. Empty unless [installFileLogs] wired the+/// mirroring sinks — which it only does where the Debug screen exists.+final LogStream logStream = LogStream();diff --git a/mobile/lib/logging/log_stream_sinks.dart b/mobile/lib/logging/log_stream_sinks.dartnew file mode 100644index 000000000..ae025e900--- /dev/null+++ b/mobile/lib/logging/log_stream_sinks.dart@@ -0,0 +1,139 @@+/// The sinks that put the app's log in two places at once: the daily files, and+/// 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+/// 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.+class FanoutAppLog implements AppLog {+ const FanoutAppLog(this.sinks);++ final List<AppLog> sinks;++ @override+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) {+ for (final sink in sinks) {+ sink.record(+ level,+ category,+ message,+ error: error,+ stackTrace: stackTrace,+ );+ }+ }+}++/// [AppLog] that appends to a [LogStream].+///+/// No burst filter, unlike [FileAppLog]: this costs no fsync, and an error+/// repeating every frame is itself the thing a developer opened this screen to+/// see. The ring bounds what it can cost.+class StreamAppLog implements AppLog {+ const StreamAppLog(this._stream);++ final LogStream _stream;++ @override+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) {+ _stream.add(+ level,+ category,+ message,+ error: error?.toString(),+ stackTrace: stackTrace?.toString(),+ );+ }+}++/// 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.dartnew file mode 100644index 000000000..fdafab7cf--- /dev/null+++ b/mobile/lib/logging/redact.dart@@ -0,0 +1,114 @@+/// Turning a WS frame into one log line, with credentials removed.+///+/// This exists because the frames worth logging are the ones most likely to+/// carry secrets — a key, a token, a session — and a blind `payload.toString()`+/// would write one to `~/.harness/logs`, where it outlives whatever it was+/// minted for.+///+/// The rule is a DENYLIST on key names rather than an allowlist on purpose. An+/// allowlist would silently drop the next field somebody adds — and the whole+/// value of this log is seeing fields nobody thought to anticipate. The cost is+/// that a new secret must be named here; [_secretKey] is deliberately broad for+/// that reason, and [redactValue] is exported so a test can pin it.+library;++/// Key names whose value must never reach the log. Broad on purpose: matching a+/// field that was not secret costs one unreadable line, missing one that was+/// costs a credential on disk.+final RegExp _secretKey = RegExp(+ r'key|token|secret|password|passphrase|credential|auth|bearer|cookie|session',+ caseSensitive: false,+);++/// Values longer than this are clipped — a log line is read by a person, and a+/// base64 blob buries the fields either side of it.+const int _maxValue = 120;++/// One frame payload as a log line: `{engine: codex, apiKey: <redacted>}`.+///+/// The cap is generous because of what these lines are for. An `agent_create`+/// reply carries a whole `Agent` — id, name, engine, session, status, cwd — and+/// a tighter cap reads better but would cut off the last field in it, which is+/// as likely as any to be the one somebody is reading the log to find. Individual values are+/// still clipped at [_maxValue], so one blob cannot eat the budget.+String summariseForLog(Object? value, {int maxLength = 1200}) {+ final text = redactValue(value);+ return text.length <= maxLength ? text : '${text.substring(0, maxLength)}…';+}++/// [value] rendered for a log, with any entry whose KEY looks secret replaced.+///+/// Recurses into maps and lists so a secret nested a level or two down is+/// caught too.+String redactValue(Object? value) {+ if (value == null) return 'null';+ if (value is Map) {+ final parts = <String>[];+ for (final entry in value.entries) {+ final key = '${entry.key}';+ parts.add(+ _secretKey.hasMatch(key)+ ? '$key: <redacted>'+ : '$key: ${redactValue(entry.value)}',+ );+ }+ return '{${parts.join(', ')}}';+ }+ if (value is List) {+ // Length, not contents: a list in a frame is a batch (agents, models,+ // frames) and printing it whole turns one line into a page.+ return '[${value.length} item${value.length == 1 ? '' : 's'}]';+ }+ final text = '$value';+ return text.length <= _maxValue ? text : '${text.substring(0, _maxValue)}…';+}++/// Anything in free-form CLI output that could be a secret, blanked.+///+/// [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+/// 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.+///+/// Conservative on purpose: it would rather blank a harmless high-entropy+/// string than write a live token to a file with a fortnight's retention.+String redactSecretsInText(String input) {+ var out = input;+ for (final rule in _textRedactions) {+ out = out.replaceAllMapped(rule.pattern, rule.replace);+ }+ return out;+}++typedef _Redaction = ({RegExp pattern, String Function(Match) replace});++final List<_Redaction> _textRedactions = [+ // `Bearer <token>` — the shape auth takes if it ever lands in output.+ (+ pattern: RegExp(r'(Bearer\s+)[A-Za-z0-9._\-]{8,}', caseSensitive: false),+ replace: (m) => '${m[1]}<redacted>',+ ),+ // Vendor keys with a well-known prefix (OpenAI `sk-…`, Anthropic `sk-ant-…`).+ (+ pattern: RegExp(r'\bsk-[A-Za-z0-9_\-]{8,}'),+ replace: (_) => 'sk-<redacted>',+ ),+ // `"session_token": "…"`, `key = …`, `password=…` — the value after any+ // secret-named field, however it is punctuated.+ (+ pattern: RegExp(+ '''(["']?\\b\\w*(?:token|secret|password|passphrase|credential|api[_-]?key)\\w*\\b["']?\\s*[:=]\\s*["']?)([^\\s"',}]{6,})''',+ caseSensitive: false,+ ),+ replace: (m) => '${m[1]}<redacted>',+ ),+ // A `?…token=…` or `?…key=…` inside a logged URL.+ (+ pattern: RegExp(+ r'([?&][^=\s&]*(?:token|key|secret|sig|signature)[^=\s&]*=)[^\s&]+',+ caseSensitive: false,+ ),+ replace: (m) => '${m[1]}<redacted>',+ ),+];diff --git a/mobile/lib/main.dart b/mobile/lib/main.dartindex 8777d2e18..28aca1284 100644--- a/mobile/lib/main.dart+++ b/mobile/lib/main.dart@@ -1,6 +1,4 @@-import 'package:harness/app_shell.dart';-import 'package:harness/core/asset_owner.dart';-+import 'app_shell.dart';import 'p2p/phone_terminal_p2p.dart';import 'phone/phone_shell.dart';@@ -9,25 +7,20 @@ import 'phone/phone_shell.dart';////// Everything before the first frame — file logs, the crash log, the keyboard/// config, the saved appearance — and every screen up to sign-in comes from-/// [startHarness] in `package:harness`, the same code the desktop app runs.-/// This package adds only what a phone needs that a window does not: the shell-/// in `lib/phone/`.+/// [startHarness] in `app_shell.dart`. This package owns all of it: the app it+/// runs lives under `lib/`, with no dependency on any other package in this+/// repo. `lib/phone/` is what a phone needs that a window does not.////// The app has no harness CLI beside it, so it is a VIEWER build: it holds its/// own SSO session and terminates the end-to-end encryption to each machine-/// itself (`kViewerMode`, and `viewer/` in `package:harness`). That is decided-/// by the platform, not here — a Mac can run the same path with+/// itself (`kViewerMode`, and `lib/viewer/`). That is decided by the platform,+/// not here — a Mac running this package can take the same path with/// `--dart-define=HARNESS_VIEWER_MODE=true`.////// It also brings its own second wire to each machine: the WebRTC data channel/// the harness CLI opens on the desktop's behalf (`lib/p2p/`), so a terminal/// rides p2p or TURN when it can and the relay only when it must.-Future<void> main() {- // `harness` is a dependency here rather than the root package, so Flutter- // registers its assets under `packages/harness/…`. Set before the first frame.- harnessAssetPackage = 'harness';- return startHarness(- authenticatedScreen: (app) => PhoneShell(notifier: app),- transportPlugins: phoneTerminalP2p.create,- );-}+Future<void> main() => startHarness(+ authenticatedScreen: (app) => PhoneShell(notifier: app),+ transportPlugins: phoneTerminalP2p.create,+);diff --git a/mobile/lib/p2p/terminal_p2p_plugin.dart b/mobile/lib/p2p/terminal_p2p_plugin.dartindex 8f99bc572..74f33de1b 100644--- a/mobile/lib/p2p/terminal_p2p_plugin.dart+++ b/mobile/lib/p2p/terminal_p2p_plugin.dart@@ -2,9 +2,9 @@ import 'dart:async';import 'dart:convert';import 'dart:typed_data';-import 'package:harness/logging/app_log.dart';-import 'package:harness/terminal/terminal_binary.dart';-import 'package:harness/ws/terminal_transport_plugin.dart';+import 'package:harness_mobile/logging/app_log.dart';+import 'package:harness_mobile/terminal/terminal_binary.dart';+import 'package:harness_mobile/ws/terminal_transport_plugin.dart';import 'terminal_p2p_link.dart';import 'terminal_p2p_policy.dart';diff --git a/mobile/lib/p2p/webrtc_terminal_p2p_link.dart b/mobile/lib/p2p/webrtc_terminal_p2p_link.dartindex f48ff66a3..86e840dff 100644--- a/mobile/lib/p2p/webrtc_terminal_p2p_link.dart+++ b/mobile/lib/p2p/webrtc_terminal_p2p_link.dart@@ -4,7 +4,7 @@ import 'dart:typed_data';import 'package:flutter/foundation.dart' show visibleForTesting;import 'package:flutter_webrtc/flutter_webrtc.dart';-import 'package:harness/logging/app_log.dart';+import 'package:harness_mobile/logging/app_log.dart';import 'terminal_p2p_link.dart';import 'terminal_p2p_policy.dart';diff --git a/mobile/lib/phone/account_button.dart b/mobile/lib/phone/account_button.dartindex 425008e10..e670a8227 100644--- a/mobile/lib/phone/account_button.dart+++ b/mobile/lib/phone/account_button.dart@@ -2,8 +2,8 @@ import 'dart:async';import 'package:flutter/material.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/state/app_state.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/state/app_state.dart';/// Who is signed in, as a round initial in the corner of the machine list — and, on a tap, the/// one account action a viewer has: signing out.diff --git a/mobile/lib/phone/agent_index.dart b/mobile/lib/phone/agent_index.dartindex b1f6f47e6..a18695bda 100644--- a/mobile/lib/phone/agent_index.dart+++ b/mobile/lib/phone/agent_index.dart@@ -1,5 +1,5 @@-import 'package:harness/core/models.dart';-import 'package:harness/state/app_state.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/state/app_state.dart';import 'phone_status.dart';/// One agent, together with the machine it runs on.diff --git a/mobile/lib/phone/agent_row.dart b/mobile/lib/phone/agent_row.dartindex 0c68bad90..1984995bb 100644--- a/mobile/lib/phone/agent_row.dart+++ b/mobile/lib/phone/agent_row.dart@@ -1,8 +1,8 @@import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/widgets/engine_identity.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/widgets/engine_identity.dart';import 'agent_index.dart';import 'phone_card.dart';import 'status_pill.dart';diff --git a/mobile/lib/phone/agent_swipe.dart b/mobile/lib/phone/agent_swipe.dartindex 82921b3b9..bf65f9903 100644--- a/mobile/lib/phone/agent_swipe.dart+++ b/mobile/lib/phone/agent_swipe.dart@@ -2,7 +2,7 @@ import 'dart:async';import 'package:flutter/material.dart';-import 'package:harness/state/app_state.dart';+import 'package:harness_mobile/state/app_state.dart';import 'agent_index.dart';import 'terminal_page.dart';diff --git a/mobile/lib/phone/agent_tile.dart b/mobile/lib/phone/agent_tile.dartindex 7c97566ea..71c1bcc56 100644--- a/mobile/lib/phone/agent_tile.dart+++ b/mobile/lib/phone/agent_tile.dart@@ -1,10 +1,10 @@import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/core/models.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/widgets/engine_identity.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/widgets/engine_identity.dart';import 'phone_card.dart';import 'phone_status.dart';diff --git a/mobile/lib/phone/agents_page.dart b/mobile/lib/phone/agents_page.dartindex 0f0bb5b25..317cccdd6 100644--- a/mobile/lib/phone/agents_page.dart+++ b/mobile/lib/phone/agents_page.dart@@ -3,11 +3,11 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/core/models.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/shared/widgets/app_icon_button.dart';-import 'package:harness/shared/widgets/empty_state.dart';-import 'package:harness/state/app_state.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/widgets/app_icon_button.dart';+import 'package:harness_mobile/shared/widgets/empty_state.dart';+import 'package:harness_mobile/state/app_state.dart';import 'agent_tile.dart';import 'link_page.dart';diff --git a/mobile/lib/phone/agents_tab.dart b/mobile/lib/phone/agents_tab.dartindex 2e06f3d8c..893031d30 100644--- a/mobile/lib/phone/agents_tab.dart+++ b/mobile/lib/phone/agents_tab.dart@@ -1,9 +1,9 @@import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/shared/widgets/empty_state.dart';-import 'package:harness/state/app_state.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/widgets/empty_state.dart';+import 'package:harness_mobile/state/app_state.dart';import 'agent_index.dart';import 'agent_row.dart';import 'account_button.dart';diff --git a/mobile/lib/phone/link_page.dart b/mobile/lib/phone/link_page.dartindex 38a4533ba..50c155288 100644--- a/mobile/lib/phone/link_page.dart+++ b/mobile/lib/phone/link_page.dart@@ -1,8 +1,8 @@import 'package:flutter/material.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/widgets/link_machine_screen.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/widgets/link_machine_screen.dart';import 'agents_page.dart';import 'phone_header.dart';import 'phone_navigation.dart';diff --git a/mobile/lib/phone/machine_filter_bar.dart b/mobile/lib/phone/machine_filter_bar.dartindex 3cd0b9e18..0016fd2ea 100644--- a/mobile/lib/phone/machine_filter_bar.dart+++ b/mobile/lib/phone/machine_filter_bar.dart@@ -1,7 +1,7 @@import 'package:flutter/material.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/state/app_state.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/state/app_state.dart';import 'phone_status.dart';import 'status_pill.dart';diff --git a/mobile/lib/phone/machine_tile.dart b/mobile/lib/phone/machine_tile.dartindex 810b81a6a..b7ba4f15b 100644--- a/mobile/lib/phone/machine_tile.dart+++ b/mobile/lib/phone/machine_tile.dart@@ -1,8 +1,8 @@import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/state/app_state.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/state/app_state.dart';import 'phone_card.dart';import 'phone_status.dart';import 'status_pill.dart';diff --git a/mobile/lib/phone/machines_tab.dart b/mobile/lib/phone/machines_tab.dartindex fc9b870ca..9d3e28d32 100644--- a/mobile/lib/phone/machines_tab.dart+++ b/mobile/lib/phone/machines_tab.dart@@ -1,9 +1,9 @@import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/shared/widgets/empty_state.dart';-import 'package:harness/state/app_state.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/widgets/empty_state.dart';+import 'package:harness_mobile/state/app_state.dart';import 'machine_tile.dart';import 'phone_card.dart';import 'phone_header.dart';diff --git a/mobile/lib/phone/new_agent_page.dart b/mobile/lib/phone/new_agent_page.dartindex 2e57356f8..f3e0b9479 100644--- a/mobile/lib/phone/new_agent_page.dart+++ b/mobile/lib/phone/new_agent_page.dart@@ -3,12 +3,12 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/core/codex_profiles.dart';-import 'package:harness/core/models.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/widgets/engine_identity.dart';-import 'package:harness/widgets/remote_folder_picker.dart';+import 'package:harness_mobile/core/codex_profiles.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/widgets/engine_identity.dart';+import 'package:harness_mobile/widgets/remote_folder_picker.dart';import 'phone_header.dart';import 'settings_row.dart';diff --git a/mobile/lib/phone/phone_card.dart b/mobile/lib/phone/phone_card.dartindex 69e2c5d04..83575b625 100644--- a/mobile/lib/phone/phone_card.dart+++ b/mobile/lib/phone/phone_card.dart@@ -1,7 +1,7 @@import 'package:flutter/material.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/shared/widgets/skeleton.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/widgets/skeleton.dart';/// The gap between two cards in a phone list.const double kPhoneCardGap = 10;diff --git a/mobile/lib/phone/phone_header.dart b/mobile/lib/phone/phone_header.dartindex 3a2f92f6f..86cd2d983 100644--- a/mobile/lib/phone/phone_header.dart+++ b/mobile/lib/phone/phone_header.dart@@ -1,8 +1,8 @@import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/shared/widgets/app_icon_button.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/widgets/app_icon_button.dart';/// The top of a phone page, drawn below the status bar and the Dynamic Island rather than into/// them — the desktop chrome only ever had traffic lights to clear.diff --git a/mobile/lib/phone/phone_layout.dart b/mobile/lib/phone/phone_layout.dartindex 4f255e6d6..2061482bb 100644--- a/mobile/lib/phone/phone_layout.dart+++ b/mobile/lib/phone/phone_layout.dart@@ -1,7 +1,7 @@import 'package:flutter/widgets.dart';-import 'package:harness/core/viewer_mode.dart';-import 'package:harness/shared/layouts/window_size.dart';+import 'package:harness_mobile/core/viewer_mode.dart';+import 'package:harness_mobile/shared/layouts/window_size.dart';/// The shortest side under which a viewer draws its phone layout — the shell's own compact/// breakpoint, so an iPad keeps the rail beside its terminals.diff --git a/mobile/lib/phone/phone_navigation.dart b/mobile/lib/phone/phone_navigation.dartindex 8db5145ba..66acab612 100644--- a/mobile/lib/phone/phone_navigation.dart+++ b/mobile/lib/phone/phone_navigation.dart@@ -2,7 +2,7 @@ import 'dart:async';import 'package:flutter/cupertino.dart';-import 'package:harness/state/app_state.dart';+import 'package:harness_mobile/state/app_state.dart';import 'agent_index.dart';import 'agent_swipe.dart';import 'agents_page.dart';diff --git a/mobile/lib/phone/phone_sheet.dart b/mobile/lib/phone/phone_sheet.dartindex 92a06cdb5..be605148d 100644--- a/mobile/lib/phone/phone_sheet.dart+++ b/mobile/lib/phone/phone_sheet.dart@@ -1,6 +1,6 @@import 'package:flutter/material.dart';-import 'package:harness/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';/// One action in a phone sheet.class PhoneSheetAction {diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dartindex a57a5f69a..05e43abd5 100644--- a/mobile/lib/phone/phone_shell.dart+++ b/mobile/lib/phone/phone_shell.dart@@ -1,6 +1,6 @@import 'package:flutter/material.dart';-import 'package:harness/state/app_state.dart';+import 'package:harness_mobile/state/app_state.dart';import '../p2p/phone_terminal_p2p.dart';import 'agent_index.dart';diff --git a/mobile/lib/phone/phone_status.dart b/mobile/lib/phone/phone_status.dartindex de61dc01b..96a169065 100644--- a/mobile/lib/phone/phone_status.dart+++ b/mobile/lib/phone/phone_status.dart@@ -1,6 +1,6 @@-import 'package:harness/core/models.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/terminal/terminal_session.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';/// How a phone status line is coloured. The widgets turn this into a palette colour, so the/// rules below stay testable without a theme.diff --git a/mobile/lib/phone/phone_tab_bar.dart b/mobile/lib/phone/phone_tab_bar.dartindex c9761a7d4..2f99f7bb9 100644--- a/mobile/lib/phone/phone_tab_bar.dart+++ b/mobile/lib/phone/phone_tab_bar.dart@@ -1,7 +1,7 @@import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';/// The three places a phone can be. Agents first: it is where the app opens and the only tab with/// anything to act on.diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dartindex f98d3b4b2..df13bafe9 100644--- a/mobile/lib/phone/settings_page.dart+++ b/mobile/lib/phone/settings_page.dart@@ -3,11 +3,11 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/core/app_version.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/shared/theme/appearance_prefs_store.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/terminal/terminal_font_store.dart';+import 'package:harness_mobile/core/app_version.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/appearance_prefs_store.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/terminal/terminal_font_store.dart';import 'phone_header.dart';import 'phone_sheet.dart';import 'settings_row.dart';diff --git a/mobile/lib/phone/settings_row.dart b/mobile/lib/phone/settings_row.dartindex 841614d6f..72709a506 100644--- a/mobile/lib/phone/settings_row.dart+++ b/mobile/lib/phone/settings_row.dart@@ -1,7 +1,7 @@import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';/// The pieces a phone settings list is built from — the grouped inset list every phone OS uses,/// rather than the desktop's `SettingRow` (a raised block with a fixed-width control on the right,diff --git a/mobile/lib/phone/status_pill.dart b/mobile/lib/phone/status_pill.dartindex 0f1c870c6..54e128de2 100644--- a/mobile/lib/phone/status_pill.dart+++ b/mobile/lib/phone/status_pill.dart@@ -1,6 +1,6 @@import 'package:flutter/material.dart';-import 'package:harness/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';import 'phone_status.dart';/// The palette colour a [PhoneTone] draws in.diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dartindex f4637ee59..91fccda4c 100644--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@ -3,12 +3,12 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/shared/widgets/app_icon_button.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/widgets/engine_identity.dart';-import 'package:harness/widgets/rename_agent_dialog.dart';-import 'package:harness/widgets/terminal_panel.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/widgets/app_icon_button.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/widgets/engine_identity.dart';+import 'package:harness_mobile/widgets/rename_agent_dialog.dart';+import 'package:harness_mobile/widgets/terminal_panel.dart';import 'phone_header.dart';import 'phone_sheet.dart';diff --git a/mobile/lib/screens/login_screen.dart b/mobile/lib/screens/login_screen.dartnew file mode 100644index 000000000..5f930754b--- /dev/null+++ b/mobile/lib/screens/login_screen.dart@@ -0,0 +1,420 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../state/app_state.dart';+import '../widgets/login_relay_diagram.dart';+import '../widgets/welcome_workspace_preview.dart';++/// The sign-in screen.+///+/// Lead with the work: real agents together in one workspace. A static+/// example explains a swarm before sign-in; the privacy guarantee stays in the+/// quiet footer. The preview never creates agents or sends them a task.+///+/// **All four states live here**, in one card, rather than the two screens this+/// used to be. Pressing Sign in swapped the whole window for+/// `AwaitingBrowserLoginScreen`, at a different type scale — a hard cut in the+/// middle of a flow, and the reason the button's own spinner was almost never+/// seen. The wait is now a state of the button, so the frame never jumps.+///+/// ⚠️ **The SSO page cannot be embedded, and that is not a preference.**+/// `auth.autonomous.ai`'s Google sign-in uses Google's popup-based Identity+/// Services flow — a real popup window that posts its result back to its+/// opener — which a single-window embedded webview cannot satisfy. The system+/// browser handles it natively, so `AppNotifier.login` launches it there and+/// this screen tracks the wait, returning on its own once+/// `harness login --force --json` reports success. (This note came from the screen+/// that used to own the waiting state; it is the reason the flow leaves the+/// app at all, so it outlives the widget it was written on.)+class LoginScreen extends StatelessWidget {+ final AppNotifier notifier;+ const LoginScreen({super.key, required this.notifier});++ /// Matches `EnvironmentSetupScreen` (560) and `LinkMachineScreen` (460) —+ /// wide enough for the diagram to breathe, still centred at the 880×560+ /// minimum window.+ static const double _cardWidth = 520;++ @override+ Widget build(BuildContext context) {+ // Law 4: a widget that reads a colour token watches, or it freezes on the+ // boot palette when the theme flips. This screen used to call it zero times.+ grid.AppTheme.watch(context);++ // The same flag `RootShell` routes on, so the button's state and the reason+ // this screen is on screen at all can never disagree.+ final waiting = notifier.signingIn;+ final compact = MediaQuery.sizeOf(context).height < 640;+ final gap = compact ? 16.0 : 24.0;++ return Scaffold(+ // The PANEL tone, not the window's. In light both `windowBg` and the+ // card's `surfaceFill` are pure white, so a card on the window is a card+ // you cannot see — only its shadow separates it, and at this size that+ // reads as a printing artefact rather than as a raised block. The rail's+ // own barely-there grey gives the card something to sit on in both+ // themes, which is the same trick the app plays everywhere else.+ backgroundColor: grid.AppPalette.panelBg,+ body: Stack(+ children: [+ const Positioned.fill(child: LoginAurora()),+ Center(+ child: SingleChildScrollView(+ padding: EdgeInsets.all(compact ? 16 : 24),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: _cardWidth),+ child: Container(+ // The app's raised-block recipe: fill plus a soft lift, no rim.+ decoration: BoxDecoration(+ color: grid.AppGlass.surfaceFill,+ borderRadius: BorderRadius.circular(14),+ boxShadow: grid.AppCard.shadow,+ ),+ padding: EdgeInsets.all(compact ? 20 : 24),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ const _AppMark(),+ SizedBox(height: gap),+ Text(+ 'All your harnesses, on one screen',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.titleLarge,+ ),+ const SizedBox(height: 8),+ Text(+ 'Work with Claude Code, Codex and other agents side by side. '+ 'Start with one harness and add panes as your work grows.',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodySmall,+ ),+ SizedBox(height: gap),+ const WelcomeWorkspacePreview(),+ SizedBox(height: gap),+ _Action(notifier: notifier, waiting: waiting),+ if (notifier.lastError != null) ...[+ const SizedBox(height: 16),+ _ErrorTile(+ message: notifier.lastError!,+ onRetry: notifier.login,+ ),+ ],+ SizedBox(height: gap),+ const _Seal(),+ ],+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}++/// The button, and what it becomes while the browser is open.+///+/// One widget for both because they are one control in two states: the label+/// changes, a spinner replaces the glyph, and Cancel appears beside it. Nothing+/// moves position, so the wait reads as *this button is working* rather than as+/// a new screen.+class _Action extends StatefulWidget {+ const _Action({required this.notifier, required this.waiting});++ final AppNotifier notifier;+ final bool waiting;++ @override+ State<_Action> createState() => _ActionState();+}++class _ActionState extends State<_Action> {+ AppNotifier get notifier => widget.notifier;+ final _signInFocus = FocusNode(debugLabel: 'Sign in');+ String? _copiedUrl;+ String? _copyFailureUrl;+ bool _copying = false;++ @override+ void didUpdateWidget(covariant _Action oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.waiting && !widget.waiting) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {+ _signInFocus.requestFocus();+ }+ });+ }+ }++ @override+ void dispose() {+ _signInFocus.dispose();+ super.dispose();+ }++ Future<void> _copyLink() async {+ final url = notifier.pendingAuthorizeUrl;+ if (url == null || !notifier.signingIn || _copying) return;+ setState(() => _copying = true);+ var copied = false;+ try {+ await Clipboard.setData(ClipboardData(text: url));+ copied = true;+ } catch (_) {+ // Keep recovery in the same sign-in if the OS clipboard is unavailable.+ }+ if (!mounted) return;+ setState(() {+ _copying = false;+ if (notifier.signingIn && notifier.pendingAuthorizeUrl == url) {+ _copiedUrl = copied ? url : null;+ _copyFailureUrl = copied ? null : url;+ }+ });+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);++ if (!widget.waiting) {+ return Column(+ children: [+ FilledButton.icon(+ focusNode: _signInFocus,+ autofocus: true,+ onPressed: notifier.login,+ icon: const Icon(Icons.login, size: grid.AppControl.iconSize),+ label: const Text('Sign in'),+ ),+ const SizedBox(height: 12),+ Text(+ 'Sign in through your browser to continue.',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodySmall,+ ),+ ],+ );+ }++ final url = notifier.pendingAuthorizeUrl;+ final message =+ notifier.loginBrowserError ??+ (url != null && _copyFailureUrl == url+ ? 'Couldn’t copy the link. Try opening your browser again.'+ : null);+ return Column(+ children: [+ FilledButton.icon(+ // Disabled, not hidden: the control the user just pressed has to stay+ // where they left it, saying what it is doing.+ onPressed: null,+ icon: const SizedBox(+ width: grid.AppControl.iconSize,+ height: grid.AppControl.iconSize,+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ label: Text(url == null ? 'Signing in…' : 'Waiting for your browser'),+ ),+ const SizedBox(height: 12),+ Semantics(+ liveRegion: true,+ child: Text(+ message ??+ (url == null+ ? 'Your workspace will open when sign-in is complete.'+ : 'Finish signing in in your browser, then return here.'),+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodySmall,+ ),+ ),+ if (url != null || notifier.canCancelLogin) ...[+ const SizedBox(height: 12),+ Wrap(+ spacing: 8,+ runSpacing: 8,+ alignment: WrapAlignment.center,+ children: [+ if (url != null) ...[+ OutlinedButton.icon(+ onPressed: notifier.openingLoginBrowser+ ? null+ : notifier.openLoginBrowser,+ icon: const Icon(Icons.open_in_new, size: 16),+ label: Text(+ notifier.openingLoginBrowser+ ? 'Opening browser…'+ : 'Open browser',+ ),+ ),+ TextButton.icon(+ onPressed: _copying ? null : _copyLink,+ icon: Icon(+ _copiedUrl == url ? Icons.check : Icons.content_copy,+ size: 16,+ ),+ label: Semantics(+ liveRegion: true,+ child: Text(+ _copiedUrl == url ? 'Link copied' : 'Copy link',+ ),+ ),+ ),+ ],+ if (notifier.canCancelLogin)+ TextButton(+ autofocus: true,+ onPressed: notifier.cancelLogin,+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ ),+ child: const Text('Cancel'),+ ),+ ],+ ),+ ],+ ],+ );+ }+}++/// A failure the user can act on.+///+/// The old screen printed the raw error in `Colors.red` with no container and+/// no way forward. Two things changed: the colour is a token that resolves per+/// theme, and there is a retry — the house rule is that every empty, loading+/// and error state offers a way on.+class _ErrorTile extends StatelessWidget {+ const _ErrorTile({required this.message, required this.onRetry});++ final String message;+ final VoidCallback onRetry;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ // Error INK on a surface, not `dangerFill`, which is tuned to carry white+ // lettering on top of it and is far too dark to read *as* text.+ final danger = grid.AppTheme.pick(+ const Color(0xFFB3261E),+ const Color(0xFFF2544B),+ );++ return Container(+ width: double.infinity,+ decoration: BoxDecoration(+ color: grid.AppCard.inset,+ // Radius 8 inside a 14 card — a child is never rounder than its parent.+ borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),+ ),+ padding: const EdgeInsets.all(16),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Icon(Icons.error_outline, size: 16, color: danger),+ const SizedBox(width: 8),+ Expanded(+ child: Text(+ 'Could not sign in',+ style: Theme.of(context).textTheme.labelMedium+ ?.copyWith(color: danger),+ ),+ ),+ ],+ ),+ const SizedBox(height: 4),+ SelectableText(message, style: Theme.of(context).textTheme.bodySmall),+ const SizedBox(height: 12),+ Align(+ alignment: Alignment.centerLeft,+ child: OutlinedButton(+ onPressed: onRetry,+ child: const Text('Try again'),+ ),+ ),+ ],+ ),+ );+ }+}++/// The quiet line at the foot of the card.+///+/// It says the guarantee in words anyone has — the cipher names that used to+/// sit here (`Ed25519 · ChaCha20-Poly1305`) were true, and unreadable to almost+/// everyone who saw them; they belong on a security page, not on the one screen+/// standing between someone and their work.+class _Seal extends StatelessWidget {+ const _Seal();++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Column(+ children: [+ Divider(height: 1, color: grid.AppPalette.divider),+ const SizedBox(height: 16),+ Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Icon(Icons.lock_outline, size: 13, color: grid.AppPalette.teal),+ const SizedBox(width: 8),+ Text(+ 'End-to-end encrypted',+ style: Theme.of(context).textTheme.labelSmall+ ?.copyWith(color: grid.AppPalette.textFaint),+ ),+ ],+ ),+ ],+ );+ }+}++/// The app icon, on a recess that gives it somewhere to stand.+///+/// The asset is the Dock icon: an amber mark on its own charcoal tile. At 40px+/// on this card that tile composites into the card behind it — they are within+/// a few points of the same grey — so the tile disappears and what is left is a+/// bare amber shape floating in the middle of an indigo-and-teal screen. It+/// read as a warning badge rather than as a logo, and it took the eye before+/// the headline did.+///+/// The fix is not to recolour the brand. It is to give the mark the ground it+/// was drawn to sit on: [grid.AppCard.inset] is a step *darker* than the card+/// in dark and a step warmer-grey in light, so the tile has an edge again in+/// both themes. The amber then reads as deliberate — the one warm thing on the+/// screen, contained — instead of as a sticker someone left on.+class _AppMark extends StatelessWidget {+ const _AppMark();++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Container(+ width: 56,+ height: 56,+ decoration: BoxDecoration(+ color: grid.AppCard.inset,+ // Radius 12 inside the card's 14 — a child is never rounder than its+ // parent, and the asset's own corners are rounder still inside this.+ borderRadius: BorderRadius.circular(12),+ ),+ alignment: Alignment.center,+ // No ClipRRect: the asset carries its own rounded corners, and clipping+ // would cut the edge twice. Same reason About renders it bare.+ child: Image.asset(+ 'assets/app_icon.png',+ width: 36,+ height: 36,+ filterQuality: FilterQuality.medium,+ ),+ );+ }+}diff --git a/mobile/lib/settings/config_store.dart b/mobile/lib/settings/config_store.dartnew file mode 100644index 000000000..722b7f680--- /dev/null+++ b/mobile/lib/settings/config_store.dart@@ -0,0 +1,78 @@+import '../core/config.dart';+import '../core/harness_file_store.dart';+import '../core/local_key_value_store.dart';++/// Persists user-configurable connection settings in the Harness home file.+class ConfigStore {+ final LocalKeyValueStore _storage;+ static const _baseUrlKey = 'app_api_base_url';+ static const _environmentKey = 'app_autonomous_environment';+ static const _skippedDesktopUpdateVersionKey =+ 'skipped_desktop_update_version';+ // No longer read or written: live pre-flight runs on every launch. Kept only+ // so Reset can clean state written by older desktop builds.+ static const _legacyEnvironmentSetupVersionKey = 'environment_setup_version';+ static const String defaultBaseUrl = 'https://harness-api.autonomous.ai';++ ConfigStore({LocalKeyValueStore? storage})+ : _storage = storage ?? HarnessFileStore.shared;++ AppConfig get config => AppConfig(+ apiBaseUrl: _cachedBaseUrl ?? defaultBaseUrl,+ autonomousEnv: _cachedEnvironment ?? 'prod',+ );+ String? _cachedBaseUrl;+ String? _cachedEnvironment;+ String? _cachedSkippedDesktopUpdateVersion;++ String? get skippedDesktopUpdateVersion => _cachedSkippedDesktopUpdateVersion;++ Future<AppConfig> load() async {+ // Keep the tiny startup path sequential and predictable.+ final baseUrl = await _storage.read(_baseUrlKey);+ final environment = await _storage.read(_environmentKey);+ final skippedUpdate = await _storage.read(_skippedDesktopUpdateVersionKey);+ _cachedBaseUrl = baseUrl ?? defaultBaseUrl;+ _cachedEnvironment = environment == 'stag' ? 'stag' : 'prod';+ _cachedSkippedDesktopUpdateVersion = skippedUpdate?.trim().isEmpty ?? true+ ? null+ : skippedUpdate!.trim();+ return config;+ }++ Future<void> save(String baseUrl) async {+ _cachedBaseUrl = baseUrl;+ await _storage.write(_baseUrlKey, baseUrl);+ }++ Future<void> saveEnvironment(String autonomousEnv) async {+ _cachedEnvironment = autonomousEnv == 'stag' ? 'stag' : 'prod';+ await _storage.write(_environmentKey, _cachedEnvironment!);+ }++ Future<void> saveSkippedDesktopUpdateVersion(String? version) async {+ final normalized = version?.trim();+ _cachedSkippedDesktopUpdateVersion =+ normalized == null || normalized.isEmpty ? null : normalized;+ if (_cachedSkippedDesktopUpdateVersion == null) {+ await _storage.delete(_skippedDesktopUpdateVersionKey);+ } else {+ await _storage.write(+ _skippedDesktopUpdateVersionKey,+ _cachedSkippedDesktopUpdateVersion!,+ );+ }+ }++ Future<void> reset() async {+ _cachedBaseUrl = null;+ _cachedEnvironment = null;+ _cachedSkippedDesktopUpdateVersion = null;+ await Future.wait([+ _storage.delete(_baseUrlKey),+ _storage.delete(_environmentKey),+ _storage.delete(_skippedDesktopUpdateVersionKey),+ _storage.delete(_legacyEnvironmentSetupVersionKey),+ ]);+ }+}diff --git a/mobile/lib/shared/layouts/window_size.dart b/mobile/lib/shared/layouts/window_size.dartnew file mode 100644index 000000000..33bb29101--- /dev/null+++ b/mobile/lib/shared/layouts/window_size.dart@@ -0,0 +1,49 @@+import 'package:flutter/widgets.dart';++/// The width bands the shell branches on.+///+/// One definition, in one place, so "narrow" means the same number to every+/// piece of chrome rather than each one inventing its own threshold.+///+/// These are WINDOW widths, not device classes. A desktop window dragged down+/// to 500pt is [compact] for the same reason a phone is, and is laid out the+/// same way — there is no separate mobile build to branch on, and a rule that+/// asked "is this a phone?" would leave the narrow desktop window broken.+///+/// The lower edge is Material's 600. The upper one is this app's own: the pane+/// grid's floor for a usable terminal tile is about 336pt (`_MinTile` in+/// `widgets/pane_grid.dart`, 40 columns at the default font), and [expanded]+/// is meant to mean "two of those side by side, with the chrome around them" —+/// which 840 does not buy and 1024 does.+enum WindowSizeClass {+ /// One thing at a time. Chrome that cannot earn its width collapses.+ compact,++ /// Everything is present, with less room around it.+ medium,++ /// The size the app is drawn for.+ expanded;++ /// First width that is no longer [compact].+ static const double compactMax = 600;++ /// First width that is [expanded].+ static const double mediumMax = 1024;++ static WindowSizeClass fromWidth(double width) => switch (width) {+ < compactMax => WindowSizeClass.compact,+ < mediumMax => WindowSizeClass.medium,+ _ => WindowSizeClass.expanded,+ };++ /// The class of the WINDOW.+ ///+ /// Prefer [fromWidth] with a `LayoutBuilder`'s own constraint for anything+ /// laid out narrower than the window: a strip inside a split should answer+ /// for the box it was given, not for the screen it happens to sit on.+ static WindowSizeClass of(BuildContext context) =>+ fromWidth(MediaQuery.sizeOf(context).width);++ bool get isCompact => this == WindowSizeClass.compact;+}diff --git a/mobile/lib/shared/theme/app_theme.dart b/mobile/lib/shared/theme/app_theme.dartnew file mode 100644index 000000000..717912e70--- /dev/null+++ b/mobile/lib/shared/theme/app_theme.dart@@ -0,0 +1,1851 @@+import '../../core/apple_fonts.dart';++import 'package:flutter/material.dart';++import 'color_palette.dart';++/// The app's live brightness — the single source of truth the color tokens below+/// resolve against. Harness Desktop is dark-only: `_GridTokenScope` (in+/// `main.dart`) pins this to [Brightness.dark] once, at the top of the tree.+///+/// Every `AppPalette`/`AppSurface`/`AppGlass`/`AppCard` member is a getter that+/// switches on this, so a call site like `color: AppPalette.windowBg` follows the+/// theme with no change to the call site.+abstract final class AppTheme {+ static final BrightnessNotifier brightness = BrightnessNotifier(+ Brightness.dark,+ );++ /// Fires when the user's type settings change. Separate from [brightness]+ /// because the two are independent — a theme flip must not restyle type, and+ /// changing the font must not repaint as though the palette moved — but read+ /// through the same [watch], since a widget that reads one token generally+ /// reads both.+ static final FontNotifier fonts = FontNotifier();+ static final palette = ValueNotifier(HarnessPalette.graphite);++ static bool get isDark => brightness.value == Brightness.dark;++ /// Pick between a light and a dark value for the current brightness.+ static T pick<T>(T light, T dark) => isDark ? dark : light;++ /// Read tokens as some *other* brightness would resolve them.+ ///+ /// The tokens resolve against one global ([brightness]), which is what makes a+ /// call site like `AppPalette.windowBg` follow the theme with no plumbing — but+ /// it also means the dark palette is unreadable while the app is light. The+ /// theme preview needs exactly that: three swatches, each showing a palette the+ /// app is *not* currently wearing.+ ///+ /// So: swap the global, read, put it back. Safe because it's synchronous and+ /// restores in a `finally` — nothing can observe the swapped value, and the+ /// swap is [BrightnessNotifier.muted] so it doesn't dirty every widget+ /// watching the theme on the way out and back.+ ///+ /// Do not `await` inside [read]: that would hand the swapped brightness to the+ /// rest of the frame, and the app would paint half a palette.+ static T as<T>(Brightness other, T Function() read) {+ final previous = brightness.value;+ if (previous == other) return read();+ return brightness.muted(() {+ try {+ brightness.value = other;+ return read();+ } finally {+ brightness.value = previous;+ }+ });+ }++ /// Registers the calling widget to rebuild whenever [brightness] flips, and+ /// returns the current value.+ ///+ /// The color tokens read [brightness] `.value` directly — a plain field read+ /// the element tree can't see — so a widget that only reads tokens has no+ /// tracked reason to rebuild when the theme changes. Worse, the app is full of+ /// `const` chrome (`const AppSidebar()`, `const _MainShellBody()`), and a+ /// `const` child is reference-identical across a parent's rebuild, so Flutter+ /// short-circuits it: rebuilding from the top never reaches the sidebar, and it+ /// stays on the old palette until something *else* (a Riverpod change from+ /// clicking a row) happens to rebuild it.+ ///+ /// Calling this at the top of a chrome widget's `build` fixes that at the root:+ /// it depends on the [_BrightnessScope] inherited widget, whose notifier is+ /// [brightness]. An `InheritedNotifier` marks its dependents dirty *directly*+ /// when the notifier fires — it doesn't rebuild through the widget tree — so+ /// every `const` boundary in between is irrelevant. This is exactly how+ /// `Theme.of(context)` makes a widget follow the theme.+ /// It also registers for type changes, via [_FontScope]. The two travel+ /// together deliberately: `AppTheme.watch(context)` is the one line a widget+ /// adds to follow the app's appearance, and splitting it into two calls would+ /// mean every widget that already follows the theme still silently ignores the+ /// font — with the exact same symptom (stuck on the value it first built with)+ /// that this method exists to fix.+ static Brightness watch(BuildContext context) {+ context.dependOnInheritedWidgetOfExactType<_BrightnessScope>();+ context.dependOnInheritedWidgetOfExactType<_FontScope>();+ context.dependOnInheritedWidgetOfExactType<_PaletteScope>();+ return brightness.value;+ }+}++/// Fires when [AppFont]'s user settings change.+///+/// It carries no value: the settings live on [AppFont] as statics, because a+/// token read like `AppFont.mono` has no context to look one up with. This is+/// only the signal that they moved.+class FontNotifier extends ChangeNotifier {+ /// Push new settings onto [AppFont] and notify, but only if they differ —+ /// setting the same font twice must not dirty the tree.+ void apply({+ String? uiFamily,+ String? codeFamily,+ required double uiScale,+ required double codeSize,+ }) {+ final changed = AppFont.apply(+ uiFamily: uiFamily,+ codeFamily: codeFamily,+ uiScale: uiScale,+ codeSize: codeSize,+ );+ if (changed) notifyListeners();+ }+}++/// The brightness global, with one extra power: it can be moved *silently*.+///+/// [AppTheme.as] swaps the brightness to read the other palette and swaps it+/// straight back. A plain `ValueNotifier` broadcasts both of those moves, so+/// every widget watching the theme would be marked dirty twice per swatch — six+/// spurious rebuilds to draw three previews, all to end up back where we+/// started. [muted] suppresses the broadcast for a change that is, from the+/// outside, not a change at all.+class BrightnessNotifier extends ValueNotifier<Brightness> {+ BrightnessNotifier(super.value);++ bool _muted = false;++ /// Run [body] with notifications suppressed. Only for a swap that restores the+ /// original value before anything can observe it — see [AppTheme.as].+ T muted<T>(T Function() body) {+ final previous = _muted;+ _muted = true;+ try {+ return body();+ } finally {+ _muted = previous;+ }+ }++ @override+ void notifyListeners() {+ if (_muted) return;+ super.notifyListeners();+ }+}++/// Wraps the app so any descendant that calls [AppTheme.watch] rebuilds when the+/// brightness flips or the user's type settings change — regardless of the+/// `const` widgets in between. Mount it once, high in the tree (see+/// `grid_app.dart`).+///+/// The name predates the font settings and is kept: it's mounted in one place,+/// and every call site in the app already knows this as the widget that makes+/// [AppTheme.watch] work.+class BrightnessScope extends StatelessWidget {+ const BrightnessScope({super.key, required this.child});++ final Widget child;++ @override+ Widget build(BuildContext context) {+ return _BrightnessScope(+ notifier: AppTheme.brightness,+ child: _FontScope(+ notifier: AppTheme.fonts,+ child: _PaletteScope(notifier: AppTheme.palette, child: child),+ ),+ );+ }+}++class _BrightnessScope extends InheritedNotifier<ValueNotifier<Brightness>> {+ const _BrightnessScope({required super.notifier, required super.child});+}++class _FontScope extends InheritedNotifier<FontNotifier> {+ const _FontScope({required super.notifier, required super.child});+}++class _PaletteScope extends InheritedNotifier<ValueNotifier<HarnessPalette>> {+ const _PaletteScope({required super.notifier, required super.child});+}++/// The app's palette — a warm paper white with near-black ink in light, a deep+/// charcoal with off-white ink in dark (the design-system "Codex" direction).+/// Centralized so every pane reads the same surfaces/accents instead of re-typing+/// hex literals, and resolves per [AppTheme.brightness].+abstract final class AppPalette {+ // Approved Swarms canvas and native tab-strip palette.+ static Color get swarmField => AppTheme.palette.value.workspace;+ static Color get swarmTabBar => AppTheme.palette.value.tabBar;+ static Color get swarmAccent => AppTheme.palette.value.accent;+ // Shared with the native search field for a continuous input/results surface.+ static Color get swarmSearchSurface => AppTheme.palette.value.search;++ // the conversation / content area — pure white in light, like Codex.+ //+ // Dark is a charcoal page rather than the near-black it was (#0A0A0A). That+ // moves every surface above it closer: a card lands at 1.065:1 where it had+ // 1.188, a dialog at 1.090 where it had 1.215, and [AppPalette.panelBg]+ // (#141414) is now *darker* than the page it sits on. Depth in dark is+ // therefore carried by the rim and the shadow, not by the fill — §2's stack+ // still holds, it just has less room to say it in.+ static Color get windowBg =>+ AppTheme.pick(const Color(0xFFFFFFFF), AppTheme.palette.value.background);++ // sidebar column — a barely-there cool grey (Codex keeps the rail almost white,+ // set apart by a hairline, not a tone) / charcoal panel in dark.+ static Color get panelBg =>+ AppTheme.pick(const Color(0xFFF9F9F8), AppTheme.palette.value.panel);++ // input fills, quiet cards+ static Color get cardBg =>+ AppTheme.pick(const Color(0xFFF3F3F2), AppTheme.palette.value.card);++ static Color get cardBgHover =>+ AppTheme.pick(const Color(0xFFECECEA), AppTheme.palette.value.hover);++ // A hairline separator. Light: a faint cool black; dark: a faint white — a+ // black divider would vanish on charcoal.+ static Color get divider =>+ AppTheme.pick(const Color(0x0F000000), const Color(0x14FFFFFF));++ /// A hairline that has to hold a *shape* rather than just part two blocks —+ /// the tree guide threading the sidebar's projects and their chats.+ ///+ /// Stronger than [divider], and deliberately so. A separator only has to be+ /// findable at the seam the eye is already looking at; a guide is a long thin+ /// run the eye has to follow, and at the divider's weight it stops reading as+ /// one line and breaks into stray ticks wherever anything crosses it.+ /// Measured against the rail it is drawn on (`AppGlass.sidebarFill`, over+ /// [windowBg] in light): divider lands at **1.14:1 light / 1.27:1 dark**,+ /// this at **1.45:1 light / 1.47:1 dark**.+ ///+ /// The two alphas differ because the rails differ — `#F9F9F8` light against+ /// `#242424` dark — and matching the *numbers* rather than the alphas is what+ /// keeps the guide equally present in both themes instead of a step fainter+ /// in light, which is how the divider's pair behaved.+ static Color get guide =>+ AppTheme.pick(const Color(0x29000000), const Color(0x20FFFFFF));++ // primary action — a solid fill with white text on it, so it has to stay dark+ // enough to carry that text (white on this is 5.5:1). Same value in both+ // themes: as a *fill* it reads on either surface.+ static const accent = Color(0xFF2F5BEA);++ /// The fill under a destructive **filled** button — Remove, Delete.+ ///+ /// Not `colorScheme.error`, and the reason is what that colour is *for*: dark's+ /// `#F2544B` is tuned to read as **ink on a dark surface**, which is why+ /// `AppIconButton` needs one lighter still. As a *fill* it leaves white+ /// lettering at 3.42:1, under the 4.5:1 floor — and Material's own `onError`+ /// substitute reaches only 3.83:1, so no foreground rescues it. Darkened until+ /// white clears the bar with the room the app's own accent button already has:+ ///+ /// ```+ /// white on fill fill vs dialog+ /// accent #2F5BEA 5.52 3.02+ /// this #C92E26 (dark) 5.38 3.10+ /// this #B3261E (light) 6.54 6.54+ /// ```+ static Color get dangerFill =>+ AppTheme.pick(const Color(0xFFB3261E), const Color(0xFFC92E26));++ /// The accent as a *mark on a surface* — a selected row's icon, an accent+ /// rail — rather than a fill behind white text.+ ///+ /// It has to part from [accent] in dark. A selected rail row composites to+ /// #353535, and #2F5BEA on that is 2.2:1 — under the 3.0 WCAG 1.4.11 asks of+ /// a UI element, which is why the selected icon read as flat charcoal-on-+ /// charcoal there while light (4.6:1) was fine. Lightened to 3.97:1 on that+ /// row, still plainly the same indigo. [accent] can't simply take this value:+ /// it is the fill under white text in ~100 places, and lightening it there+ /// would drop that text to ~3.1:1 — fixing the icon by breaking the buttons.+ static Color get accentOnSurface =>+ AppTheme.pick(const Color(0xFF2F5BEA), AppTheme.palette.value.accent);++ // avatar fill (white text on it); a touch brighter in dark for contrast.+ static Color get accentMuted =>+ AppTheme.pick(const Color(0xFF3550C8), const Color(0xFF4E6BF0));++ /// The initial tile beside a name in a roster — the accent's hue with most of+ /// its saturation taken out, so a column of ten of them reads as a list rather+ /// than as ten buttons.+ ///+ /// **Not [accent] or [accentMuted].** Both are made to be *loud*: one is the+ /// fill under a primary button, the other the base of the account avatar that+ /// marks **you**. A saturated indigo is right for one mark on a screen and+ /// wrong for a mark on every row — a whole panel of them pulled the eye off+ /// the names they were meant to introduce.+ ///+ /// Still a solid fill under white text, and still measured for it: 5.26:1 in+ /// light, 6.19:1 in dark. Softening a mark must not cost the letter inside it,+ /// which is the only part carrying information — a tint at 14% alpha would+ /// have taken the glyph to 4.5:1 at rest and under it on a hovered row.+ ///+ /// Slightly deeper in dark, where the tile stands on charcoal (2.63:1 against+ /// the panel) rather than on white (5.26:1).+ static Color get avatarFill =>+ AppTheme.pick(const Color(0xFF5369AC), const Color(0xFF4B5F9B));++ /// The colours a member's circle is drawn in, one per person — see+ /// `memberAvatarSlot`, which decides which of them an address takes.+ ///+ /// **The same list in both themes, deliberately.** Every other colour here+ /// resolves per brightness; this one must not, because here the colour *is*+ /// the identity. A person who is teal on the dark theme and green on the light+ /// one is two people to the eye, and the whole reason for colouring a roster+ /// is that a face can be found before it is read.+ ///+ /// Eight hues rather than a generated spread: a hash over a continuous wheel+ /// puts neighbouring people two degrees apart as often as not, and a palette+ /// picked by hand is the only way the marks stay *told apart*. All eight carry+ /// white at ≥5:1 (measured: 5.02 green → 7.10 violet), which is what the+ /// letter needs — the disc itself is a container, and lands at 2.3–3.5:1+ /// against the panels it sits on, the same band [avatarFill] occupies today.+ static const avatarPalette = <Color>[+ Color(0xFF1D5BD6), // blue+ Color(0xFF0F766E), // teal+ Color(0xFF15803D), // green+ Color(0xFFA65A08), // amber+ Color(0xFFBE123C), // rose+ Color(0xFF6D28D9), // violet+ Color(0xFFA21CAF), // fuchsia+ Color(0xFF4E5D78), // slate+ ];++ /// The primary action's fill under the pointer — the top bar's Invite button.+ ///+ /// **Deepens in light, brightens in dark**, rather than one shift applied to+ /// both: hover should raise the control's contrast against the page it sits+ /// on, and the page runs the other way in the other theme. The numbers force+ /// it too — the obvious "lift toward [AppCard.accentStrong]" puts dark on+ /// `#5C7CFF`, where the button's own white label falls to **3.63:1**. These+ /// two hold it at 6.50:1 (light) and 4.76:1 (dark).+ static Color get accentHover =>+ AppTheme.pick(const Color(0xFF2850D8), const Color(0xFF4166F2));++ // "Owner" badge — a teal that stays legible on either surface.+ static Color get teal =>+ AppTheme.pick(const Color(0xFF0F766E), const Color(0xFF2DD4BF));++ // green "connected" dot+ static Color get online =>+ AppTheme.pick(const Color(0xFF15803D), const Color(0xFF3FB950));++ // expiring soon+ static Color get warn =>+ AppTheme.pick(const Color(0xFFB45309), const Color(0xFFFFB020));++ // grey dot+ static Color get offline =>+ AppTheme.pick(const Color(0xFFA3A29C), const Color(0xFF6E6E6E));++ // Grid brand lightning gold — the live/active ⚡ mark, matching the tray bolt.+ static Color get brandBolt =>+ AppTheme.pick(const Color(0xFFC98A00), const Color(0xFFE0A93B));++ static Color get textPrimary =>+ AppTheme.pick(const Color(0xFF1A1A18), const Color(0xFFF5F5F5));++ static Color get textSecondary =>+ AppTheme.pick(const Color(0xFF62615B), const Color(0xFFA8A8A2));++ static Color get textFaint =>+ AppTheme.pick(const Color(0xFF8E8D86), const Color(0xFF6E6E68));++ /// The page a document is drawn on, and the ink on it.+ ///+ /// The one pair here that does **not** follow the app's theme, deliberately: a+ /// page is the *document*, not the app's chrome. Word keeps dark chrome around+ /// white paper for the reason that decides it — what you edit has to look like+ /// what you send, and a page that turned charcoal in dark mode would show the+ /// author a document nobody else will ever see. Named here rather than typed+ /// into the editor so the rule is stated once and the exception is visible+ /// next to the tokens it breaks with.+ /// Both are `const`, and that is the enforcement rather than a note: a+ /// `AppTheme.pick` here would make the page follow Light/Dark, and a value that+ /// cannot be picked cannot drift. Pure black ink, not the app's near-black+ /// [textPrimary] — Word's "automatic" text colour is #000000, and this text is+ /// going to print.+ static const paper = Color(0xFFFFFFFF);+ static const paperInk = Color(0xFF000000);++ /// The furniture *around* the page — the formatting bar and the two rulers.+ ///+ /// Light in both themes, like [paper] above, and for a reason one step on+ /// from it. The page stays white because it is what you send; these stay light+ /// because they are what you set it with, and a ruler mixed for charcoal+ /// while the paper beside it is white belongs to neither. Word and Google Docs+ /// both keep this band light against a dark desk, which is what makes the page+ /// read as a page rather than as a white hole.+ ///+ /// `const` for the same reason [paper] is: a value that cannot be+ /// [AppTheme.pick]ed cannot quietly start following the theme again.+ ///+ /// Measured on [paperChrome]: [paperChromeInk] 11.3:1, [paperChromeInkSoft]+ /// 5.1:1 — both clear §11 with room, which the app's own text tokens would not+ /// have on this surface in dark.+ static const paperChrome = Color(0xFFF2F1ED);++ /// Hairlines, and the ruler's margin band.+ static const paperChromeLine = Color(0xFFD6D5CF);++ /// A pressed toggle, and the lift under a hovered glyph.+ static const paperChromeFill = Color(0xFFE3E2DC);++ /// Labels, glyphs and the ruler's numbers.+ static const paperChromeInk = Color(0xFF33332F);++ /// The resting ink of a control that isn't the one in force.+ static const paperChromeInkSoft = Color(0xFF63625C);++ /// The desk the page sits on.+ ///+ /// It used to follow the theme, and in dark that made it `#141414` — a page+ /// of white paper laid on near-black, which is the harshest edge the app had+ /// and the thing that made this screen tiring to look at. Now that the bar and+ /// the rulers around the page are fixed light, a desk that flipped was also+ /// the one surface still changing theme in the middle of the document, with+ /// chrome above it that didn't.+ ///+ /// So: one warm grey, in both. Deeper than [paperChromeLine] so the desk reads+ /// as *behind* the rulers rather than continuous with them, and far enough+ /// from [paper] that the page keeps its edges — which was the reason the light+ /// value could never be white either.+ static const paperDesk = Color(0xFFC4C3BD);+}++/// The scrollbar thumb, per brightness.+///+/// Kept as plain constants rather than only as [AppSurface] getters because+/// [buildAppTheme] needs the values *before* the global brightness is the one+/// being built for — see the note at its `scrollbarTheme`. The getters below read+/// these same four, so there is one set of numbers rather than two that can drift.+const Color _scrollThumbLight = Color(0xFF8C8C8C);+const Color _scrollThumbDark = Color(0xFF686868);+const Color _scrollThumbHoverLight = Color(0xFF6E6E6E);+const Color _scrollThumbHoverDark = Color(0xFF8A8A8A);++/// Surface tokens for the app's chrome — the sidebar's rows, the composer card,+/// a recessed list column. Depth comes from a hairline rim and a soft shadow; the+/// overlays flip from black (on light) to white (on dark) so a hover/selection is+/// visible on either surface.+abstract final class AppSurface {+ /// The sidebar row you're on.+ static Color get selectedFill =>+ AppTheme.pick(const Color(0x0D000000), const Color(0x14FFFFFF));++ /// The sidebar row under the pointer — lighter than [selectedFill], so hover+ /// never reads as "selected".+ static Color get hoverFill =>+ AppTheme.pick(const Color(0x07000000), const Color(0x0DFFFFFF));++ /// A whisper of the accent, washed under the rail's primary action ("New+ /// chat") so it invites the click without hardening into a button. Kept faint+ /// (~8% in light, a touch stronger in dark so it reads on charcoal).+ static Color get accentWash =>+ AppTheme.pick(const Color(0x142F5BEA), const Color(0x242F5BEA));++ /// The same wash a step stronger, for the primary action under the pointer —+ /// so hovering it still reads as a change without ever looking "selected".+ static Color get accentWashHover =>+ AppTheme.pick(const Color(0x1F2F5BEA), const Color(0x332F5BEA));++ /// The icon well inside a list row.+ ///+ /// Translucent on purpose. An opaque fill would be picked against the row's+ /// *resting* colour and then near-vanish the moment the row lifted on hover —+ /// measured at 1.041:1 against the hovered light row. An overlay rides whatever+ /// it sits on, so the well keeps its edge in both states:+ ///+ /// ```+ /// rest hover+ /// light 1.168 1.173+ /// dark 1.183 1.200+ /// ```+ ///+ /// The two themes take different alphas because they start from different+ /// grounds — light needs more to separate from `#F3F3F2` than dark does from+ /// `#202020`. The glyph inside keeps 4.79:1 (light) and 5.76:1 (dark).+ static Color get wellFill =>+ AppTheme.pick(const Color(0x12000000), const Color(0x0FFFFFFF));++ /// A recessed well inside a panel.+ static Color get recess =>+ AppTheme.pick(const Color(0x08000000), const Color(0x0FFFFFFF));++ /// The recessed well under the pointer — a step lighter than [recess], so a+ /// hoverable surface (the account pill) lifts a touch to say it's clickable.+ static Color get recessHover =>+ AppTheme.pick(const Color(0x12000000), const Color(0x1AFFFFFF));++ /// A scrollbar thumb at rest.+ ///+ /// Opaque rather than a wash, and per-brightness rather than one alpha, because+ /// Material's default is neither and lands under the 3:1 that WCAG 1.4.11 asks+ /// of a UI element — `onSurface` at 10% is **1.23:1** on the light page, and at+ /// 30% is **2.46:1** on the dark one. Both were measured; both read as "no+ /// scrollbar" until you look for it.+ ///+ /// One alpha can't fix it either: white lifts a dark page fast while black+ /// barely dents a white one, so reaching 3:1 needs 0.40 in dark and 0.50 in+ /// light. These are those two values resolved — 3.55:1 dark, 3.36:1 light —+ /// stated as colours so a list on the panel measures the same as one on the page.+ static Color get scrollThumb =>+ AppTheme.pick(_scrollThumbLight, _scrollThumbDark);++ /// The thumb under the pointer or mid-drag: the same hue, plainly grabbed.+ static Color get scrollThumbHover =>+ AppTheme.pick(_scrollThumbHoverLight, _scrollThumbHoverDark);++ /// Soft drop shadow that lifts a floating surface (the composer) off the page.+ /// Deeper/darker in dark mode where a light lift would look like a glow.+ static List<BoxShadow> get shadow => AppTheme.pick(+ const [+ BoxShadow(+ color: Color(0x14000000),+ blurRadius: 24,+ offset: Offset(0, 10),+ spreadRadius: -10,+ ),+ BoxShadow(color: Color(0x0A000000), blurRadius: 4, offset: Offset(0, 1)),+ ],+ const [+ BoxShadow(+ color: Color(0x66000000),+ blurRadius: 24,+ offset: Offset(0, 10),+ spreadRadius: -10,+ ),+ BoxShadow(color: Color(0x40000000), blurRadius: 4, offset: Offset(0, 1)),+ ],+ );++ /// The composer's lift — Codex gives its input a soft shadow that spreads wide+ /// and low so the box clearly floats over the transcript. Two layers: a broad+ /// ambient pool plus a tighter contact shadow right under the rim.+ static List<BoxShadow> get composerShadow => AppTheme.pick(+ const [+ BoxShadow(+ color: Color(0x1F000000),+ blurRadius: 28,+ offset: Offset(0, 10),+ spreadRadius: -6,+ ),+ BoxShadow(+ color: Color(0x14000000),+ blurRadius: 8,+ offset: Offset(0, 2),+ spreadRadius: -2,+ ),+ ],+ const [+ BoxShadow(+ color: Color(0x80000000),+ blurRadius: 30,+ offset: Offset(0, 12),+ spreadRadius: -6,+ ),+ BoxShadow(+ color: Color(0x4D000000),+ blurRadius: 10,+ offset: Offset(0, 3),+ spreadRadius: -3,+ ),+ ],+ );+}++/// Translucent Codex-like chrome surfaces used behind a backdrop blur (the+/// sidebar, the top bar, floating pills). Fills are semi-transparent so the blur+/// shows through; kept separate from [AppCard] because these surfaces are chrome,+/// not dense content cards.+abstract final class AppGlass {+ // Near-opaque so the rail reads as a calm flat surface, not a frosted panel.+ //+ // Dark is fully opaque and says the value it means. Nothing is blurred behind+ // the rail (see [AppSidebar]), so the alpha did one thing: pull the fill 6%+ // back towards the page under it and land the rail on #191919 rather than the+ // number written here — a token that could only be read by compositing it.+ // At #242424 the rail is 1.27:1 against the page, so it reads as a surface+ // the content lies beside rather than the same charcoal with a hairline on it.+ static Color get sidebarFill =>+ AppTheme.pick(const Color(0xF7F9F9F8), const Color(0xFF242424));++ // Pills/menus are solid white in Codex (their softness comes from the rim and+ // a whisper of shadow, not from translucency).+ static Color get surfaceFill =>+ AppTheme.pick(const Color(0xFFFFFFFF), const Color(0xFF202020));++ static Color get surfaceHoverFill =>+ AppTheme.pick(const Color(0xFFF7F7F6), const Color(0xFF272727));++ static Color get hair =>+ AppTheme.pick(const Color(0x14000000), const Color(0x1FFFFFFF));++ /// A more present rim for the surfaces that should read as *lifted* — the+ /// composer, above all. The plain [hair] disappears into a white pane; this one+ /// is a clear soft grey (~#DADADA on white) so the input keeps a visible edge+ /// like Codex, without hardening into a boxy outline.+ static Color get lift =>+ AppTheme.pick(const Color(0x2E000000), const Color(0x2EFFFFFF));++ static Color get bubbleFill =>+ AppTheme.pick(const Color(0xFFF3F3F1), const Color(0xFF242424));++ static List<BoxShadow> get shadow => AppTheme.pick(+ const [+ BoxShadow(+ color: Color(0x14000000),+ blurRadius: 16,+ offset: Offset(0, 6),+ spreadRadius: -6,+ ),+ BoxShadow(color: Color(0x0A000000), blurRadius: 2, offset: Offset(0, 1)),+ ],+ const [+ BoxShadow(+ color: Color(0x66000000),+ blurRadius: 18,+ offset: Offset(0, 7),+ spreadRadius: -7,+ ),+ BoxShadow(color: Color(0x33000000), blurRadius: 3, offset: Offset(0, 1)),+ ],+ );++ // A whisper — the soft, tight lift Codex gives its floating pills and menus,+ // not a big ambient drop.+ /// A list row sitting directly on the page, at rest.+ ///+ /// **Not [surfaceFill], and light is the whole reason.** `windowBg` in light is+ /// pure `#FFFFFF` and so is `surfaceFill`, which put the row and the page it+ /// sits on at **1.000:1** — the same colour. The list had no rows in light at+ /// all until the pointer moved over one, because `surfaceHoverFill` (`#F7F7F6`,+ /// 1.072:1) was the first fill that differed from the page.+ ///+ /// A raised block cannot be raised by fill on a pure-white page: lighter than+ /// white does not exist. So light recesses instead — a grey card on white, the+ /// ordinary light-UI idiom — while dark keeps lifting. Measured, and shaped to+ /// match dark's separation rather than guessed at:+ ///+ /// ```+ /// rest hover hover vs rest+ /// dark 1.090 1.189 1.091+ /// light 1.110 1.205 1.086+ /// ```+ ///+ /// Light's rest is [AppPalette.cardBg] rather than a new colour; only the hover+ /// step needed one. Text keeps its room on both: `textSecondary` reads 5.60:1+ /// at rest and 5.15:1 hovered.+ static Color get rowFill =>+ AppTheme.pick(const Color(0xFFF3F3F2), const Color(0xFF202020));++ /// The same row under the pointer.+ ///+ /// Moves *away* from the page in both themes — darker in light, lighter in dark+ /// — because a hover that drifts toward the background erases the row it is+ /// meant to be highlighting.+ static Color get rowHoverFill =>+ AppTheme.pick(const Color(0xFFEAEAE7), const Color(0xFF272727));++ static List<BoxShadow> get cardShadow => AppTheme.pick(+ const [+ BoxShadow(+ color: Color(0x0F000000),+ blurRadius: 8,+ offset: Offset(0, 3),+ spreadRadius: -3,+ ),+ BoxShadow(color: Color(0x08000000), blurRadius: 1, offset: Offset(0, 1)),+ ],+ const [+ BoxShadow(+ color: Color(0x59000000),+ blurRadius: 10,+ offset: Offset(0, 4),+ spreadRadius: -4,+ ),+ ],+ );+}++/// The floating-panel recipe — **one** source for every menu, popover and+/// tooltip in the app, so the three cannot drift apart.+///+/// They already had. Before this the app carried *four* recipes for the same+/// surface, and no two agreed:+///+/// ```+/// fill (dark) elevation radius rim+/// menuTheme / popupMenuTheme #1E1E1E 8 6 no+/// appMenuStyle() #2A2A2A 12 10 yes+/// tooltipTheme #1E1E1E — 10 yes+/// AccountFooter, inline cardBg 18 8 yes+/// ```+///+/// The cost was exactly what a second recipe always costs: the account footer's+/// `MenuAnchor` passed no style at all, so it opened the rimless themed default+/// — the surface `appMenuStyle` had been written to replace.+///+/// ⚠️ The fill is deliberately **not** the themed default. `#1E1E1E` sits within+/// 1.02:1 of a raised block ([AppGlass.surfaceFill], `#202020`), and in light+/// both are pure white — a menu opened over a dialog then has no edge at all and+/// its rows appear to float loose on the page. These lift clear of *both*+/// grounds a menu can open over: the page (`#181818` / `#FFFFFF`) and that+/// block. Measured with `tool/contrast.py`, 2026-09-03:+///+/// ```+/// dark panel #2A2A2A vs page #181818 = 1.237 : 1+/// dark panel #2A2A2A vs block #202020 = 1.135 : 1+/// light panel #FFFFFF vs page #FFFFFF = 1.000 : 1 ← the rim does it+/// light panel #FFFFFF vs block #FFFFFF = 1.000 : 1 ← and here+/// ```+///+/// Light is why the rim exists. On a white page the panel and the ground under+/// it are *the same colour*, so the rim is the only thing drawing the edge —+/// which is what earns it the one exception §1 allows. Fill alone cannot+/// separate two surfaces (§9.1); the rim and the shadow do it together, which is+/// also why the rim is not held to §16's 3.0 — see the note in `contrast.py`.+///+/// ⚠️ These are measurements with a date. Move `windowBg` or `surfaceFill` and+/// all four are stale — re-run the script, don't trust the comment.+///+/// ⚠️ The `*Light`/`*Dark` const twins exist for the same reason `_scrollThumb*`+/// do: [buildAppTheme] builds a theme for a brightness it has been *handed*,+/// while a getter answers for the brightness the app is *wearing*, and the two+/// differ in exactly the call that produces `darkTheme`. Inside that function+/// use [styleFor] and the consts; everywhere else use [style] and the getters.+abstract final class AppMenu {+ static const Color fillLight = Color(0xFFFFFFFF);+ static const Color fillDark = Color(0xFF2A2A2A);+ static Color get fill => AppTheme.pick(fillLight, fillDark);++ /// The panel's rim — the same hairline [AppGlass.hair] resolves to, stated as+ /// consts so [buildAppTheme] can read it.+ static const Color rimLight = Color(0x14000000);+ static const Color rimDark = Color(0x1FFFFFFF);+ static Color get rim => AppTheme.pick(rimLight, rimDark);++ /// A menu panel's rounding. On the §3 ladder this is the *panel* step (10),+ /// one below a content card (12) and above the rows inside it (8) — a child is+ /// never rounder than its parent.+ static const double panelRadius = 10;++ /// Deeper than Material's menu default (8): this panel opens over chrome that+ /// already carries a lift of its own, and at 8 it reads as lying *on* that+ /// chrome rather than over it.+ static const double elevation = 12;++ /// ⚠️ Vertical only. Rows carry their own horizontal gutter so their hover+ /// highlight reads as an inset pill; side padding here would double it.+ static const EdgeInsets panelPadding = EdgeInsets.symmetric(vertical: 5);++ /// The style every menu panel in the app takes.+ ///+ /// [minWidth]/[maxWidth] are for a panel whose width is part of its meaning —+ /// the account menu holds an email address and must not resize as the address+ /// changes. [maxHeight] defaults to [AppControl.menuMaxHeight]; override it+ /// only for a panel that is taller by design, and read that token's note+ /// first: a menu that opens *upward* places itself by summing the height it is+ /// about to take.+ static MenuStyle style({+ double? minWidth,+ double? maxWidth,+ double? maxHeight,+ }) => _style(+ isDark: AppTheme.isDark,+ minWidth: minWidth,+ maxWidth: maxWidth,+ maxHeight: maxHeight,+ );++ /// [style] resolved against a brightness handed in rather than the one the app+ /// is wearing. Only [buildAppTheme] needs this — see the ⚠️ above.+ static MenuStyle styleFor({required bool isDark}) => _style(isDark: isDark);++ static MenuStyle _style({+ required bool isDark,+ double? minWidth,+ double? maxWidth,+ double? maxHeight,+ }) => MenuStyle(+ backgroundColor: WidgetStatePropertyAll(isDark ? fillDark : fillLight),+ surfaceTintColor: const WidgetStatePropertyAll(Colors.transparent),+ elevation: const WidgetStatePropertyAll(elevation),+ padding: const WidgetStatePropertyAll(panelPadding),+ minimumSize: minWidth == null+ ? null+ : WidgetStatePropertyAll(Size(minWidth, 0)),+ maximumSize: WidgetStatePropertyAll(+ Size(maxWidth ?? double.infinity, maxHeight ?? AppControl.menuMaxHeight),+ ),+ shape: WidgetStatePropertyAll(+ RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(panelRadius),+ side: BorderSide(color: isDark ? rimDark : rimLight),+ ),+ ),+ );+}++/// Content-card recipe — a surface with a hairline rim and a soft lift. Distinct+/// from [AppSurface] (the chrome): cards carry dense content, so they stay quiet+/// and let the text do the work. Applied via [GlassCard].+abstract final class AppCard {+ static const accent = AppPalette.accent;+ static Color get accentStrong =>+ AppTheme.pick(const Color(0xFF1E40AF), const Color(0xFF5C7CFF));++ // card surface+ static Color get base =>+ AppTheme.pick(const Color(0xFFFFFFFF), const Color(0xFF1E1E1E));++ // recessed inner box / list tile+ static Color get inset =>+ AppTheme.pick(const Color(0xFFF7F7F5), const Color(0xFF181818));++ static Color get hair => AppPalette.divider; // card rim+ static Color get insetHair =>+ AppTheme.pick(const Color(0x0F000000), const Color(0x14FFFFFF));++ // Accent tints — used sparingly, for the focal card's wash and rim. Slightly+ // stronger in dark so the wash reads on charcoal.+ static Color get tint10 =>+ AppTheme.pick(const Color(0x0A2F5BEA), const Color(0x1A2F5BEA));+ static Color get tint18 =>+ AppTheme.pick(const Color(0x142F5BEA), const Color(0x282F5BEA));+ static Color get tint25 =>+ AppTheme.pick(const Color(0x332F5BEA), const Color(0x422F5BEA));++ static Color get highlightEdge =>+ AppTheme.pick(const Color(0x0A000000), const Color(0x1FFFFFFF));++ /// Corner rounding, on macOS's scale rather than iOS's.+ ///+ /// A Mac window is ~10 and a sheet/popover ~12; iOS and the web round far+ /// harder, and at 18 a card read as an iOS sheet that had wandered onto a+ /// desktop. It also disagreed with the buttons *inside* it ([AppControl.radius]+ /// is 8), so a card and its own action were speaking two shape languages.+ ///+ /// The inset tile drops to 8 to match those buttons: an inset sits inside a+ /// card, and nesting a rounder box inside a less-round one is what makes a+ /// tile look pasted on rather than set in.+ static const double radius = 12;+ static const double insetRadius = 8;++ /// Soft ambient drop that lifts a card off the page.+ static List<BoxShadow> get shadow => AppTheme.pick(+ const [+ BoxShadow(+ color: Color(0x12000000),+ blurRadius: 20,+ offset: Offset(0, 8),+ spreadRadius: -8,+ ),+ ],+ const [+ BoxShadow(+ color: Color(0x66000000),+ blurRadius: 20,+ offset: Offset(0, 8),+ spreadRadius: -8,+ ),+ ],+ );++ /// The focal (hero) card's stronger lift.+ static List<BoxShadow> get heroShadow => AppTheme.pick(+ [+ const BoxShadow(+ color: Color(0x1A000000),+ blurRadius: 28,+ offset: Offset(0, 12),+ spreadRadius: -8,+ ),+ BoxShadow(+ color: tint18,+ blurRadius: 32,+ offset: const Offset(0, 10),+ spreadRadius: -8,+ ),+ ],+ [+ const BoxShadow(+ color: Color(0x73000000),+ blurRadius: 28,+ offset: Offset(0, 12),+ spreadRadius: -8,+ ),+ BoxShadow(+ color: tint18,+ blurRadius: 32,+ offset: const Offset(0, 10),+ spreadRadius: -8,+ ),+ ],+ );+}++/// The app's theme for a given [brightness]. Both the light and dark themes are+/// built from this one function so the two never drift; the color tokens above+/// resolve against [AppTheme.brightness] at paint time.+ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {+ final isDark = brightness == Brightness.dark;+ final scheme = isDark+ ? ColorScheme.dark(+ primary: AppPalette.accent,+ onPrimary: Colors.white,+ secondary: AppPalette.accent,+ surface: AppTheme.palette.value.background,+ onSurface: const Color(0xFFF5F5F5),+ onSurfaceVariant: const Color(0xFFA8A8A2),+ surfaceContainerHighest: AppTheme.palette.value.card,+ outline: const Color(0x14FFFFFF),+ outlineVariant: const Color(0x14FFFFFF),+ error: const Color(0xFFF2544B),+ )+ : const ColorScheme.light(+ primary: AppPalette.accent,+ onPrimary: Colors.white,+ secondary: AppPalette.accent,+ // Pure white — matches AppPalette.windowBg so the chat pane (which+ // paints scheme.surface) reads as clean white, letting the composer's+ // rim and shadow stand out instead of blending into an off-white wash.+ surface: Color(0xFFFFFFFF),+ onSurface: Color(0xFF1A1A18),+ onSurfaceVariant: Color(0xFF62615B),+ surfaceContainerHighest: Color(0xFFF3F3F2),+ outline: Color(0x0F000000),+ outlineVariant: Color(0x0F000000),+ error: Color(0xFFB3261E),+ );++ // The chrome fills used by menus, dialogs and toasts. A getter-backed token+ // can't be a compile-time const, so these are resolved here per-brightness —+ // and, more importantly, from `isDark` rather than off a token, for the reason+ // spelled out at `scrollbarTheme` below.+ //+ // Two fills, not one. A *floating panel* (menu, popover, tooltip) opens over+ // chrome that may itself be raised, so it takes [AppMenu]'s lifted fill; a+ // *dialog* is the raised block, so it takes the block's own fill. Before this+ // both were `#1E1E1E`, which is [AppCard.base] — a content card's colour, one+ // step *below* the block it was supposed to be.+ final panelFill = isDark ? AppMenu.fillDark : AppMenu.fillLight;+ final dialogFill = isDark+ ? AppTheme.palette.value.card+ : const Color(0xFFFFFFFF);+ final textTheme = _appTextTheme(scheme.onSurface, scheme.onSurfaceVariant);++ return ThemeData(+ filledButtonTheme: FilledButtonThemeData(style: _filledButtonStyle()),+ outlinedButtonTheme: OutlinedButtonThemeData(+ style: _outlinedButtonStyle(scheme),+ ),+ textButtonTheme: TextButtonThemeData(style: _textButtonStyle()),+ useMaterial3: true,+ brightness: brightness,+ colorScheme: scheme,+ // Also stated at ThemeData level, not only inside the ramp: Material builds+ // text of its own (a dialog's semantics label, a field's error line) that+ // never passes through `textTheme`, and without this those fall through to+ // Roboto — one stray face in an app drawn entirely in San Francisco.+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ scaffoldBackgroundColor: scheme.surface,+ canvasColor: scheme.surface,+ dividerColor: scheme.outline,+ dividerTheme: DividerThemeData(+ color: scheme.outline,+ thickness: 1,+ space: 1,+ ),+ // Set once here rather than per-Scrollbar: the three call sites that predate+ // this each accepted Material's default, which measures 1.23:1 on the light+ // page and 2.46:1 on the dark one — under the 3:1 floor for a UI element.+ // See `AppSurface.scrollThumb` for the numbers.+ scrollbarTheme: ScrollbarThemeData(+ // Resolved from `isDark`, not read off `AppSurface` — this function is+ // called twice up front, and the dark pass runs while the global+ // brightness still says light, so a getter-backed token would bake the+ // light thumb into `darkTheme`. The `AppPalette.accent` reads above never+ // exposed this: that one is a const with the same value in both themes.+ thumbColor: WidgetStateProperty.resolveWith(+ (states) =>+ states.contains(WidgetState.hovered) ||+ states.contains(WidgetState.dragged)+ ? (isDark ? _scrollThumbHoverDark : _scrollThumbHoverLight)+ : (isDark ? _scrollThumbDark : _scrollThumbLight),+ ),+ // No track: a filled channel down the edge of every pane is a border by+ // another name, and §2 allows exactly one of those.+ trackColor: WidgetStateProperty.all(Colors.transparent),+ trackBorderColor: WidgetStateProperty.all(Colors.transparent),+ // 6px, radius 3 — a thin capsule rather than the 8px slab, which at this+ // contrast would read as a chrome element competing with the rows.+ thickness: WidgetStateProperty.all(6),+ radius: const Radius.circular(3),+ // The thumb is only meaningful while there is more list than pane, and+ // fading it in on scroll keeps a short list from wearing furniture.+ thumbVisibility: WidgetStateProperty.all(false),+ interactive: true,+ ),+ // Material opens a tooltip the instant the pointer enters. In a transcript+ // that scrolls under a still pointer that means tooltips popping open on+ // rows flying past — and worse: a tooltip shown mid-scroll gets its overlay+ // hit-tested before it has been laid out, which throws inside the mouse+ // tracker and then re-throws every frame after (see ErrorBurstFilter). A+ // delay is the fix for both, set once here rather than at the nine call+ // sites that each reached for their own number.+ //+ // Everything below the delay is the app's floating-panel recipe, the same+ // one `appMenuStyle` uses, because a tooltip is one: the menu fill, the+ // hairline rim, the panel radius and the lift. Material's own is an+ // *inverse* surface — deliberately the opposite of the window — so on a dark+ // build it opened a white slab in the middle of a near-black app.+ //+ // The rim earns its place here for the reason it does on a menu: in light+ // the fill is the same white as the surface underneath, so the rim is the+ // only thing drawing the edge, and in dark it firms up a lift that a shadow+ // alone renders too softly against near-black.+ tooltipTheme: TooltipThemeData(+ waitDuration: const Duration(milliseconds: 500),+ decoration: BoxDecoration(+ color: panelFill,+ borderRadius: BorderRadius.circular(AppMenu.panelRadius),+ // Resolved from `isDark` rather than read off the `AppMenu` getters:+ // those answer for the brightness the app is *showing*, and this function+ // builds the theme for a brightness it has been handed.+ border: Border.all(color: isDark ? AppMenu.rimDark : AppMenu.rimLight),+ boxShadow: isDark+ ? const [+ BoxShadow(+ color: Color(0x66000000),+ blurRadius: 24,+ offset: Offset(0, 10),+ spreadRadius: -10,+ ),+ BoxShadow(+ color: Color(0x40000000),+ blurRadius: 4,+ offset: Offset(0, 1),+ ),+ ]+ : const [+ BoxShadow(+ color: Color(0x14000000),+ blurRadius: 24,+ offset: Offset(0, 10),+ spreadRadius: -10,+ ),+ BoxShadow(+ color: Color(0x0A000000),+ blurRadius: 4,+ offset: Offset(0, 1),+ ),+ ],+ ),+ // A step under the control font: a tooltip is read *while* looking at the+ // thing it explains, so it should not compete with it. The line height is+ // for the long ones — a run of selections is several lines of quoted code,+ // and set solid it reads as a wall.+ textStyle: TextStyle(+ fontSize: 12.5,+ height: 1.45,+ color: scheme.onSurface,+ ),+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),+ // Long quoted lines would otherwise take the tooltip out to the window's+ // full width — a panel wider than the conversation it is explaining.+ constraints: const BoxConstraints(maxWidth: 420),+ ),+ // macOS controls do not ripple. §10.1 lists the ink ripple among the four+ // things a raw `MenuItemButton` gets wrong, and §11 names it again for+ // `IconButton` and `SegmentedButton` — so turning it off once here is the+ // same rule applied at the root instead of at every call site.+ splashFactory: NoSplash.splashFactory,+ textTheme: textTheme,+ primaryTextTheme: textTheme,+ iconTheme: IconThemeData(color: scheme.onSurfaceVariant, size: 18),+ switchTheme: SwitchThemeData(+ thumbColor: WidgetStateProperty.all(Colors.white),+ trackColor: WidgetStateProperty.resolveWith(+ (s) => s.contains(WidgetState.selected)+ ? AppPalette.accent+ : (isDark ? const Color(0xFF3A3A3A) : const Color(0xFFA3A29C)),+ ),+ trackOutlineColor: WidgetStateProperty.all(Colors.transparent),+ ),+ // A text field must show where the keyboard is going. This used to set+ // BorderSide.none on all three states, so every field that took the theme+ // default — most of the app — had no focus ring at all: you could not tell+ // a focused field from an idle one. macOS rings the focused control in the+ // accent; that's what these borders restore.+ inputDecorationTheme: InputDecorationTheme(+ isDense: true,+ filled: true,+ fillColor: scheme.surfaceContainerHighest,+ // A field is a control, so its hint takes the control font — 13pt, the+ // same as the button beside it. (The typed text is set on the field via+ // [kFieldTextStyle]; `InputDecorationTheme` has no `style` of its own, so+ // a field's own text can't be themed globally here.)+ hintStyle: _fieldTextStyle(+ scheme.onSurfaceVariant.withValues(alpha: 0.7),+ ),+ // Material builds a field for a phone: its default padding, plus the 48px+ // touch target it gives a prefixIcon, rendered this 48 tall next to a 32px+ // button. That's what these constraints exist to hold back.+ //+ // The height is [AppControl.heightField], not [AppControl.height]: a field+ // is typed in, not clicked, and at a button's 32 it reads cramped — see+ // that token. Derived here rather than typed as a number that happens to+ // land near it.+ //+ // The arithmetic: the box is padding + one line of AppControl.fontSize.+ // `isDense` already tightens Material's own vertical slack, so the padding+ // is what's left over once the line has taken its share.+ constraints: BoxConstraints(minHeight: AppControl.heightFieldScaled),+ contentPadding: EdgeInsets.symmetric(+ horizontal: 10,+ vertical:+ (AppControl.heightFieldScaled -+ AppControl.fontSize * 1.35 * AppFont.uiScale) /+ 2,+ ),+ // The glyph sits on the text's line, not in a tap target of its own. A+ // step above [AppControl.iconSize]: that size is tuned to a button's cap+ // height, and this field is taller, so the button's glyph looks+ // undersized in it.+ prefixIconConstraints: BoxConstraints(+ minWidth: 32 * AppFont.uiScale,+ minHeight: kFieldIconSize * AppFont.uiScale,+ ),+ border: _fieldBorder(scheme.outline),+ enabledBorder: _fieldBorder(scheme.outline),+ focusedBorder: _fieldBorder(AppPalette.accent, width: 1.5),+ errorBorder: _fieldBorder(scheme.error),+ focusedErrorBorder: _fieldBorder(scheme.error, width: 1.5),+ ),+ // Fill, rim and elevation come from [AppMenu] so a Material popup cannot+ // disagree with a MenuAnchor about what a menu looks like.+ //+ // The radius does not: [AppControl.menuRadius] (6) is the §3 step for+ // *Material's own* popup, which draws tighter than the app's panel (10).+ popupMenuTheme: PopupMenuThemeData(+ color: panelFill,+ surfaceTintColor: Colors.transparent,+ elevation: AppMenu.elevation,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(AppControl.menuRadius),+ side: BorderSide(color: isDark ? AppMenu.rimDark : AppMenu.rimLight),+ ),+ ),+ // The default every `MenuAnchor` gets, identical to what [AppMenu.style]+ // hands a call site that asks for one explicitly. That identity is the whole+ // point: a MenuAnchor that forgets to pass a style used to fall back to a+ // rimless panel, which is the bug the hand-written style existed to fix.+ menuTheme: MenuThemeData(style: AppMenu.styleFor(isDark: isDark)),+ // An ExpansionTile defaults `backgroundColor` (expanded) and+ // `collapsedBackgroundColor` to *different* values and cross-fades between+ // them, so opening one flashes a tint over whatever surface it sits on. Our+ // tiles are always laid into a card that has already painted its own+ // background, so both states must simply be transparent — then expanding+ // moves the disclosure and nothing else.+ expansionTileTheme: const ExpansionTileThemeData(+ backgroundColor: Colors.transparent,+ collapsedBackgroundColor: Colors.transparent,+ // Same reason for the divider lines each tile was clearing by hand.+ shape: Border(),+ collapsedShape: Border(),+ ),+ dialogTheme: DialogThemeData(+ // The raised block's own fill, not a menu's and not a card's. §9.3: a+ // dialog that takes `windowBg` merges with the page, and one that takes+ // [AppCard.base] sits a step under the block it is supposed to *be* —+ // both invisible in light, both plain in dark.+ backgroundColor: dialogFill,+ surfaceTintColor: Colors.transparent,+ // The card radius, not a number of its own. This was 18 — the iOS+ // action-sheet curve, and the app's cards had already come down to 12 for+ // macOS without the dialogs following.+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(AppCard.radius),+ ),+ ),+ // ⚠️ [AppPalette.accentOnSurface], NOT `colorScheme.primary`.+ //+ // A spinner is the textbook case that token exists for: a MARK ON A SURFACE,+ // not a fill carrying white text. Left to `primary` the arc draws #2F5BEA on+ // the dark page, which measures 3.218:1 — over §16's 3.0 floor for a UI+ // element, but only just, and it is the one thing on screen saying the app+ // is still working. The lifted tint reaches 5.750:1.+ //+ // Resolved from `isDark` rather than read off the getter — see the note at+ // `scrollbarTheme`.+ progressIndicatorTheme: ProgressIndicatorThemeData(+ color: isDark ? const Color(0xFF6E8BFF) : const Color(0xFF2F5BEA),+ linearTrackColor: scheme.outline,+ ),+ snackBarTheme: SnackBarThemeData(+ behavior: SnackBarBehavior.floating,+ width: 520,+ // A snackbar floats over everything, so it takes the panel fill.+ backgroundColor: panelFill,+ contentTextStyle: TextStyle(+ color: scheme.onSurface,+ fontSize: 13.5,+ fontWeight: FontWeight.w600,+ ),+ actionTextColor: AppPalette.accent,+ closeIconColor: scheme.onSurfaceVariant,+ elevation: 10,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(13)),+ ),+ );+}++/// The one set of numbers every button in the app is built from.+///+/// macOS controls are compact, squarish and quiet: a 13pt semibold label in a+/// ~32px capsule with a small radius — not the tall, wide, fully-round buttons+/// Material defaults to. Before this existed each call site invented its own,+/// which is how the app ended up with seven button heights, three shape systems+/// and six label sizes. Change a number here, not at a call site.+abstract final class AppControl {+ /// Standard control height. macOS's regular push button sits at 32; the app's+ /// own most-used value was 34, and 32 reads correctly next to a 13pt label.+ static const double height = 32;++ /// A compact control (inline actions inside a dense row or a card header).+ static const double heightSmall = 28;++ /// A search field at the head of a list column.+ ///+ /// Taller than [height], and deliberately: a push button is sized to be hit,+ /// but this field is sized to be *typed in* and to anchor the column under it.+ /// Finder and Mail both give their sidebar search more room than a button in+ /// the same window for exactly that reason — at [height] it reads as cramped,+ /// which is what a control set to a button's scale looks like when it isn't+ /// one.+ static const double heightField = 36;++ /// Corner radius. Apple's push buttons are gently rounded, not stadium — a+ /// pill reads as a "chip" on macOS, not as a button.+ static const double radius = 8;++ /// A menu/popover's rounding. Tighter than a button's: macOS menus are nearly+ /// square-cornered, and rounding one like an iOS action sheet is one of the+ /// louder tells that a desktop app was drawn to phone conventions.+ static const double menuRadius = 6;++ /// The air between a menu panel and the control it hangs off.+ ///+ /// One number for every menu in the app, in both directions: a downward menu+ /// passes `Offset(0, menuGap)`, an upward one `Offset(0, -menuGap)`. It was+ /// three numbers before — 6 nearly everywhere, 8 on the composer's agent and+ /// approval pills, and none at all on its model pill, so the three menus that+ /// open off the *same* toolbar each sat at a different height.+ static const double menuGap = 6;++ /// The tallest a menu panel ever draws, whatever it lists — `appMenuStyle`+ /// caps every menu here.+ ///+ /// A token rather than a number inside that style, because the menus that+ /// open *upward* have to place themselves by summing the height they are+ /// about to take: a caller that predicts 310 for a panel the style then draws+ /// at 240 lifts it 70px clear of its button. That is what floated the chat+ /// model list off the composer and over the conversation.+ /// [anchoredMenuPosition] clamps to this by default.+ static const double menuMaxHeight = 240;++ /// The label. 13pt medium is the macOS control font — Apple sets a push+ /// button's label at medium, not semibold; at 13pt the extra step reads as a+ /// button trying to be a heading.+ static const double fontSize = 13;+ static const FontWeight fontWeight = AppFont.medium;++ /// A leading glyph inside a button, sized to sit on the cap height of a 13pt+ /// label rather than tower over it.+ static const double iconSize = 16;++ /// The glyph on a chip — an inline affordance whose label runs smaller than a+ /// button's (11pt, not 13). [iconSize] is cut to a 13pt cap height and towers+ /// over an 11pt one, so a chip needs its own step down rather than a number+ /// picked by eye at each call site.+ static const double iconSizeChip = 13;++ /// Horizontal breathing room. Apple pads a push button generously sideways and+ /// barely at all vertically — the height is what sets the touch target.+ static const EdgeInsets padding = EdgeInsets.symmetric(horizontal: 14);+ static const EdgeInsets paddingSmall = EdgeInsets.symmetric(horizontal: 10);++ /// A button that leads with a glyph, at the compact scale.+ ///+ /// Wider on the leading edge than the trailing one, and the asymmetry is the+ /// point: [paddingSmall] is even, which measures as centred and *reads* as+ /// pushed left. A glyph is a solid shape that fills its box to the edge, while+ /// a label's first letter carries its own sidebearing — so at an equal 10px+ /// the glyph sits visibly tighter to the rim than the text does at the other+ /// end. Extra leading pad buys back what the glyph lacks.+ ///+ /// Only for `.icon` constructors; a text-only button stays on [paddingSmall].+ static const EdgeInsets paddingSmallIcon = EdgeInsets.only(+ left: 12,+ right: 10,+ );++ // — the same numbers, grown with the user's UI size —+ //+ // The constants above stay constants on purpose. They appear in ~40 `const`+ // expressions across the app (`const Size(0, AppControl.height)`, `const+ // Icon(…, size: AppControl.iconSize)`), and turning them into getters would+ // break every one of those for no gain: a `const Icon` inside a themed button+ // is already re-laid-out when the button's own box grows.+ //+ // What actually has to grow is the *box*, and every box in the app comes from+ // one of the button/field styles built below in [buildAppTheme] — so these+ // scaled forms are read there, in one place, rather than at the call sites.++ /// [height], grown for the current UI size.+ static double get heightScaled => height * AppFont.uiScale;++ /// [heightField], grown for the current UI size.+ static double get heightFieldScaled => heightField * AppFont.uiScale;++ /// [padding], grown for the current UI size — a wider label needs the+ /// sidebearing to grow with it, or the text crowds the capsule's ends.+ static EdgeInsets get paddingScaled =>+ EdgeInsets.symmetric(horizontal: 14 * AppFont.uiScale);++ static EdgeInsets get paddingSmallScaled =>+ EdgeInsets.symmetric(horizontal: 10 * AppFont.uiScale);++ // [fontSize] deliberately has no scaled twin. The label inside a button is a+ // `Text`, so `MediaQuery`'s text scaler already grows it — scaling the+ // theme's `textStyle` too would apply the user's setting twice, and a button+ // set to 19px would render at ~26. The boxes above scale; the type does not.+}++/// How long the app's UI takes to change, and on what curve.+///+/// These aren't new numbers — they're the ones already in use, given a name. The+/// app had settled on ~130ms for a hover and `Curves.easeOut` almost everywhere+/// (31 call sites against 8 for the next most common), but every one of them+/// typed the number in by hand, and the drift had already started: 120, 130, 140+/// and 160 all appear for the same kind of change. A tile in Plugins even+/// carries a comment saying its timing "matches the job list's, so a row lifts+/// the same way everywhere in the app" — an intent with nothing enforcing it.+///+/// Motion here is for *continuity*, not decoration: it says the thing you're+/// looking at is the same thing it was a moment ago. That's why it's this short.+/// Anything long enough to notice as an animation is too long for a hover.+abstract final class AppMotion {+ /// A surface reacting to the pointer — a row's hover fill, a chip warming up.+ static const Duration hover = Duration(milliseconds: 130);++ /// Content being replaced in place: a list swapping to another set of rows.+ static const Duration swap = Duration(milliseconds: 160);++ /// A panel folding or unfolding — the sidebar collapsing to its glyphs.+ ///+ /// Longer than [swap], and it has to be: what moves is the window's left+ /// edge and everything to the right of it, over 212px. At [swap] that reads+ /// as the layout jumping rather than the rail folding, which is the one thing+ /// the animation exists to prevent.+ static const Duration fold = Duration(milliseconds: 220);++ /// A meter filling to the figure beside it — the node panel's speed bars.+ ///+ /// Longer than [fold] even though what moves is 26px, because this one is not+ /// a surface getting out of the way: it is a value being drawn, and a reader+ /// is meant to watch it arrive. Under about a quarter second the bars read as+ /// having simply appeared at their length, which is the same as no animation+ /// at all.+ ///+ /// Still short enough to survive repetition. These panels open on hover, so+ /// the fill replays every time the pointer crosses the pill — anything that+ /// lingers turns into a toll on a gesture people make dozens of times an hour.+ static const Duration meter = Duration(milliseconds: 300);++ /// A surface acknowledging a click while the button is still down.+ ///+ /// Shorter than [hover], and it has to be: hover follows a pointer that is+ /// merely passing, while this one answers a press the user is *making*. A+ /// dip that outlasts the click reads as lag in the click itself. Four call+ /// sites had already converged on this number by hand before it had a name.+ static const Duration press = Duration(milliseconds: 110);++ /// The app's curve. Fast to start, settling at the end — the thing arrives+ /// under the pointer rather than drifting toward it.+ static const Curve curve = Curves.easeOut;+}++/// The app's two font stacks, and the rule for which one a given piece of text+/// gets.+///+/// The rule: **mono is for strings the user copies, not for strings they read.**+/// A model id, an endpoint, a token — those need `l`/`1`/`I` and `0`/`O` to stay+/// apart, because the user is going to paste them somewhere that cares. Prose+/// (a heading, a subtitle, a node's name) is *read*, and mono makes reading it+/// slower while making the surface look like a terminal instead of a product.+///+/// Numbers are the case that looks like it wants mono but doesn't: what a stat+/// actually needs is digits that don't reflow when the value changes, and+/// [tabularFigures] buys exactly that on the sans stack — no terminal costume+/// required.+abstract final class AppFont {+ /// The reading stack — matches the text theme's system font.+ ///+ /// A getter, not a const: the user can put a family of their own in front of+ /// it from Appearance, and a `const` can't be re-resolved. [sansDefault] is+ /// the shipped value, still a const, and still what everything falls back to.+ static String get sans => _uiFamily ?? sansDefault;++ /// The shipped reading face, per platform.+ ///+ /// A getter now, because the shipped value is not one name: nothing in the+ /// Apple stack resolves on Linux, so the app was drawn in the engine's own+ /// default rather than a face anyone chose.+ ///+ /// `Ubuntu Sans` (25.04 and later) and `Ubuntu` (before it) lead because they+ /// are what the desktop itself is set in. Measured on Ubuntu 26.04 they do+ /// not currently resolve either — both are two-axis variable fonts+ /// (`wdth,wght`) and measure identically to a family that does not exist,+ /// while the single-axis `Ubuntu Sans Mono` resolves fine — so today the+ /// effective face is `Noto Sans`, the next entry. They stay in front because+ /// they cost nothing and are the right answer the moment the engine can+ /// reach them; `Noto Sans` and `DejaVu Sans` are what actually carries it.+ static String get sansDefault =>+ hasAppleFonts ? _macSansDefault : _linuxSansDefault;++ static const String _macSansDefault = '.AppleSystemUIFont';+ static const String _linuxSansDefault = 'Ubuntu Sans';++ /// The fallbacks behind [sans].+ ///+ /// When the user has chosen a family, the *system* font goes to the front of+ /// this list rather than being dropped: a chosen face is usually a display or+ /// text font with a partial repertoire, and one missing glyph should degrade+ /// to SF Pro — the thing the app was drawn in — rather than to Arial or to a+ /// row of tofu boxes.+ static List<String> get sansFallback => _uiFamily == null+ ? _sansFallbackDefault+ : [sansDefault, ..._sansFallbackDefault];++ static List<String> get _sansFallbackDefault =>+ hasAppleFonts ? _macSansFallback : _linuxSansFallback;++ static const List<String> _macSansFallback = [+ 'SF Pro Text',+ 'Helvetica Neue',+ 'Arial',+ ];++ static const List<String> _linuxSansFallback = [+ 'Ubuntu',+ 'Noto Sans',+ 'DejaVu Sans',+ 'sans-serif',+ ];++ /// The copy-me stack: SF Mono, the system's own code face.+ ///+ /// The name matters. `'SF Mono'` does **not** resolve — CoreText returns nil+ /// for it, so Flutter quietly falls through to the next entry (that's what the+ /// login screen's `fontFamily: 'SF Mono'` has always done: it renders Menlo).+ /// The face is only reachable under its internal name, below. Verified with+ /// `NSFont(name:size:)` + `CTFontGetBoundingRectsForGlyphs`; a `flutter test`+ /// probe can't confirm this — the headless test font manager resolves every+ /// family to the same test face and reports monospace metrics for all of them.+ ///+ /// Menlo is the fallback, not a compromise: its glyphs measure within 0.01pt+ /// of SF Mono's at 13px. SF Mono leads only for a slashed zero and a tailed+ /// `l`, which is exactly what a model id needs. Avoid Monaco — it lacks a+ /// slashed zero.+ static String get mono => _codeFamily ?? monoDefault;++ /// The shipped code face, per platform — same argument as [sansDefault], and+ /// a worse failure when it is wrong: on Linux the whole Apple stack down to+ /// `Courier New` resolved to a PROPORTIONAL face, so anything set in "mono"+ /// was not monospaced at all. The Linux chain is the terminal's own default+ /// (see `lib/terminal/terminal_typography.dart` for why DejaVu leads).+ static String get monoDefault =>+ hasAppleFonts ? _macMonoDefault : _linuxMonoDefault;++ static const String _macMonoDefault = '.AppleSystemUIFontMonospaced';+ static const String _linuxMonoDefault = 'DejaVu Sans Mono';++ /// The fallbacks behind [mono]. The system's own mono goes in front of them+ /// once a family is chosen, for the reason given on [sansFallback] — and it+ /// matters more here: a code block that falls through to a proportional face+ /// stops being a code block.+ static List<String> get monoFallback => _codeFamily == null+ ? _monoFallbackDefault+ : [monoDefault, ..._monoFallbackDefault];++ static List<String> get _monoFallbackDefault =>+ hasAppleFonts ? _macMonoFallback : _linuxMonoFallback;++ static const List<String> _macMonoFallback = [+ 'Menlo',+ 'Monaco',+ 'Courier New',+ 'monospace',+ ];++ static const List<String> _linuxMonoFallback = [+ 'Ubuntu Sans Mono',+ 'Noto Sans Mono',+ 'Liberation Mono',+ 'monospace',+ ];++ /// Digits that hold a fixed width, so a stat doesn't reflow as its value+ /// changes and a column of numbers lines up.+ static const List<FontFeature> tabularFigures = [+ FontFeature.tabularFigures(),+ ];++ // — the weight ladder —+ //+ // Three steps, and the app should not need a fourth. Named rather than typed+ // as `FontWeight.w500` at the call site, because the numbers moved once+ // already: the app was drawn at w600 for every label and w700 for every+ // heading, which is a step heavier than macOS itself sets the same things.+ // Finder's sidebar, System Settings' rows and a push button's label are all+ // *medium*; semibold is what Apple reserves for a window title or a section+ // header that has to out-rank the rows under it.+ //+ // At 13pt on a Retina panel that one step is the difference between a UI that+ // reads as crisp and one that reads as shouted — every label competing with+ // every other, and nothing left to promote a heading with.++ /// Body copy, and anything that is simply being read.+ static const FontWeight regular = FontWeight.w400;++ /// The app's workhorse: control labels, sidebar items, row titles, table+ /// headers — anything that names something without being a heading.+ ///+ /// This is the weight that used to be [semibold] in 133 places.+ static const FontWeight medium = FontWeight.w500;++ /// Reserved for type that has to out-rank the medium text beside it: a screen+ /// or section heading, the selected row in a menu.+ ///+ /// If everything on a screen is semibold, nothing is — which is the state the+ /// ladder was introduced to fix. Reach for [medium] first.+ static const FontWeight semibold = FontWeight.w600;++ /// The tracking a given size wants, in logical pixels.+ ///+ /// SF Pro is an optically-sized family: on Apple's own platforms the system+ /// re-spaces it as it scales, opening the letters up at caption sizes and+ /// pulling them in at display sizes. Flutter asks CoreText for one static+ /// face, so none of that happens for free and every size came out at the+ /// metrics of whatever master got picked — which is why small text read as+ /// cramped and large headings read as one solid mass.+ ///+ /// The curve below follows Apple's own SF Pro tracking table, rounded to the+ /// steps this app actually uses:+ ///+ /// ```+ /// ≥ 28pt -0.4 display / greeting+ /// ≥ 20pt -0.25 screen titles+ /// ≥ 17pt -0.1 section headings+ /// ≥ 15pt 0 body — the neutral point the app was drawn at+ /// ≥ 13pt +0.05 control labels+ /// < 13pt +0.12 captions, chips, meta+ /// ```+ ///+ /// The numbers are small on purpose. Tracking is not a style knob — at half a+ /// pixel it is already the difference between a line that breathes and one+ /// that doesn't, and anything larger starts to look like a logotype.+ static double trackingFor(double size) {+ if (size >= 28) return -0.4;+ if (size >= 20) return -0.25;+ if (size >= 17) return -0.1;+ if (size >= 15) return 0;+ if (size >= 13) return 0.05;+ return 0.12;+ }++ // — the user's type settings, mirrored here so a token read resolves them —+ //+ // These are set from one place (`FontSync` in `grid_app.dart`, fed by+ // `fontPrefsProvider`) and read from everywhere, exactly like+ // `AppTheme.brightness`. A widget reading them must call [AppTheme.watch] to+ // be rebuilt when they change — see that method for why a top-down rebuild+ // isn't enough in this app.++ static String? _uiFamily;+ static String? _codeFamily;+ static double _uiScale = 1;+ static double _codeSize = _codeSizeDefault;++ static const double _codeSizeDefault = 12.5;++ /// The UI size the app was DRAWN at, and therefore the denominator of+ /// [uiScale]: a setting of 14 gives a scale of exactly 1, which is the only+ /// value at which every control keeps the geometry this file specifies.+ ///+ /// Public because the settings screen has to divide by it to turn a size the+ /// user picked into the scale [apply] takes, and a second copy of the number+ /// on that side is a second thing to forget.+ static const double uiSizeDefault = 14;++ /// What every UI dimension is multiplied by: 1.0 is the size the app was+ /// drawn at.+ static double get uiScale => _uiScale;++ /// The size code is set at, in logical pixels.+ ///+ /// Absolute, not scaled: the UI scale reaches code through `MediaQuery`'s text+ /// scaler like it reaches everything else, so a code surface that also+ /// multiplied by [uiScale] would apply it twice. Code surfaces wrap themselves+ /// in `MediaQuery.withNoTextScaling` and use this number as-is.+ static double get codeSize => _codeSize;++ /// Apply the user's type settings. Returns true when something actually+ /// changed, so the caller only fires listeners on a real change.+ static bool apply({+ String? uiFamily,+ String? codeFamily,+ required double uiScale,+ required double codeSize,+ }) {+ if (uiFamily == _uiFamily &&+ codeFamily == _codeFamily &&+ uiScale == _uiScale &&+ codeSize == _codeSize) {+ return false;+ }+ _uiFamily = uiFamily;+ _codeFamily = codeFamily;+ _uiScale = uiScale;+ _codeSize = codeSize;+ return true;+ }++ /// The style for a surface made of code — a diff, a log, a code block, a+ /// model id the user is going to paste somewhere.+ ///+ /// Carries the user's code family *and* their code size, so a caller gets+ /// both from one place instead of remembering to read the second. [scale]+ /// is for the few call sites drawn deliberately smaller than body code (a+ /// caption under a block, a chip): it keeps them proportional to the user's+ /// choice rather than pinned to a number that stops matching once the setting+ /// moves.+ ///+ /// Pair this with `MediaQuery.withNoTextScaling` on the surface — see+ /// [codeSize] for why.+ static TextStyle codeStyle({+ Color? color,+ double scale = 1,+ double? height,+ FontWeight? fontWeight,+ }) => TextStyle(+ fontFamily: mono,+ fontFamilyFallback: monoFallback,+ fontSize: codeSize * scale,+ color: color,+ height: height,+ fontWeight: fontWeight,+ );++ /// Put the type settings back to the shipped defaults.+ ///+ /// For tests: the fields are static, so one test that changes the font would+ /// otherwise leak into every test that runs after it in the same process.+ static void reset() {+ _uiFamily = null;+ _codeFamily = null;+ _uiScale = 1;+ _codeSize = _codeSizeDefault;+ }+}++/// A text field's rim at one state. Radius matches [AppControl.radius] so a+/// field and the button next to it are cut from the same shape language.+OutlineInputBorder _fieldBorder(Color color, {double width = 1}) =>+ OutlineInputBorder(+ borderRadius: BorderRadius.circular(AppControl.radius),+ borderSide: BorderSide(color: color, width: width),+ );++/// The label style shared by every button, carrying the UI font: a+/// `ButtonStyle.textStyle` does **not** inherit `fontFamily` from the text+/// theme, so a button that sets only a size silently drops SF Pro.+///+/// A getter, not a const: it reads [AppFont.sans], which the user can change.+TextStyle get _buttonTextStyle => TextStyle(+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ fontSize: AppControl.fontSize,+ fontWeight: AppControl.fontWeight,+ // From the same ramp as the text theme, rather than a flat 0: a button's+ // label is 13pt, which is small enough to want its letters opened up.+ letterSpacing: AppFont.trackingFor(AppControl.fontSize),+);++/// A text field's own text: the macOS control font, so a field sits at the same+/// scale as the button next to it.+///+/// Material's default field text is `bodyLarge` — 16pt, sized for a phone. On a+/// desktop row that puts a visibly larger search box beside a 13pt button.+/// `InputDecorationTheme` has no `style` slot (it themes the *decoration*, not+/// the editable text), so a field must be handed this explicitly:+/// `TextField(style: kFieldTextStyle, ...)`.+TextStyle get kFieldTextStyle => _fieldTextStyle(AppPalette.textPrimary);++TextStyle _fieldTextStyle(Color color) => TextStyle(+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ fontSize: AppControl.fontSize,+ letterSpacing: AppFont.trackingFor(AppControl.fontSize),+ color: color,+);++/// A field's leading glyph — the magnifier on a search box, and its kind.+///+/// A step above [AppControl.iconSize], which is tuned to sit on the cap height+/// of a button's 13pt label. A field is [AppControl.heightField] tall, so the+/// button's glyph reads undersized in it — the icon has to follow the box it+/// sits in, not the token next to it. Themed via `prefixIconConstraints`, but+/// the `Icon` itself still has to be handed this size at the call site.+const double kFieldIconSize = 18;++RoundedRectangleBorder get _buttonShape => RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(AppControl.radius),+);++/// The primary action: a solid accent capsule.+/// A filled button that destroys something.+///+/// Exists so the three that do — the two connector confirms and the skill delete+/// — cannot each pick their own red and their own label colour. Before this they+/// had three answers between them, and all three failed in dark: two set white+/// on [AppPalette.dangerFill]'s predecessor (3.42:1) and one left the label to+/// Material (3.83:1).+///+/// `foregroundColor` is named rather than left to `colorScheme.onError`, which+/// this app's scheme never sets — so Material fills in its own and lands under+/// the floor.+ButtonStyle dangerButtonStyle() => FilledButton.styleFrom(+ backgroundColor: AppPalette.dangerFill,+ foregroundColor: Colors.white,+);++ButtonStyle _filledButtonStyle() => FilledButton.styleFrom(+ minimumSize: Size(0, AppControl.heightScaled),+ padding: AppControl.paddingScaled,+ shape: _buttonShape,+ textStyle: _buttonTextStyle,+ // Material pads every button out to a 48px tap target — on a desktop app+ // that leaves a 32px button floating in a 48px box and wrecks every row it+ // sits in.+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ visualDensity: VisualDensity.standard,+ // Its own wash, not [AppSurface.hoverFill]: this button already carries the+ // accent as a FILL, so the hover has to read against that rather than against+ // the page. White at 12% lifts the accent a step without turning it into a+ // second colour. See [_textButtonStyle] for why any of these are needed at+ // all — `NoSplash` took the ripple away and left nothing behind it.+ overlayColor: const Color(0x1FFFFFFF),+);++/// The secondary action: a hairline rim, no fill — Apple's "bordered" button.+ButtonStyle _outlinedButtonStyle(ColorScheme scheme) =>+ OutlinedButton.styleFrom(+ minimumSize: Size(0, AppControl.heightScaled),+ padding: AppControl.paddingScaled,+ shape: _buttonShape,+ textStyle: _buttonTextStyle,+ side: BorderSide(color: scheme.outline),+ foregroundColor: scheme.onSurface,+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ visualDensity: VisualDensity.standard,+ );++/// The tertiary action: text only, for the quiet way out of a dialog.+ButtonStyle _textButtonStyle() => TextButton.styleFrom(+ minimumSize: Size(0, AppControl.heightScaled),+ padding: AppControl.paddingSmallScaled,+ shape: _buttonShape,+ textStyle: _buttonTextStyle,+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ visualDensity: VisualDensity.standard,+ // ⚠️ Without this a text button has NO hover state at all.+ //+ // `splashFactory: NoSplash` turns Material's ripple off app-wide — right, it+ // is an Android idiom — but the ripple was also the only thing this theme+ // left drawing a response to the pointer. M3 derives its own overlay from+ // `foregroundColor`, and `styleFrom` here passes none, so the resolved+ // overlay came back **null**: the button lit up on press and on focus and did+ // nothing whatsoever on hover. On a desktop app, where the pointer is how you+ // find out what is clickable, that is a control that reads as a label.+ //+ // [AppSurface.hoverFill] is the same wash the rows and menu items already+ // use, so a button now answers the pointer the way everything around it does.+ overlayColor: AppSurface.hoverFill,+);++TextTheme _appTextTheme(Color primary, Color secondary) {+ final base = TextStyle(+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ color: primary,+ height: 1.34,+ fontWeight: AppFont.regular,+ );++ /// One step of the ramp, with its tracking derived from its size.+ TextStyle step(double size, {FontWeight? weight, Color? color}) =>+ base.copyWith(+ fontSize: size,+ fontWeight: weight,+ color: color,+ letterSpacing: AppFont.trackingFor(size),+ );++ // The ramp splits along one line: type that *is* a heading keeps semibold,+ // type that merely names a control drops to medium.+ //+ // Large sizes carry weight optically — 25pt at semibold is already emphatic,+ // and taking it to medium would leave a screen title reading as body copy that+ // happens to be big. Small sizes are the opposite: at 12–14pt semibold turns+ // into ink rather than emphasis, and it was on *every* label, so nothing was+ // emphasised relative to anything else.+ return TextTheme(+ displayLarge: step(57, weight: AppFont.semibold),+ displayMedium: step(45, weight: AppFont.semibold),+ displaySmall: step(36, weight: AppFont.semibold),+ headlineLarge: step(32, weight: AppFont.semibold),+ headlineMedium: step(29, weight: AppFont.semibold),+ headlineSmall: step(25, weight: AppFont.semibold),+ titleLarge: step(22, weight: AppFont.semibold),+ titleMedium: step(17, weight: AppFont.semibold),+ // 14.5 is where a "title" stops out-ranking anything and becomes a row+ // label, so this is the first step down.+ titleSmall: step(14.5, weight: AppFont.medium),+ bodyLarge: step(16.5),+ bodyMedium: step(15),+ bodySmall: step(13.5, color: secondary),+ // Every `label*` names a control. Medium, like the controls themselves.+ labelLarge: step(14.5, weight: AppFont.medium),+ labelMedium: step(13, weight: AppFont.medium),+ labelSmall: step(12, weight: AppFont.medium),+ );+}diff --git a/mobile/lib/shared/theme/appearance_prefs_store.dart b/mobile/lib/shared/theme/appearance_prefs_store.dartnew file mode 100644index 000000000..18d94af35--- /dev/null+++ b/mobile/lib/shared/theme/appearance_prefs_store.dart@@ -0,0 +1,209 @@+import 'package:flutter/foundation.dart';++import '../../core/harness_file_store.dart';+import '../../core/local_key_value_store.dart';+import 'app_theme.dart';+import 'color_palette.dart';++/// The app's coordinated palette and UI typography on this computer.+///+/// This does not change the terminal's type. The terminal renders a grid a remote+/// program draws into, so it keeps its own face and its own size in+/// [TerminalFontStore], reached from Settings ▸ Terminal — and the app's UI+/// scale is fenced out of it at five seams (see the notes in+/// `terminal_panel.dart` and `terminal_composer.dart`, and the regression test+/// in `test/terminal_ui_scale_isolation_test.dart`).+@immutable+class AppearancePrefs {+ const AppearancePrefs({+ this.uiFamily,+ this.uiSize = uiSizeDefault,+ this.palette = HarnessPalette.graphite,+ });++ final HarnessPalette palette;++ /// The face the app's chrome is set in. `null` means the system font, which is+ /// what [AppFont.sans] falls back to.+ ///+ /// Never the empty string. CoreText resolves `''` to nothing at all and the+ /// text simply disappears, so "use the system font" is represented by the+ /// absence of a value at every layer — here, and as a deleted key on disk.+ final String? uiFamily;++ /// The base size everything else is measured against, in logical pixels.+ final double uiSize;++ /// The size the app was drawn at. [AppFont.uiScale] is this over that, so at+ /// 14 the scale is exactly 1 and every control keeps the geometry the design+ /// system specifies.+ static const double uiSizeDefault = AppFont.uiSizeDefault;++ /// ⚠️ Not a matter of taste. A control here is a fixed-height box built for a+ /// 13pt label — [AppControl.height] 32, [AppControl.heightField] 36 — and past+ /// roughly ±35% the label stops fitting the box it sits in.+ static const double uiSizeMin = 11;+ static const double uiSizeMax = 19;++ /// [uiFamily] is nullable and `copyWith` cannot express "unset" with+ /// `?? this.x`, so going back to the system font needs its own flag. Without+ /// one, choosing System silently does nothing.+ AppearancePrefs copyWith({+ String? uiFamily,+ double? uiSize,+ HarnessPalette? palette,+ bool clearUiFamily = false,+ }) => AppearancePrefs(+ uiFamily: clearUiFamily ? null : (uiFamily ?? this.uiFamily),+ uiSize: uiSize ?? this.uiSize,+ palette: palette ?? this.palette,+ );++ @override+ bool operator ==(Object other) =>+ other is AppearancePrefs &&+ other.uiFamily == uiFamily &&+ other.uiSize == uiSize &&+ other.palette == palette;++ @override+ int get hashCode => Object.hash(uiFamily, uiSize, palette);+}++/// The user's appearance choices, remembered across launches.+///+/// Same shape as [TerminalFontStore]: a [ValueNotifier]+/// singleton over [HarnessFileStore], loaded once by `loadPersistedSettings()`+/// before the first frame. Not a Riverpod provider — `MaterialApp` is built+/// above every provider scope in this app, and these values have to resolve+/// before there is a scope at all.+class AppearancePrefsStore extends ValueNotifier<AppearancePrefs> {+ AppearancePrefsStore({LocalKeyValueStore? storage})+ : _storage = storage ?? HarnessFileStore.shared,+ super(const AppearancePrefs());++ static const _familyKey = 'app_ui_font_family';+ static const _sizeKey = 'app_ui_font_size';+ static const _paletteKey = 'app_color_palette';+ Future<void>? _paletteSave;++ final LocalKeyValueStore _storage;++ /// Read the saved choices, if there are any.+ ///+ /// Tolerant by design: a missing, truncated or hand-edited file lands on the+ /// defaults rather than throwing. Someone who opened `state.json` in an editor+ /// should get a plain-looking app, not an app that refuses to start.+ Future<void> load() async {+ try {+ final saved = await _storage.readMany([+ _familyKey,+ _sizeKey,+ _paletteKey,+ ]);+ value = AppearancePrefs(+ uiFamily: _familyFrom(saved[_familyKey]),+ uiSize: _sizeFrom(saved[_sizeKey]),+ palette: HarnessPalette.fromId(saved[_paletteKey]),+ );+ } catch (_) {+ value = const AppearancePrefs();+ }+ }++ /// Preview now, persist in order. Rapid choices coalesce while storage is+ /// busy so an older write cannot replace the user's final selection.+ Future<void> setPalette(HarnessPalette palette) {+ if (value.palette == palette) return _paletteSave ?? Future.value();+ value = value.copyWith(palette: palette);+ return _paletteSave ??= _savePalette();+ }++ Future<void> _savePalette() async {+ try {+ while (true) {+ final id = value.palette.name;+ await _storage.write(_paletteKey, id);+ if (value.palette.name == id) break;+ }+ } catch (_) {+ // The chosen palette remains usable for this run if storage fails.+ } finally {+ _paletteSave = null;+ }+ }++ /// Choose a face, or pass `null` for the system font.+ Future<void> setUiFamily(String? family) async {+ final next = _familyFrom(family);+ if (next == value.uiFamily) return;+ value = value.copyWith(uiFamily: next, clearUiFamily: next == null);+ try {+ if (next == null) {+ // Deleted, not written as ''. See [AppearancePrefs.uiFamily].+ await _storage.delete(_familyKey);+ } else {+ await _storage.write(_familyKey, next);+ }+ } catch (_) {+ // Kept for this run; a failed write costs the choice at next launch.+ }+ }++ /// Set the base size. Values outside the range snap to the nearest end rather+ /// than being rejected, so a caller never has to pre-validate.+ Future<void> setUiSize(double size) async {+ final next = _clampSize(size);+ if (next == value.uiSize) return;+ // The notifier moves first and the write is awaited after, so the window+ // repaints on the click rather than on the disk.+ value = value.copyWith(uiSize: next);+ try {+ await _storage.write(_sizeKey, next.toString());+ } catch (_) {+ // See above.+ }+ }++ /// Back to the shipped defaults.+ Future<void> reset() async {+ value = const AppearancePrefs();+ await _paletteSave;+ try {+ await _storage.delete(_familyKey);+ await _storage.delete(_sizeKey);+ await _storage.delete(_paletteKey);+ } catch (_) {+ // See above.+ }+ }++ /// ⚠️ Empty and blank strings become `null`, not a family name. CoreText+ /// resolves `''` to no face at all, and the app renders no text — a failure+ /// with no error attached to it.+ static String? _familyFrom(String? raw) {+ final trimmed = raw?.trim();+ return (trimmed == null || trimmed.isEmpty) ? null : trimmed;+ }++ static double _sizeFrom(String? raw) {+ final parsed = double.tryParse(raw ?? '');+ return parsed == null ? AppearancePrefs.uiSizeDefault : _clampSize(parsed);+ }++ /// ⚠️ The `isFinite` guard has to come BEFORE the clamp, not after.+ /// `double.tryParse('NaN')` succeeds, and `double.nan.clamp(11, 19)` returns+ /// 19 — so a hand-edited file saying `NaN` would silently pin the whole app at+ /// maximum size instead of falling back to the default.+ static double _clampSize(double size) => !size.isFinite+ ? AppearancePrefs.uiSizeDefault+ : size.clamp(AppearancePrefs.uiSizeMin, AppearancePrefs.uiSizeMax);+}++/// The one instance the app reads.+///+/// Here rather than beside `main()` for the same reason `terminalFontStore` is:+/// the widgets that change these values would otherwise have to reach up into+/// the app entrypoint, dragging `runApp` and every screen into anything that+/// renders them — tests included.+final appearancePrefsStore = AppearancePrefsStore();diff --git a/mobile/lib/shared/theme/color_palette.dart b/mobile/lib/shared/theme/color_palette.dartnew file mode 100644index 000000000..2a1bcf10b--- /dev/null+++ b/mobile/lib/shared/theme/color_palette.dart@@ -0,0 +1,105 @@+import 'package:flutter/painting.dart';++/// Coordinated workspace colors. These feed the existing design-system tokens,+/// native tabs/search, and terminal defaults; they do not change agent state.+enum HarnessPalette {+ graphite(+ 'Graphite',+ 'Neutral charcoal',+ background: Color(0xff181818),+ panel: Color(0xff141414),+ card: Color(0xff1e1e1e),+ hover: Color(0xff252525),+ workspace: Color(0xff282828),+ tabBar: Color(0xff1c1c1c),+ search: Color(0xff2c2c2c),+ accent: Color(0xffbdcbdc),+ ),+ dusk(+ 'Dusk',+ 'Soft plum',+ background: Color(0xff181818),+ panel: Color(0xff141414),+ card: Color(0xff1e1e1e),+ hover: Color(0xff252525),+ workspace: Color(0xff463746),+ tabBar: Color(0xff332936),+ search: Color(0xff3d333f),+ accent: Color(0xffd8cce1),+ ),+ midnight(+ 'Midnight',+ 'Deep indigo',+ background: Color(0xff171b29),+ panel: Color(0xff141722),+ card: Color(0xff202638),+ hover: Color(0xff2a3348),+ workspace: Color(0xff252d43),+ tabBar: Color(0xff1b2030),+ search: Color(0xff262f46),+ accent: Color(0xffb1c7f5),+ ),+ slate(+ 'Slate',+ 'Cool blue gray',+ background: Color(0xff222a35),+ panel: Color(0xff1b222c),+ card: Color(0xff2c3543),+ hover: Color(0xff374457),+ workspace: Color(0xff354153),+ tabBar: Color(0xff273140),+ search: Color(0xff344154),+ accent: Color(0xffbdd3e7),+ ),+ forest(+ 'Forest',+ 'Quiet evergreen',+ background: Color(0xff18231e),+ panel: Color(0xff141c18),+ card: Color(0xff202c25),+ hover: Color(0xff2a3a31),+ workspace: Color(0xff2b3b31),+ tabBar: Color(0xff1b2720),+ search: Color(0xff293a31),+ accent: Color(0xffb4d8be),+ ),+ ember(+ 'Ember',+ 'Warm earth',+ background: Color(0xff26201c),+ panel: Color(0xff1e1a17),+ card: Color(0xff312923),+ hover: Color(0xff3d342c),+ workspace: Color(0xff3d322a),+ tabBar: Color(0xff2b221d),+ search: Color(0xff3c3129),+ accent: Color(0xffe6c39e),+ );++ const HarnessPalette(+ this.label,+ this.description, {+ required this.background,+ required this.panel,+ required this.card,+ required this.hover,+ required this.workspace,+ required this.tabBar,+ required this.search,+ required this.accent,+ });++ final String label, description;+ final Color background, panel, card, hover, workspace, tabBar, search, accent;+ Color get foreground => const Color(0xfff5f5f5);++ static HarnessPalette fromId(String? id) =>+ values.where((palette) => palette.name == id).firstOrNull ?? graphite;++ Map<String, int> get nativeColors => {+ 'tabBar': tabBar.toARGB32(),+ 'workspace': workspace.toARGB32(),+ 'search': search.toARGB32(),+ 'accent': accent.toARGB32(),+ };+}diff --git a/mobile/lib/shared/widgets/app_dialog.dart b/mobile/lib/shared/widgets/app_dialog.dartnew file mode 100644index 000000000..22f8f50f9--- /dev/null+++ b/mobile/lib/shared/widgets/app_dialog.dart@@ -0,0 +1,174 @@+/// One way to open a dialog, so every dialog in the app stands on the same+/// veil.+///+/// Material's `showDialog` can only TINT what is behind a dialog —+/// `barrierColor` is a flat fill, and this app's background is terminals. Dimmed+/// text is still text: at any alpha that keeps the window feeling alive, the+/// lines behind a panel stay legible enough to read, and a reader's eye goes on+/// picking words out of them instead of settling on the thing that just opened.+///+/// So the barrier is BUILT rather than coloured — a [BackdropFilter] under a+/// tint, the pairing `task_palette.dart` already uses for its own veil. Blur+/// destroys the letterforms; the tint then sets the depth. Together they make+/// what is behind read as *behind*.+library;++import 'dart:ui' show ImageFilter;++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++/// How far the app blurs what sits behind a dialog.+///+/// ⚠️ Bounded on purpose. A terminal is high-contrast text on a dark ground,+/// and far enough past this the glyphs stop reading as letters at all and+/// become a grey haze that looks like a rendering fault rather than depth. 7+/// is where a line behind the panel is unmistakably gone while the window+/// still reads as the window.+const double kDialogVeilBlur = 7;++/// Shared dark backdrop for dialogs and centered pickers. Terminal output+/// stays in the background while the active surface has the user's attention.+const Color kDialogVeilTint = Color(0xE6000000);++/// The app's dialog barrier: a blur, then a tint, then whatever opened.+///+/// Use it in place of `showDialog` wherever a panel should take the window's+/// full attention. It keeps `showDialog`'s shape — the same `builder`,+/// `barrierDismissible` and return type — so a call site changes by its name+/// alone.+///+/// ⚠️ [barrierDismissible] is wired by hand, because the real barrier is+/// transparent: Material dismisses on a tap only when it draws the barrier+/// itself, and this one is a widget. The [GestureDetector] below is what keeps+/// a tap outside working, and `maybePop` rather than `pop` so a route that+/// refuses to leave (an unsaved form, say) still gets to refuse.+Future<T?> showAppDialog<T>({+ required BuildContext context,+ required WidgetBuilder builder,+ bool barrierDismissible = true,+ String barrierLabel = 'Dismiss',+ Color veilTint = kDialogVeilTint,+ double veilBlur = kDialogVeilBlur,+ Duration transitionDuration = const Duration(milliseconds: 140),+}) => showGeneralDialog<T>(+ context: context,+ // The route's own barrier draws nothing: the veil below is the barrier.+ barrierColor: Colors.transparent,+ // Kept FALSE whatever the caller asked, and handled in the tree instead —+ // see the note above. Left true, Material would dismiss on a tap anywhere+ // over a barrier it believes is there, including a tap on the dialog.+ barrierDismissible: false,+ barrierLabel: barrierLabel,+ transitionDuration: transitionDuration,+ pageBuilder: (context, _, _) => _AppDialogVeil(+ tint: veilTint,+ blur: veilBlur,+ dismissible: barrierDismissible,+ child: Builder(builder: builder),+ ),+ transitionBuilder: (context, anim, _, child) => FadeTransition(+ opacity: CurvedAnimation(parent: anim, curve: Curves.easeOut),+ child: child,+ ),+);++/// The veil, and the dialog standing on it.+class _AppDialogVeil extends StatelessWidget {+ const _AppDialogVeil({+ required this.tint,+ required this.blur,+ required this.dismissible,+ required this.child,+ });++ final Color tint;+ final double blur;+ final bool dismissible;+ final Widget child;++ @override+ Widget build(BuildContext context) => _DismissOnEscape(+ enabled: dismissible,+ child: Stack(+ children: [+ Positioned.fill(+ child: GestureDetector(+ // `opaque`, so a tap on the veil is taken here rather than falling+ // through to whatever the window has underneath — a terminal would+ // otherwise get the click that was meant to close the panel.+ behavior: HitTestBehavior.opaque,+ onTap: dismissible ? () => Navigator.of(context).maybePop() : null,+ child: blur == 0+ ? ColoredBox(color: tint)+ : BackdropFilter(+ filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),+ child: ColoredBox(color: tint),+ ),+ ),+ ),+ // ⚠️ The dialog is NOT inside the GestureDetector above: nested in it,+ // a tap on the panel itself would close the panel.+ child,+ ],+ ),+ );+}++/// Closes the dialog on Escape.+///+/// ⚠️ **This exists because `showAppDialog` passes `barrierDismissible: false`+/// to the route, and that flag is not only about taps.** Flutter wires the+/// Escape key off the same flag: a modal route built with it false installs no+/// `DismissIntent` handler, so Escape reaches nothing. The barrier here is a+/// widget rather than the route's own, so the flag has to stay false — leaving+/// it true makes Material dismiss on a tap anywhere over a barrier it believes+/// it is drawing, the panel included — and the key has to be put back by hand,+/// exactly as the tap was.+///+/// It was missed when the tap was wired, and every dialog in the app lost+/// Escape with it — including the ones whose own chrome draws an `esc` cap.+///+/// `maybePop`, matching the tap: a route that refuses to leave still gets to+/// refuse.+class _DismissOnEscape extends StatelessWidget {+ const _DismissOnEscape({required this.enabled, required this.child});++ /// False leaves the key alone, so a dialog that opted out of tap-dismissal+ /// is not quietly closable by keyboard instead.+ final bool enabled;++ final Widget child;++ @override+ Widget build(BuildContext context) {+ if (!enabled) return child;+ return Shortcuts(+ shortcuts: const {+ SingleActivator(LogicalKeyboardKey.escape): DismissIntent(),+ },+ child: Actions(+ actions: {+ DismissIntent: CallbackAction<DismissIntent>(+ onInvoke: (_) {+ Navigator.of(context).maybePop();+ return null;+ },+ ),+ },+ // A `Shortcuts` only sees a key once focus is somewhere inside it, and+ // not every dialog focuses something of its own — so the scope takes+ // focus itself when nothing else claims it.+ //+ // ⚠️ `Focus`, not `FocusScope`. Both autofocus, and a descendant that+ // also autofocuses (the model picker's search field) wins either way —+ // but a `FocusScope` additionally becomes the dialog's focus ROOT,+ // which changes where traversal wraps and what `unfocus` falls back+ // to. Nothing here wants to move those; this only needs to be a node+ // in the chain that holds focus when no descendant asks for it.+ // `skipTraversal` keeps it out of the tab order it is not a stop in.+ child: Focus(autofocus: true, skipTraversal: true, child: child),+ ),+ );+ }+}diff --git a/mobile/lib/shared/widgets/app_icon_button.dart b/mobile/lib/shared/widgets/app_icon_button.dartnew file mode 100644index 000000000..d774bd42e--- /dev/null+++ b/mobile/lib/shared/widgets/app_icon_button.dart@@ -0,0 +1,217 @@+import 'package:flutter/material.dart';++import '../theme/app_theme.dart';++/// A small icon affordance that lifts under the pointer.+///+/// Material's [IconButton] is unusable raw here for the same reason+/// `MenuItemButton` is: the app defines no `iconButtonTheme`, so a bare one+/// takes Material's defaults — a 48px tap target padded around a 40px circle,+/// an ink ripple the app disables everywhere else, and, worst, **no hover+/// treatment at all** beyond a faint circular overlay. Its glyph keeps its+/// resting ink while the pointer sits on it, which reads as decoration rather+/// than something you can press.+///+/// This is the formula the rest of the app uses (`_MenuTrigger` in+/// `project_menu.dart`, `_ChatMenuItem` in `chat_header.dart`): the glyph climbs+/// to [AppPalette.textPrimary] and [AppSurface.hoverFill] lays in behind it.+///+/// ### Owning its own hover matters+///+/// A row that already lightens on hover (an `ExtensionTileSurface`) does **not**+/// tell the button inside it where the pointer is. Without its own+/// [MouseRegion] the button stays at rest for the whole time it's hovered, and+/// without its own [fill] the user can't tell "on the row" from "on the button".+/// Both halves were live bugs before this widget existed.+class AppIconButton extends StatefulWidget {+ const AppIconButton({+ super.key,+ required this.icon,+ required this.onPressed,+ this.tooltip,+ this.size = 15,+ this.color,+ this.hoverColor,+ this.hoverFill,+ this.destructive = false,+ this.spinning = false,+ });++ final IconData icon;+ final VoidCallback? onPressed;+ final String? tooltip;++ /// The glyph turns, and the button stops taking presses.+ ///+ /// For a control whose work the user cannot otherwise see finishing — the+ /// rail's reload, which fires a REST call and an `agents_list` per open+ /// machine and may take a second or two over a slow relay. Greying it out+ /// would say "unavailable", which is the wrong word: it is *working*, and+ /// the turn is what says so.+ ///+ /// Kept separate from a null [onPressed] on purpose. Disabled draws+ /// [AppPalette.textFaint]; a spinning button keeps its resting ink, because+ /// it is about to be pressable again.+ final bool spinning;++ /// Glyph size. 15 is the inline default — a ✕ that clears a field, a dismiss+ /// on a row. A dialog's own close is 18, the size the app draws it at.+ final double size;++ /// Resting ink. Defaults to [AppPalette.textSecondary].+ final Color? color;++ /// Hovered ink. Defaults to [AppPalette.textPrimary] — the climb *is* the+ /// affordance. Ignored when [destructive] is set.+ final Color? hoverColor;++ /// The lift behind the glyph on hover. Defaults to [AppSurface.hoverFill],+ /// which follows the app's theme.+ ///+ /// Overridden only by chrome that deliberately does **not** follow it — the+ /// bar and rulers around a document page, which stay light in dark mode the+ /// way the page itself does (see [AppPalette.paper]). Without this the glyph+ /// and the fill answer to two different themes, and a light toolbar lifts its+ /// buttons with a wash mixed for charcoal.+ final Color? hoverFill;++ /// Hover turns the *glyph* red, over the same neutral fill every other button+ /// gets.+ ///+ /// For a button that deletes: the neutral lift is honest about where the+ /// pointer is but says nothing about what pressing would do, and this is the+ /// one control on a row that doesn't undo.+ ///+ /// The red is not `colorScheme.error` in dark. Measured against the hover fill+ /// (`#3A3A3A` — the button's overlay on top of the row's own):+ ///+ /// ```+ /// dark error #F2544B = 3.33 : 1 ← under 4.5+ /// dark [_dangerDark] = 4.98 : 1+ /// light error #B3261E = 5.23 : 1 ← fine as-is+ /// ```+ ///+ /// So light uses the token and dark uses a lighter tint of the same hue —+ /// the same trick `AppPalette.accentOnSurface` plays for the accent, and for+ /// the same reason: a colour tuned as a *fill* is too dark to be *ink* on a+ /// dark surface.+ ///+ /// Resting state stays neutral — a column of red buttons sitting at rest+ /// reads as an error state rather than a list of models.+ final bool destructive;++ /// The dark-theme danger ink: `colorScheme.error` lightened until it clears+ /// 4.5:1 on the hover fill, while still reading unmistakably red.+ static const Color _dangerDark = Color(0xFFFF8A80);++ /// The button's box. Kept a touch larger than the glyph so the hover fill+ /// reads as a pill around it rather than a tight halo.+ static const double _box = 24;++ /// 7 — the app's radius for a small inline button (`ghost_button.dart`,+ /// `chat_header.dart`), and never rounder than the 8 of a control it sits in.+ static const double _radius = 7;++ @override+ State<AppIconButton> createState() => _AppIconButtonState();+}++class _AppIconButtonState extends State<AppIconButton>+ with SingleTickerProviderStateMixin {+ bool _hovered = false;++ /// One turn. Slow enough to read as deliberate rather than as a busy+ /// indicator thrashing, fast enough that a reload finishing inside a single+ /// revolution still looks like it moved.+ static const Duration _spinPeriod = Duration(milliseconds: 900);++ late final AnimationController _spin = AnimationController(+ vsync: this,+ duration: _spinPeriod,+ );++ @override+ void initState() {+ super.initState();+ if (widget.spinning) _spin.repeat();+ }++ @override+ void didUpdateWidget(AppIconButton oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (widget.spinning == oldWidget.spinning) return;+ if (widget.spinning) {+ _spin.repeat();+ } else {+ // Let the current revolution land instead of stopping the glyph at+ // whatever angle the reply happened to arrive at. A mark frozen at 200°+ // reads as a failure state; one that comes to rest upright reads as done.+ _spin+ .animateTo(1, duration: _spinPeriod * (1 - _spin.value))+ .whenComplete(() {+ if (mounted && !widget.spinning) _spin.value = 0;+ });+ }+ }++ @override+ void dispose() {+ _spin.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context); // reads AppPalette/AppSurface tokens.+ // Spinning does not grey the glyph out, but it does stop the press: the+ // work the last one asked for is still running.+ final enabled = widget.onPressed != null && !widget.spinning;+ final pressable = widget.onPressed != null;+ final resting = widget.color ?? AppPalette.textSecondary;+ // Only the glyph changes. The fill stays the same neutral lift every other+ // button gets, so a destructive button reads as *the same affordance* the+ // rest of the app uses — just saying, in its ink, what it would do.+ final danger = AppTheme.pick(+ Theme.of(context).colorScheme.error,+ AppIconButton._dangerDark,+ );+ final active = widget.destructive+ ? danger+ : (widget.hoverColor ?? AppPalette.textPrimary);++ final button = MouseRegion(+ cursor: enabled ? SystemMouseCursors.click : MouseCursor.defer,+ onEnter: (_) => setState(() => _hovered = true),+ onExit: (_) => setState(() => _hovered = false),+ child: GestureDetector(+ onTap: enabled ? widget.onPressed : null,+ child: AnimatedContainer(+ duration: AppMotion.hover,+ curve: AppMotion.curve,+ width: AppIconButton._box,+ height: AppIconButton._box,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: _hovered && enabled+ ? (widget.hoverFill ?? AppSurface.hoverFill)+ : Colors.transparent,+ borderRadius: BorderRadius.circular(AppIconButton._radius),+ ),+ child: RotationTransition(+ turns: _spin,+ child: Icon(+ widget.icon,+ size: widget.size,+ color: pressable+ ? (_hovered && enabled ? active : resting)+ : AppPalette.textFaint,+ ),+ ),+ ),+ ),+ );++ final tooltip = widget.tooltip;+ return tooltip == null ? button : Tooltip(message: tooltip, child: button);+ }+}diff --git a/mobile/lib/shared/widgets/app_menu.dart b/mobile/lib/shared/widgets/app_menu.dartnew file mode 100644index 000000000..ac97e2d95--- /dev/null+++ b/mobile/lib/shared/widgets/app_menu.dart@@ -0,0 +1,337 @@+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../theme/app_theme.dart';++/// The measurements one [AppMenuItem] is built from.+///+/// TWO sizes exist in this app, deliberately, and the distinction is worth+/// stating because two sizes is otherwise exactly the drift this file was+/// written to end:+///+/// [compact] — a CONTEXT menu. A short list of actions on the thing you just+/// right-clicked or pressed ⋯ on: the machine and agent menus, the account+/// menu. macOS sets these tight, and they are read in a glance.+///+/// [roomy] — a PICKER's list. The menu IS the control: it is the only place+/// the choices are ever shown, it is read down rather than glanced at, and it+/// is often long enough to scroll. macOS gives a popup button's list more room+/// than a context menu for the same reason.+///+/// A third size would be drift. Reach for one of these two.+@immutable+class AppMenuRowMetrics {+ const AppMenuRowMetrics({+ required this.fontSize,+ required this.noteSize,+ required this.iconSize,+ required this.padding,+ required this.extent,+ });++ final double fontSize;+ final double noteSize;+ final double iconSize;+ final EdgeInsets padding;++ /// The height a row of this size actually lays out at.+ ///+ /// ⚠️ MEASURED, not derived, and the difference has already cost a bug. Adding+ /// the paddings up for [compact] gives 33.6; a laid-out row measures 34.0,+ /// because the line box rounds up to the font's own metrics rather than taking+ /// `fontSize × height` literally. Over seven rows that 0.4 became 2.8 — enough+ /// to overflow a panel sized from the arithmetic and hang a scrollbar on it.+ ///+ /// `app_select_field_test.dart` measures a real row against this to 0.1, so a+ /// padding that moves without this moving fails a test rather than quietly+ /// mis-sizing every panel.+ final double extent;++ /// What a row with a [AppMenuItem.detail] line lays out at instead.+ ///+ /// [extent] plus the second line's own box — [noteSize] × 1.25, rounded up+ /// the same way a line box rounds, plus the 2px that separates the two lines.+ /// Stated rather than derived at the call site for the same reason [extent]+ /// is: a panel sized by arithmetic that disagrees with the layout by half a+ /// pixel per row wears a scrollbar it does not need.+ double get detailExtent => extent + noteSize * 1.25 + 2;++ /// A context menu's row: the macOS control scale.+ static const compact = AppMenuRowMetrics(+ fontSize: 13,+ noteSize: 11.5,+ iconSize: 16,+ padding: EdgeInsets.symmetric(horizontal: 9, vertical: 8),+ extent: 34,+ );++ /// A picker's row — one step up on every axis at once, which is the only way+ /// to change a platform convention without breaking the proportions inside it.+ static const roomy = AppMenuRowMetrics(+ fontSize: 14,+ noteSize: 12.5,+ iconSize: 18,+ padding: EdgeInsets.symmetric(horizontal: 11, vertical: 10),+ extent: 40,+ );+}++/// The height one [AppMenuItem] occupies.+///+/// Stated so a caller that has to SIZE a panel — see [AppSelectField] — can do+/// the arithmetic up front instead of discovering at runtime that its list+/// overflows by a few pixels and wears a scrollbar for no reason.+///+/// ⚠️ MEASURED, not derived, and the difference matters. Adding the paddings up+///+/// outer 1 × 2 = 2 · inner 8 × 2 = 16 · line 13 × 1.2 = 15.6 → 33.6+///+/// gives 33.6, which is WRONG: a laid-out row measures 34.0, because the line+/// box rounds up to the font's own metrics rather than taking `fontSize ×+/// height` literally. Over seven rows that 0.4 becomes 2.8 — the width of the+/// mistake that put a scrollbar on the engine picker in the first place.+///+/// `app_select_field_test.dart` measures a real row against this to 0.1, so if+/// a padding moves and this does not, a test says so.+const double kMenuRowExtent = 34.0;+// (kept as the compact row's extent; see AppMenuRowMetrics.compact.extent)++/// One row in an [AppMenu] panel.+///+/// The panel itself is no longer built here: it lives on [AppMenu] in+/// `app_theme.dart`, and `menuTheme` hands it to every `MenuAnchor` in the app,+/// so a menu that passes no style gets the same surface as one that does. The+/// hand-written `appMenuStyle()` this file used to export was the second of four+/// disagreeing recipes — see that class.+///+/// Hand-rolled rather than a [MenuItemButton] because the app has no+/// `menuButtonTheme`, so a bare one takes Material's M3 defaults and lands+/// wrong on four counts at once: radius 0, 14pt text, a grey 8% hover, and a+/// ripple every other menu here has turned off.+///+/// Stateful for its own hover: the glyph has to climb to [AppPalette.textPrimary]+/// under the pointer. An icon that stays dim while the cursor sits on it reads+/// as decoration, and nothing above this row tracks hover per-row to do it.+class AppMenuItem extends StatefulWidget {+ const AppMenuItem({+ super.key,+ this.icon,+ required this.label,+ required this.onPressed,+ this.danger = false,+ this.selected = false,+ this.note,+ this.detail,+ this.leading,+ this.trailing,+ this.focusNode,+ this.metrics = AppMenuRowMetrics.compact,+ });++ /// The leading glyph. Null for a row in a list that PICKS one of several — the+ /// slot is still reserved, so labels line up whether a row is ticked or not.+ final IconData? icon;+ final String label;++ /// A quieter qualifier after the label — a face name beside "System". Set+ /// apart by ink rather than by a separator character, so it reads as an aside+ /// instead of as part of the name.+ final String? note;++ /// A mark at the row's far end, after [note] — a state the row has rather+ /// than a word about it.+ ///+ /// For a fact that repeats down a list, where the same short phrase on every+ /// other row turns the column into noise the eye has to re-read. A glyph is+ /// scanned once. Give it a [Tooltip]: a mark carries no meaning to a reader+ /// meeting it for the first time, and there is nowhere else in a menu row to+ /// put the sentence.+ final Widget? trailing;+ final FocusNode? focusNode;++ /// A quiet SECOND LINE under the label, for a row whose label alone does not+ /// say what picking it does — "Most tokens read in the last 24h" under+ /// "Input tokens", "That, plus…" under a role.+ ///+ /// Distinct from [note], which sits *beside* the label and qualifies the same+ /// noun ("System — SF Pro"). A sentence cannot go there: a menu is as wide as+ /// its button, and the qualifier would arrive clipped to its first three+ /// words. So this row grows a line instead of the panel growing a column.+ ///+ /// It makes the row taller, which is why a caller that has to SIZE a panel+ /// asks [AppMenuRowMetrics.detailExtent] rather than [AppMenuRowMetrics.extent].+ final String? detail;++ /// A mark that belongs to the ROW's subject rather than to its action — an+ /// engine's logo, say. It gets a slot of its own AFTER the tick's, so the tick+ /// still has somewhere to go and a picked row's label does not shift sideways+ /// from an unpicked one's.+ final Widget? leading;++ /// Which of the two row sizes this is. Defaults to a context menu's; a picker+ /// passes [AppMenuRowMetrics.roomy].+ final AppMenuRowMetrics metrics;++ /// This row is the current choice.+ ///+ /// Marked THREE ways, never by one: an accent wash, a heavier label, and a+ /// tick in the leading slot. Colour alone fails anyone who cannot separate+ /// these two greys, and a tick alone is easy to miss in a long list.+ final bool selected;++ final VoidCallback onPressed;++ /// Tints the row red and gives it a red hover wash — for the row that+ /// destroys something.+ final bool danger;++ @override+ State<AppMenuItem> createState() => _AppMenuItemState();+}++class _AppMenuItemState extends State<AppMenuItem> {+ bool _hovered = false;++ @override+ Widget build(BuildContext context) {+ // Lives in the MenuAnchor's overlay, so it watches for itself.+ AppTheme.watch(context);+ final error = Theme.of(context).colorScheme.error;+ // A danger row is already red at rest, so it deepens rather than climbs.+ final tint = widget.danger+ ? error+ : (_hovered || widget.selected+ ? AppPalette.textPrimary+ : AppPalette.textSecondary);+ // The tick takes the leading slot when this row is the choice; otherwise the+ // row's own glyph does, and a row with neither keeps the slot EMPTY.+ //+ // ⚠️ Empty means an empty box, not `Icons.check_box_outline_blank`. That+ // glyph draws a real outlined square — which turns a pick-one menu into what+ // reads as a checkbox list, and puts a border somewhere §1 does not allow+ // one. It shipped that way once; this comment is why it will not again.+ final glyph = widget.selected ? LucideIcons.check300 : widget.icon;++ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),+ child: Material(+ color: Colors.transparent,+ borderRadius: BorderRadius.circular(8),+ child: InkWell(+ focusNode: widget.focusNode,+ onTap: widget.onPressed,+ onHover: (hovered) => setState(() => _hovered = hovered),+ borderRadius: BorderRadius.circular(8),+ hoverColor: widget.danger+ ? error.withValues(alpha: 0.09)+ : AppSurface.hoverFill,+ focusColor: AppSurface.hoverFill,+ splashFactory: NoSplash.splashFactory,+ child: Ink(+ decoration: BoxDecoration(+ color: widget.selected+ ? AppSurface.accentWash+ : Colors.transparent,+ borderRadius: BorderRadius.circular(8),+ ),+ padding: widget.metrics.padding,+ child: Row(+ children: [+ // Fixed slot: these glyphs differ in width, and without it every+ // label would start at a slightly different column — and a+ // ticked row would sit a few pixels off an unticked one.+ SizedBox(+ width: widget.metrics.iconSize,+ child: glyph == null+ ? null+ : Icon(glyph, size: widget.metrics.iconSize, color: tint),+ ),+ const SizedBox(width: 9),+ if (widget.leading != null) ...[+ SizedBox(+ width: widget.metrics.iconSize,+ child: Center(child: widget.leading),+ ),+ const SizedBox(width: 9),+ ],+ Flexible(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ widget.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: widget.danger ? error : AppPalette.textPrimary,+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ fontSize: widget.metrics.fontSize,+ height: 1.2,+ fontWeight: widget.selected+ ? AppFont.semibold+ : AppFont.medium,+ ),+ ),+ if (widget.detail case final detail?) ...[+ const SizedBox(height: 2),+ Text(+ detail,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: AppPalette.textSecondary,+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ fontSize: widget.metrics.noteSize,+ height: 1.25,+ ),+ ),+ ],+ ],+ ),+ ),+ if (widget.note != null) ...[+ const SizedBox(width: 8),+ Flexible(+ child: Text(+ widget.note!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: AppPalette.textFaint,+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ fontSize: widget.metrics.noteSize,+ height: 1.2,+ ),+ ),+ ),+ ],+ if (widget.trailing != null) ...[+ const SizedBox(width: 8),+ widget.trailing!,+ ],+ ],+ ),+ ),+ ),+ ),+ );+ }+}++/// The rule that sets a destructive row apart from the ordinary ones.+class AppMenuDivider extends StatelessWidget {+ const AppMenuDivider({super.key});++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 5),+ child: Divider(height: 1, thickness: 1, color: AppPalette.divider),+ );+ }+}diff --git a/mobile/lib/shared/widgets/app_select_field.dart b/mobile/lib/shared/widgets/app_select_field.dartnew file mode 100644index 000000000..8a51d216d--- /dev/null+++ b/mobile/lib/shared/widgets/app_select_field.dart@@ -0,0 +1,469 @@+import 'dart:math' as math;++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../theme/app_theme.dart';+import 'app_menu.dart';++/// One choice in an [AppSelectField].+@immutable+class SelectOption<T> {+ const SelectOption({+ required this.value,+ required this.label,+ this.note,+ this.detail,+ this.leading,+ this.trailing,+ });++ final T value;+ final String label;++ /// A sentence UNDER the label, for a list whose labels alone do not say what+ /// picking one does.+ ///+ /// Distinct from [note], which sits beside the label and qualifies the same+ /// noun. A sentence cannot go there: the closed field is only as wide as the+ /// control, so it would arrive clipped mid-clause. Shown in the OPEN menu+ /// only, which is where it is needed — while choosing, not after.+ final String? detail;++ /// A mark shown before the label, in the row AND in the closed control — an+ /// engine's logo, a colour swatch. Built fresh per use rather than shared, so+ /// the same option can appear in both places.+ final Widget Function()? leading;++ /// A short qualifier shown after the label in quieter ink — "SF Pro" beside+ /// "System", or a warning that a saved choice is no longer installed.+ final String? note;++ /// A mark at the row's far end. Built fresh per use, like [leading].+ ///+ /// For a state that recurs down the list, where the same words on several+ /// rows read as noise. Only in the open list: the closed control shows the+ /// chosen option's [note], and a glyph there would have to explain itself+ /// with no room to.+ final Widget Function()? trailing;+}++/// A control that picks one of a list, replacing [DropdownButtonFormField].+///+/// Material's dropdown is unusable here: it renders its own popup, anchors it+/// *over* the field rather than under it, forces the panel to the field's width,+/// and comes out square-cornered and edge-to-edge no matter what `borderRadius`,+/// `elevation` or `dropdownColor` you hand it — while ignoring BOTH `menuTheme`+/// and `popupMenuTheme`, so it cannot be made to match any other menu in the+/// app. Built on [MenuAnchor] instead, it takes [AppMenu]'s panel like every+/// other menu here and its rows are the app's own [AppMenuItem].+///+/// ⚠️ There is no disabled row, deliberately. A choice that is visible but+/// silently does nothing is worse than a choice that is absent — so a caller+/// with an unavailable option should drop it from [options] rather than hope+/// for a greyed-out row. The exception worth making is the option that is+/// currently SELECTED but no longer available: that one stays, with a [note]+/// saying why, because a picker that silently forgets the user's setting is the+/// same failure wearing a different hat.+class AppSelectField<T> extends StatefulWidget {+ const AppSelectField({+ super.key,+ required this.value,+ required this.options,+ required this.onChanged,+ this.width,+ this.height = AppControl.height,+ this.trigger,+ });++ final T value;+ final List<SelectOption<T>> options;+ final ValueChanged<T> onChanged;++ /// Fixed width, so a column of these lines up on one right edge. Null lets it+ /// take whatever its parent gives.+ final double? width;+ final double height;++ /// An alternate compact trigger, such as the agent picker's More button.+ /// Selection, keyboard navigation and menu rows remain shared.+ final Widget? trigger;++ @override+ State<AppSelectField<T>> createState() => _AppSelectFieldState<T>();+}++class _AppSelectFieldState<T> extends State<AppSelectField<T>> {+ final _controller = MenuController();+ final _fieldFocus = FocusNode(debugLabel: 'Select field');+ final _optionFocus = <T, FocusNode>{};+ ({T value})? _pendingFocus;+ String _prefix = '';+ Duration? _lastTyped;+ bool _focusScheduled = false;+ bool _hovered = false;+ bool _focused = false;++ FocusNode _focusFor(T value) => _optionFocus.putIfAbsent(+ value,+ () => FocusNode(debugLabel: 'Select option'),+ );++ SelectOption<T>? get _currentOption =>+ widget.options+ .where((option) => option.value == widget.value)+ .firstOrNull ??+ widget.options.firstOrNull;++ @override+ void didUpdateWidget(AppSelectField<T> oldWidget) {+ super.didUpdateWidget(oldWidget);+ final values = widget.options.map((option) => option.value).toSet();+ var lostFocus = false;+ for (final value in _optionFocus.keys.toList()) {+ if (values.contains(value)) continue;+ final node = _optionFocus.remove(value)!;+ lostFocus |= node.hasFocus || _pendingFocus?.value == value;+ node.dispose();+ }+ if (!_controller.isOpen || !lostFocus) return;+ _prefix = '';+ _lastTyped = null;+ final next = _currentOption;+ if (next == null) {+ _controller.close();+ } else {+ _focusOption(next);+ }+ }++ @override+ void dispose() {+ _fieldFocus.dispose();+ for (final node in _optionFocus.values) {+ node.dispose();+ }+ super.dispose();+ }++ void _open() {+ if (widget.options.isEmpty || _controller.isOpen) return;+ _prefix = '';+ _lastTyped = null;+ _controller.open();+ // Unopened controls need no per-option focus nodes. Mount them with the+ // menu, including any match typed before its first frame.+ setState(() {});+ _focusOption(_currentOption!, afterLayout: true);+ }++ void _focusOption(SelectOption<T> option, {bool afterLayout = false}) {+ _pendingFocus = (value: option.value);+ final node = _focusFor(option.value);+ if (!afterLayout &&+ !_focusScheduled &&+ node.parent != null &&+ node.context?.mounted == true) {+ node.requestFocus();+ Scrollable.ensureVisible(node.context!);+ return;+ }+ // Opening and typing can happen before the menu's first frame. Keep the+ // newest match, rather than restoring the old selection after it mounts.+ if (_focusScheduled) return;+ _focusScheduled = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ _focusScheduled = false;+ if (!mounted || !_controller.isOpen) return;+ final pending = _pendingFocus;+ if (pending == null) return;+ final node = _optionFocus[pending.value];+ if (node?.context == null) return;+ node!.requestFocus();+ Scrollable.ensureVisible(node.context!);+ });+ }++ int get _highlightedIndex {+ final focused = widget.options.indexWhere(+ (option) => _optionFocus[option.value]?.hasPrimaryFocus == true,+ );+ if (focused >= 0) return focused;+ final pending = _pendingFocus;+ return pending == null+ ? -1+ : widget.options.indexWhere((option) => option.value == pending.value);+ }++ void _choose(SelectOption<T> option) {+ _controller.close();+ _fieldFocus.requestFocus();+ if (option.value != widget.value) widget.onChanged(option.value);+ }++ KeyEventResult _typeAhead(FocusNode _, KeyEvent event) {+ if (!_controller.isOpen || event is KeyUpEvent) {+ return KeyEventResult.ignored;+ }+ final keyboard = HardwareKeyboard.instance;+ if (keyboard.isMetaPressed ||+ keyboard.isControlPressed ||+ keyboard.isAltPressed) {+ return KeyEventResult.ignored;+ }+ if (!keyboard.isShiftPressed) {+ if (event.logicalKey == LogicalKeyboardKey.escape) {+ _controller.close();+ _fieldFocus.requestFocus();+ return KeyEventResult.handled;+ }+ if (event.logicalKey == LogicalKeyboardKey.enter ||+ event.logicalKey == LogicalKeyboardKey.numpadEnter) {+ final index = _highlightedIndex;+ if (index >= 0) _choose(widget.options[index]);+ return KeyEventResult.handled;+ }+ }+ final text = event.character?.toLowerCase();+ if (text == null ||+ text.isEmpty ||+ text.runes.any((r) => r < 32 || r == 127)) {+ _prefix = '';+ return KeyEventResult.ignored;+ }+ if (_lastTyped == null ||+ event.timeStamp < _lastTyped! ||+ event.timeStamp - _lastTyped! > const Duration(seconds: 1)) {+ _prefix = '';+ }+ if (text == ' ' && _prefix.isEmpty) return KeyEventResult.ignored;+ _lastTyped = event.timeStamp;+ final continuing = _prefix.isNotEmpty && _prefix != text;+ _prefix = continuing ? _prefix + text : text;+ final current = _highlightedIndex;+ final start = current < 0 ? 0 : current + (continuing ? 0 : 1);+ for (var offset = 0; offset < widget.options.length; offset++) {+ final option = widget.options[(start + offset) % widget.options.length];+ if (option.label.trimLeft().toLowerCase().startsWith(_prefix)) {+ _focusOption(option);+ break;+ }+ }+ return KeyEventResult.handled;+ }++ Widget _typingRegion(Widget child, {Key? key}) => Focus(+ key: key,+ canRequestFocus: false,+ skipTraversal: true,+ onKeyEvent: _typeAhead,+ child: child,+ );++ /// How tall this panel may draw.+ ///+ /// ⚠️ NOT [AppControl.menuMaxHeight]. That token's 240 is for a menu that+ /// opens UPWARD and places itself by summing the height it is about to take;+ /// this one hangs below its field, so it is free to be as tall as its own+ /// list. Left at 240, a seven-item picker overflowed by five pixels and grew+ /// a scrollbar to show them — furniture that says "there is more here" when+ /// there is not.+ ///+ /// The ceiling is still real: past it a long list scrolls instead of running+ /// off the window.+ double get _panelHeight => math.min(+ // A row with a detail line is TALLER, and the difference has to be counted+ // per row rather than assumed for all of them: a list where only some+ // options carry a sentence would otherwise be measured wrong in whichever+ // direction the guess went, and a panel that disagrees with its layout by a+ // few pixels wears a scrollbar it does not need.+ widget.options.fold<double>(+ 0,+ (total, option) =>+ total ++ (option.detail == null+ ? AppMenuRowMetrics.roomy.extent+ : AppMenuRowMetrics.roomy.detailExtent),+ ) ++ AppMenu.panelPadding.vertical,+ _maxPanelHeight,+ );++ static const double _maxPanelHeight = 380;++ /// A floor under the panel's width, on top of the field's own.+ ///+ /// A field can be narrow — the font picker's is 188 — while its list holds+ /// names that are not. The panel is where the choosing happens, so it is+ /// allowed to be wider than the box it drops out of; the reverse, a panel+ /// narrower than its control, is what reads as an unrelated box.+ static const double _minPanelWidth = 240;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final selected = widget.options.where((o) => o.value == widget.value);+ final current = selected.isEmpty ? null : selected.first;++ // The panel is measured against the FIELD, not against its own contents: a+ // menu narrower than the control it drops out of reads as an unrelated box+ // that happened to open nearby. `widget.width` covers a fixed-size field;+ // the incoming constraint covers one that fills its parent — the case in a+ // dialog, and the one that was missed.+ return LayoutBuilder(+ builder: (context, constraints) => _anchor(+ current,+ widget.width ??+ (constraints.maxWidth.isFinite ? constraints.maxWidth : null),+ ),+ );+ }++ Widget _anchor(SelectOption<T>? current, double? panelWidth) {+ return MenuAnchor(+ controller: _controller,+ childFocusNode: _fieldFocus,+ onClose: () {+ _prefix = '';+ _lastTyped = null;+ _pendingFocus = null;+ },+ // Below the control, by the app's one menu gap — and the panel takes its+ // fill, rim and radius from [AppMenu], the app's single panel recipe.+ alignmentOffset: const Offset(0, AppControl.menuGap),+ // ⚠️ The width is set on the ROWS, not with `MenuStyle.minimumSize`.+ //+ // `minimumSize` does widen the panel, but `MenuAnchor` lays its children+ // out loose, so the rows keep their intrinsic width and sit in a wider box+ // — measured at 173 inside a panel asked for 240, which reads as a menu+ // with a mysterious margin down one side. Sizing the row makes the panel+ // follow it, and the hover pill then spans the width a person is aiming+ // at.+ style: AppMenu.style(maxHeight: _panelHeight),+ menuChildren: [+ for (final option in widget.options)+ _typingRegion(+ SizedBox(+ width: math.max(panelWidth ?? 0, _minPanelWidth),+ child: AppMenuItem(+ // No glyph of its own: the leading slot belongs to the tick,+ // and stays empty (not a blank checkbox) on rows without it.+ // `selected` also carries the wash and the heavier label, so the+ // choice is marked three ways rather than by a tick alone.+ // A picker's list, not a context menu's: this menu IS the+ // control, it is read down rather than glanced at, and it is the+ // only place these choices are ever shown.+ metrics: AppMenuRowMetrics.roomy,+ focusNode: _controller.isOpen ? _focusFor(option.value) : null,+ selected: option.value == widget.value,+ label: option.label,+ note: option.note,+ detail: option.detail,+ leading: option.leading?.call(),+ trailing: option.trailing?.call(),+ onPressed: () => _choose(option),+ ),+ ),+ key: ValueKey(option.value),+ ),+ ],+ builder: (context, controller, _) => _typingRegion(+ MouseRegion(+ cursor: SystemMouseCursors.click,+ onEnter: (_) => setState(() => _hovered = true),+ onExit: (_) => setState(() => _hovered = false),+ child: CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.arrowDown): _open,+ const SingleActivator(LogicalKeyboardKey.arrowUp): _open,+ },+ child: InkWell(+ focusNode: _fieldFocus,+ onFocusChange: (value) => setState(() => _focused = value),+ onTap: () => controller.isOpen ? controller.close() : _open(),+ splashFactory: NoSplash.splashFactory,+ hoverColor: Colors.transparent,+ focusColor: Colors.transparent,+ borderRadius: BorderRadius.circular(AppControl.radius),+ child: AnimatedContainer(+ duration: AppMotion.hover,+ curve: AppMotion.curve,+ width: widget.width,+ height: widget.height,+ padding: const EdgeInsets.only(left: 10, right: 8),+ decoration: BoxDecoration(+ color: _hovered || _focused || controller.isOpen+ ? AppSurface.recessHover+ : AppSurface.recess,+ borderRadius: BorderRadius.circular(AppControl.radius),+ border: Border.all(+ color: _focused+ ? AppPalette.accentOnSurface+ : Colors.transparent,+ ),+ ),+ child:+ widget.trigger ??+ Row(+ children: [+ Expanded(+ child: Row(+ children: [+ if (current?.leading != null) ...[+ current!.leading!(),+ const SizedBox(width: 8),+ ],+ Flexible(+ child: Text(+ current?.label ?? '—',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ fontSize: AppControl.fontSize,+ fontWeight: AppControl.fontWeight,+ letterSpacing: AppFont.trackingFor(+ AppControl.fontSize,+ ),+ color: AppPalette.textPrimary,+ ),+ ),+ ),+ if (current?.note != null) ...[+ const SizedBox(width: 8),+ Flexible(+ child: Text(+ current!.note!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ fontSize: 11.5,+ color: AppPalette.textFaint,+ ),+ ),+ ),+ ],+ ],+ ),+ ),+ const SizedBox(width: 6),+ Icon(+ Icons.expand_more_rounded,+ size: AppControl.iconSize,+ color: _hovered || controller.isOpen+ ? AppPalette.textPrimary+ : AppPalette.textSecondary,+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/lib/shared/widgets/command_row.dart b/mobile/lib/shared/widgets/command_row.dartnew file mode 100644index 000000000..d75db9803--- /dev/null+++ b/mobile/lib/shared/widgets/command_row.dart@@ -0,0 +1,57 @@+import 'package:flutter/material.dart';++import '../../theme/app_theme.dart';+import '../theme/app_theme.dart' as grid;++/// A single-line shell command with a copy affordance: tap anywhere on the row to copy, the trailing+/// icon flips to a checkmark for a moment to confirm. Shared by any screen that hands the user a+/// command to run themselves (`harness_join_guide_screen.dart`, `environment_setup_screen.dart`).+class CommandRow extends StatelessWidget {+ final String command;+ final bool copied;+ final VoidCallback onCopy;++ const CommandRow({+ super.key,+ required this.command,+ required this.copied,+ required this.onCopy,+ });++ @override+ Widget build(BuildContext context) {+ return InkWell(+ onTap: onCopy,+ borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),+ child: Container(+ width: double.infinity,+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ decoration: BoxDecoration(+ color: AppColors.background,+ border: Border.all(color: AppColors.border),+ borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),+ ),+ child: Row(+ children: [+ Text('\$ ', style: TextStyle(color: AppColors.mutedStrong)),+ Expanded(+ child: SelectableText(+ command,+ style: TextStyle(+ color: AppColors.text,+ fontFamily: AppFonts.mono,+ fontSize: 13,+ ),+ ),+ ),+ Icon(+ copied ? Icons.check : Icons.copy,+ size: 16,+ color: copied ? AppColors.success : AppColors.mutedStrong,+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/lib/shared/widgets/empty_state.dart b/mobile/lib/shared/widgets/empty_state.dartnew file mode 100644index 000000000..cf50eb9f9--- /dev/null+++ b/mobile/lib/shared/widgets/empty_state.dart@@ -0,0 +1,91 @@+import 'package:flutter/material.dart';++import '../theme/app_theme.dart';++/// "There's nothing here (yet)."+///+/// The app grew at least fourteen private one-off versions of this — `_Empty`+/// four times, `_NoAgent` three, plus `_NoJobs`, `_NoResults`, `_NoMatches`,+/// `_NoMatch`, `_NoGrid`, `_NoSelection`, `_NothingServedYet`, `_NoModelYet`.+/// Same idea every time, all `_`-private, so none could be reused and each drew+/// its icon at a different size.+///+/// Two flavours worth keeping distinct:+/// - *nothing exists yet* → give the user the action that creates the first one+/// ([action]).+/// - *nothing matches the filter* → no action; the fix is to change the query.+class EmptyState extends StatelessWidget {+ const EmptyState({+ super.key,+ required this.icon,+ required this.title,+ this.message,+ this.action,+ this.compact = false,+ });++ final IconData icon;+ final String title;++ /// One quiet line under the title. Keep it to a sentence.+ final String? message;++ /// The action that makes the emptiness go away — "New agent", "Add plugin".+ final Widget? action;++ /// Tightens the spacing for an empty state inside a card or a narrow column+ /// rather than a whole pane.+ final bool compact;++ /// Nothing matched the current search or filter. Deliberately actionless.+ const EmptyState.noMatches({super.key, this.message, this.compact = true})+ : icon = Icons.search_off_rounded,+ title = 'No matches',+ action = null;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Center(+ child: Padding(+ padding: EdgeInsets.all(compact ? 16 : 32),+ child: Column(+ mainAxisAlignment: MainAxisAlignment.center,+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(icon, size: compact ? 24 : 32, color: AppPalette.textFaint),+ SizedBox(height: compact ? 10 : 14),+ Text(+ title,+ textAlign: TextAlign.center,+ style: TextStyle(+ color: AppPalette.textPrimary,+ fontSize: compact ? 13 : 14.5,+ fontWeight: FontWeight.w600,+ ),+ ),+ if (message != null) ...[+ const SizedBox(height: 6),+ ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 320),+ child: Text(+ message!,+ textAlign: TextAlign.center,+ style: TextStyle(+ color: AppPalette.textSecondary,+ fontSize: compact ? 12 : 13,+ height: 1.4,+ ),+ ),+ ),+ ],+ if (action != null) ...[+ SizedBox(height: compact ? 12 : 18),+ action!,+ ],+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/lib/shared/widgets/pulse.dart b/mobile/lib/shared/widgets/pulse.dartnew file mode 100644index 000000000..a232c06d8--- /dev/null+++ b/mobile/lib/shared/widgets/pulse.dart@@ -0,0 +1,128 @@+import 'package:flutter/material.dart';++/// The app's one "still alive" rhythm.+///+/// `t` runs 0 → 1 → 0 forever on an ease-in-out curve; [builder] turns it+/// into whatever the caller is breathing — a skeleton's fill, a dot's alpha.+/// This widget owns the *timing* and nothing about the *shape*, which is what+/// lets every long-running thing in the app beat at the same tempo instead of+/// each pane hand-rolling its own `AnimationController`. That animation had+/// been written three separate times (the status LED, the login mark, the+/// model pill) and only two honoured Reduce Motion — the same heartbeat at+/// three tempos, one of them still moving for someone who had asked it to+/// stop.+///+/// Two decisions live here so no call site has to remember them:+///+/// - **Reduce Motion stops the beat at the peak (`t = 1`), not the middle.**+/// A block frozen at 40% opacity reads as *disabled*, which is the opposite+/// of what a placeholder means.+/// - **The [RepaintBoundary] is inside.** Everything built on this is+/// long-running by definition, and the shell keeps rail, bar and pane in one+/// layer — without the boundary a breathing skeleton in the sidebar repaints+/// the terminal beside it sixty times a second.+class Pulse extends StatefulWidget {+ const Pulse({+ super.key,+ required this.builder,+ this.duration = const Duration(milliseconds: 1600),+ this.curve = Curves.easeInOut,+ this.child,+ });++ /// Called with `t` in `[0, 1]`. [child] is passed through untouched so a+ /// subtree that does not depend on `t` is built once.+ final Widget Function(BuildContext context, double t, Widget? child) builder;++ /// One half of the cycle — rest to peak. The whole breath is twice this.+ ///+ /// 1600ms is the status LED's blink, which is what the bare default serves.+ /// A skeleton asks for 1100 explicitly; slower reads as calmer, and the two+ /// are different instruments rather than one drifting.+ final Duration duration;++ final Curve curve;+ final Widget? child;++ @override+ State<Pulse> createState() => _PulseState();+}++class _PulseState extends State<Pulse> with SingleTickerProviderStateMixin {+ late final AnimationController _controller = AnimationController(+ vsync: this,+ duration: widget.duration,+ );+ late final Animation<double> _t = CurvedAnimation(+ parent: _controller,+ curve: widget.curve,+ );++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ if (MediaQuery.disableAnimationsOf(context)) {+ _controller+ ..stop()+ ..value = 1;+ } else if (!_controller.isAnimating) {+ _controller.repeat(reverse: true);+ }+ }++ @override+ void didUpdateWidget(covariant Pulse oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.duration != widget.duration) {+ _controller.duration = widget.duration;+ if (_controller.isAnimating) _controller.repeat(reverse: true);+ }+ }++ @override+ void dispose() {+ _controller.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => RepaintBoundary(+ child: AnimatedBuilder(+ animation: _t,+ child: widget.child,+ builder: (context, child) => widget.builder(context, _t.value, child),+ ),+ );+}++/// A soft-glowing dot that blinks to signal "live" — the status LED used by the+/// playground pill and anywhere else a thing is running.+class PulseDot extends StatelessWidget {+ const PulseDot({super.key, required this.color, this.size = 6});++ final Color color;+ final double size;++ @override+ Widget build(BuildContext context) {+ return Pulse(+ builder: (context, t, _) {+ final opacity = 0.4 + 0.6 * t;+ return Container(+ width: size,+ height: size,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: color.withValues(alpha: opacity),+ boxShadow: [+ BoxShadow(+ color: color.withValues(alpha: 0.5 * opacity),+ blurRadius: size * 0.85,+ ),+ ],+ ),+ );+ },+ );+ }+}diff --git a/mobile/lib/shared/widgets/skeleton.dart b/mobile/lib/shared/widgets/skeleton.dartnew file mode 100644index 000000000..1cc3eb164--- /dev/null+++ b/mobile/lib/shared/widgets/skeleton.dart@@ -0,0 +1,338 @@+import 'package:flutter/material.dart';++import '../theme/app_theme.dart';+import 'pulse.dart';++/// Placeholders for content whose *shape* is already known.+///+/// A skeleton beats a spinner when you know what is coming: the layout does+/// not jump when the data lands, and what the reader waits on reads as "your+/// rows are on their way" rather than "something is happening somewhere". The+/// converse holds too — shape unknown, use a spinner; do not invent one.+///+/// Four rules every skeleton in the app keeps, in order of how often they are+/// broken elsewhere:+///+/// 1. **The rhythm is an opacity breath, not a shimmer sweep.** [Pulse] owns+/// it; a light band wiping across a pane fights the app's quiet.+/// 2. **A placeholder wears the real content's metrics.** One pixel off and it+/// causes the very jump it exists to prevent — which is why [SkeletonText]+/// measures the line box of the style it stands in for instead of guessing.+/// 3. **A block fades towards its bottom** ([skeletonFade]), so it reads as+/// "more below" rather than a wall cut off mid-list.+/// 4. **Line widths differ.** Equal bars turn a cluster into one grey slab.+///+/// The fill is [AppSurface.recess] breathing up to [AppSurface.recessHover]:+/// a translucent *well*, not a solid. A skeleton sits on top of a card, so it+/// borrows the token for a hollow rather than the card's own fill — it has to+/// read as an absence — and an overlay rides any ground (page, card, dialog)+/// without being re-measured against it.+class Skeleton extends StatelessWidget {+ const Skeleton({+ super.key,+ this.width,+ this.height = 12,+ this.radius = 6,+ this.shape = BoxShape.rectangle,+ });++ /// A round placeholder — an avatar, a status dot.+ ///+ /// ⚠️ Only for slots that ARE round. A 10-radius badge wants a 10-radius+ /// [Skeleton], or the one detail that changes shape when data lands is the+ /// one the eye catches.+ const Skeleton.circle({super.key, required double size})+ : width = size,+ height = size,+ radius = 0,+ shape = BoxShape.circle;++ /// A line of text: the tighter radius the app's type scale wants.+ const Skeleton.text({super.key, this.width, this.height = 12})+ : radius = 4,+ shape = BoxShape.rectangle;++ /// Null stretches to the parent.+ final double? width;+ final double height;+ final double radius;+ final BoxShape shape;++ @override+ Widget build(BuildContext context) {+ // Tokens are getters against a global brightness; nothing here depends on+ // Theme.of, so the widget has to register for a flip itself.+ AppTheme.watch(context);+ final rest = AppSurface.recess;+ final peak = AppSurface.recessHover;+ return Pulse(+ // Stated, not inherited: [Pulse]'s bare default is the status LED's+ // blink, and a placeholder breathes faster than a light does.+ duration: const Duration(milliseconds: 1100),+ builder: (context, t, _) => Container(+ width: width,+ height: height,+ decoration: BoxDecoration(+ color: Color.lerp(rest, peak, t),+ borderRadius: shape == BoxShape.rectangle+ ? BorderRadius.circular(radius)+ : null,+ shape: shape,+ ),+ ),+ );+ }+}++/// A text line as a fraction of the row it sits in.+///+/// Fractions, not pixels, so a set of lines keeps its proportions in a 284px+/// menu and a 900px table alike. Needs a bounded width from its parent.+class SkeletonLine extends StatelessWidget {+ const SkeletonLine({super.key, this.widthFactor = 1, this.height = 12});++ final double widthFactor;+ final double height;++ @override+ Widget build(BuildContext context) => FractionallySizedBox(+ alignment: Alignment.centerLeft,+ widthFactor: widthFactor,+ child: Skeleton.text(height: height),+ );+}++/// A text line that occupies exactly the line box of [style].+///+/// The bar is drawn shorter than the line — text has ascenders and descenders+/// a solid block does not — but the box it reserves is measured from the+/// style with a real [TextPainter], under the ambient [DefaultTextStyle] and+/// text scaler. That is what makes a skeleton row and a real row the same+/// height whatever font the fallback chain lands on: read a height off the+/// code and you get the arithmetic, which [AppMenuRowMetrics] documents is+/// wrong by a fraction of a pixel per line.+///+/// Give it a [width] (pixels) or a [widthFactor] (share of a bounded parent);+/// with neither it fills the parent.+class SkeletonText extends StatelessWidget {+ const SkeletonText({+ super.key,+ required this.style,+ this.width,+ this.widthFactor,+ this.barHeight,+ this.strutStyle,+ this.alignment = Alignment.centerLeft,+ }) : assert(+ width == null || widthFactor == null,+ 'Give a width or a widthFactor, not both',+ );++ /// The style of the text this stands in for. Only the metrics are read.+ final TextStyle style;++ /// Matched to the real text's strut when it pins one — a sidebar row's label+ /// does, and a skeleton measured without it lands a pixel short.+ final StrutStyle? strutStyle;++ final double? width;+ final double? widthFactor;++ /// Bar thickness. Defaults to roughly the x-height of [style], which is+ /// where the ink of a real line is densest.+ final double? barHeight;++ final AlignmentGeometry alignment;++ /// The height of one line of [style] under [context]'s text settings.+ static double lineHeight(+ BuildContext context,+ TextStyle style, {+ StrutStyle? strutStyle,+ }) {+ final resolved = DefaultTextStyle.of(context).style.merge(style);+ final painter = TextPainter(+ text: TextSpan(text: 'X', style: resolved),+ strutStyle: strutStyle,+ textDirection: Directionality.maybeOf(context) ?? TextDirection.ltr,+ textScaler: MediaQuery.textScalerOf(context),+ maxLines: 1,+ )..layout();+ final height = painter.height;+ painter.dispose();+ return height;+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final height = lineHeight(context, style, strutStyle: strutStyle);+ final fontSize =+ style.fontSize ?? DefaultTextStyle.of(context).style.fontSize ?? 14;+ final bar = barHeight ?? (fontSize * 0.72).roundToDouble().clamp(6.0, 16.0);+ Widget line = Skeleton.text(width: width, height: bar);+ if (width == null) {+ line = FractionallySizedBox(+ alignment: alignment,+ widthFactor: widthFactor ?? 1,+ child: line,+ );+ }+ return SizedBox(+ height: height,+ width: width,+ child: Align(alignment: alignment, child: line),+ );+ }+}++/// How faint row `i` of `rows` should be.+///+/// The default (0.65) is for a long list pane; a short menu or popover uses+/// the gentler [light] so three rows do not end at a whisper.+double skeletonFade(int i, int rows, {double depth = 0.65}) =>+ rows <= 0 ? 1 : 1 - (i / rows) * depth;++/// The gentler fade for a block that is capped short — a menu, a popover.+const double skeletonFadeLight = 0.5;++/// One list row: a round or square leading slot and two lines of unequal+/// width (0.42 / 0.68), the shape of most "icon + name + summary" rows.+///+/// Wear the real row's surface and padding around this — a bare skeleton+/// list draws grey bars with no home on the page ground, and the cards then+/// *appear* when data lands, which is exactly the shift a skeleton exists to+/// prevent.+class SkeletonListTile extends StatelessWidget {+ const SkeletonListTile({+ super.key,+ this.leading = 30,+ this.leadingRadius,+ this.subtitle = true,+ this.titleFactor = 0.42,+ this.subtitleFactor = 0.68,+ this.padding = const EdgeInsets.symmetric(vertical: 8),+ });++ /// Size of the leading slot; 0 for none.+ final double leading;++ /// Null draws a circle; a value draws a rounded square with that radius —+ /// match the real badge.+ final double? leadingRadius;++ final bool subtitle;+ final double titleFactor;+ final double subtitleFactor;+ final EdgeInsets padding;++ @override+ Widget build(BuildContext context) => Padding(+ padding: padding,+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (leading > 0) ...[+ leadingRadius == null+ ? Skeleton.circle(size: leading)+ : Skeleton(+ width: leading,+ height: leading,+ radius: leadingRadius!,+ ),+ const SizedBox(width: 12),+ ],+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ SkeletonLine(widthFactor: titleFactor, height: 13),+ if (subtitle) ...[+ const SizedBox(height: 6),+ SkeletonLine(widthFactor: subtitleFactor, height: 11),+ ],+ ],+ ),+ ),+ ],+ ),+ );+}++/// A column of [rows] placeholders, already faded towards the bottom and+/// deaf to the pointer.+///+/// [itemBuilder] gets the row index and builds its shape; the default is a+/// [SkeletonListTile]. Pick [rows] from what it replaces, not from habit: a+/// long list pane wants 5–7, a capped block (dialog, popover) wants 3 — a+/// skeleton *taller* than the list it stands in for causes an upward jump,+/// which is worse than a downward one.+class SkeletonList extends StatelessWidget {+ const SkeletonList({+ super.key,+ this.rows = 5,+ this.itemBuilder,+ this.fadeDepth = 0.65,+ this.padding = EdgeInsets.zero,+ this.semanticsLabel = 'Loading',+ });++ final int rows;+ final IndexedWidgetBuilder? itemBuilder;+ final double fadeDepth;+ final EdgeInsetsGeometry padding;+ final String semanticsLabel;++ @override+ Widget build(BuildContext context) => SkeletonBlock(+ semanticsLabel: semanticsLabel,+ // A scroll view that cannot scroll: it is the one container that neither+ // overflows a short pane (an `Expanded` on a small window) nor demands a+ // bounded height (a dialog that shrink-wraps its content).+ child: SingleChildScrollView(+ physics: const NeverScrollableScrollPhysics(),+ padding: padding,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ for (var i = 0; i < rows; i++)+ Opacity(+ opacity: skeletonFade(i, rows, depth: fadeDepth),+ child: itemBuilder?.call(context, i) ?? const SkeletonListTile(),+ ),+ ],+ ),+ ),+ );+}++/// What every composite skeleton is wrapped in: no pointer, no hover, one+/// semantics node that says "loading".+///+/// A placeholder that scrolls under the cursor or lights up on hover reads+/// as real content, and a screen reader walking twelve empty bars learns+/// nothing it could not learn from one label.+class SkeletonBlock extends StatelessWidget {+ const SkeletonBlock({+ super.key,+ required this.child,+ this.semanticsLabel = 'Loading',+ });++ final Widget child;+ final String semanticsLabel;++ @override+ Widget build(BuildContext context) => Semantics(+ label: semanticsLabel,+ liveRegion: false,+ container: true,+ child: ExcludeSemantics(+ child: IgnorePointer(+ child: MouseRegion(cursor: SystemMouseCursors.basic, child: child),+ ),+ ),+ );+}diff --git a/mobile/lib/shortcuts/app_keymap.dart b/mobile/lib/shortcuts/app_keymap.dartnew file mode 100644index 000000000..da6a58d98--- /dev/null+++ b/mobile/lib/shortcuts/app_keymap.dart@@ -0,0 +1,244 @@+import 'dart:io';++import 'package:flutter/widgets.dart';++import 'app_shortcuts.dart';+import 'keymap.dart';+import 'keymap_commands.dart';+import 'keymap_store.dart';++/// A window's configuration, injectable so tests never read a user's dotfiles.+class AppKeymap extends ChangeNotifier {+ AppKeymap({this.store}) {+ store?.addListener(_changed);+ }+ final KeymapStore? store;+ int version = 0;+ ResolvedKeymap get current => store?.current ?? harnessDefaultKeymap;+ String? get error => store?.error;+ String? get path => store?.file.path;+ void _changed() {+ version++;+ notifyListeners();+ }++ Future<void> start() async {+ await store?.start();+ }++ static KeymapStore fileStore() => KeymapStore(+ file: File(KeymapStore.defaultPath()),+ defaults: harnessDefaultBindings,+ commands: harnessCommandById.keys.toSet(),+ validate: (map) => validateNativeKeys(map, macOS: Platform.isMacOS),+ );++ Iterable<KeyBinding> bindings(+ String command, {+ KeymapContext context = KeymapContext.workspace,+ }) => current+ .bindingsFor(context)+ .where((binding) => binding.command == command);++ String? hint(+ String command, {+ KeymapContext context = KeymapContext.workspace,+ }) {+ final binding = bindings(command, context: context).firstOrNull;+ return binding == null ? null : describeKeyBinding(binding);+ }++ /// These are names of actual AppKit commands, not all system shortcuts.+ /// Native editing is dispatched before Flutter, including sequence suffixes.+ static void validateNativeKeys(ResolvedKeymap map, {required bool macOS}) {+ if (!macOS) return;+ final reserved = {+ for (final chord in [+ 'cmd+q',+ 'cmd+m',+ 'cmd+alt+h',+ 'cmd+ctrl+f',+ 'cmd+c',+ 'cmd+v',+ 'cmd+x',+ 'cmd+a',+ 'cmd+z',+ 'cmd+shift+z',+ 'cmd+alt+shift+v',+ 'cmd+backquote',+ 'cmd+shift+backquote',+ 'cmd+0',+ 'cmd+equal',+ 'cmd+shift+equal',+ 'cmd+minus',+ ])+ KeyStroke.parse(chord),+ };+ for (final context in KeymapContext.values) {+ for (final binding in map.bindingsFor(context)) {+ final conflict = binding.keys.where(reserved.contains).firstOrNull;+ if (binding.custom && conflict != null) {+ throw FormatException(+ '$conflict belongs to a native Mac editing, font or window command; choose another key',+ );+ }+ }+ }+ }++ @override+ void dispose() {+ store?.removeListener(_changed);+ super.dispose();+ }+}++/// InheritedTheme lets dialogs/routes carry the same live configuration.+/// The provider rebuilds only on config changes, never on individual keys.+class KeymapProvider extends StatelessWidget {+ const KeymapProvider({super.key, required this.keymap, required this.child});+ final AppKeymap keymap;+ final Widget child;+ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: keymap,+ builder: (context, _) =>+ KeymapTheme(keymap: keymap, version: keymap.version, child: child),+ );+}++class KeymapTheme extends InheritedTheme {+ const KeymapTheme({+ super.key,+ required this.keymap,+ required this.version,+ required super.child,+ });+ final AppKeymap keymap;+ final int version;+ static AppKeymap? of(BuildContext context, {bool listen = true}) =>+ (listen+ ? context.dependOnInheritedWidgetOfExactType<KeymapTheme>()+ : context.getInheritedWidgetOfExactType<KeymapTheme>())+ ?.keymap;+ @override+ bool updateShouldNotify(KeymapTheme oldWidget) =>+ keymap != oldWidget.keymap || version != oldWidget.version;+ @override+ Widget wrap(BuildContext context, Widget child) =>+ KeymapProvider(keymap: keymap, child: child);+}++/// Pickers provide their own actions. A terminal only changes scope/IME state;+/// the containing workspace continues to own its navigation commands.+class KeymapRegion extends InheritedWidget {+ const KeymapRegion({+ super.key,+ required this.contextKind,+ this.actions,+ this.composing,+ required super.child,+ });+ final KeymapContext contextKind;+ final Map<String, VoidCallback>? actions;+ final bool Function()? composing;+ static KeymapRegion? of(BuildContext context) =>+ context.getInheritedWidgetOfExactType<KeymapRegion>();+ @override+ bool updateShouldNotify(KeymapRegion oldWidget) => false;+}++String? effectiveShortcutHint(BuildContext context, ShortcutAction action) {+ final command = harnessCommands+ .where((command) => command.action == action)+ .firstOrNull;+ final map = KeymapTheme.of(context);+ if (command == null) return null;+ final binding = (map?.current ?? harnessDefaultKeymap)+ .bindingsFor(KeymapContext.workspace)+ .where((binding) => binding.command == command.id)+ .firstOrNull;+ return binding == null ? null : describeKeyBinding(binding);+}++String withEffectiveShortcutHint(+ BuildContext context,+ String label,+ ShortcutAction action,+) {+ final hint = effectiveShortcutHint(context, action);+ return hint == null ? label : '$label $hint';+}++String? effectiveCommandHint(+ BuildContext context,+ String command, {+ KeymapContext contextKind = KeymapContext.workspace,+}) {+ final bindings = (KeymapTheme.of(context)?.current ?? harnessDefaultKeymap)+ .bindingsFor(contextKind);+ final binding = bindings+ .where((binding) => binding.command == command)+ .firstOrNull;+ return binding == null ? null : describeKeyBinding(binding);+}++List<ShortcutRow> effectiveShortcutRows(+ BuildContext context,+ KeymapContext contextKind,+) {+ final map = KeymapTheme.of(context)?.current;+ if (map == null && contextKind == KeymapContext.workspace) {+ return shortcutRows();+ }+ final bindings = (map ?? harnessDefaultKeymap).bindingsFor(contextKind);+ final defaultDigits =+ contextKind != KeymapContext.picker &&+ List.generate(kTabDigitCount, (i) {+ final matches = bindings+ .where((b) => b.command == 'swarm.select_${i + 1}')+ .toList();+ return matches.length == 1 &&+ matches.single.keys.length == 1 &&+ matches.single.keys.single == KeyStroke.parse('cmd+${i + 1}');+ }).every((value) => value);+ final shortcuts = appShortcuts();+ return [+ for (final command in harnessCommands)+ if ((command.context == KeymapContext.workspace ||+ command.context == contextKind) &&+ (!defaultDigits ||+ !RegExp(r'^swarm\.select_[1-9]$').hasMatch(command.id)))+ if (command.action != null ||+ bindings.any((b) => b.command == command.id))+ ShortcutRow(+ label:+ shortcuts+ .where((s) => s.action == command.action)+ .firstOrNull+ ?.label ??+ command.label,+ chords: [+ for (final binding in bindings.where(+ (b) => b.command == command.id,+ ))+ binding.keys.length == 1+ ? describeKeyStrokeKeys(binding.keys.single)+ : [+ describeKeyBinding(binding)+ .replaceAll('↵', 'Return')+ .replaceAll('⇥', 'Tab'),+ ],+ ],+ group: command.group,+ ),+ if (defaultDigits)+ const ShortcutRow(+ label: 'Select tabs 1–9',+ chords: [+ ['⌘', '1 – 9'],+ ],+ group: ShortcutGroup.navigate,+ ),+ ];+}diff --git a/mobile/lib/shortcuts/app_shortcuts.dart b/mobile/lib/shortcuts/app_shortcuts.dartnew file mode 100644index 000000000..1440e12c4--- /dev/null+++ b/mobile/lib/shortcuts/app_shortcuts.dart@@ -0,0 +1,632 @@+import 'package:flutter/services.dart';+import 'package:flutter/widgets.dart';++import '../logging/debug_surface.dart';++/// Harness uses Command as a direct prefix for frequent workspace actions.+/// T opens a tab, N creates a harness, O finds one, S changes layout,+/// H/J/K/L and arrows focus panes, B routes a task, D splits down and R splits+/// right. The same definitions feed live keys, help and search.+///+/// Unclaimed input stays with the focused agent or text field. Composition,+/// copy/paste and the coding agent's own prompt editing must keep working.+/// AppKit's Edit menu has no competing equivalents for C/V/X/A, and Hide has+/// no H equivalent: Flutter owns editing and Harness owns Command-H navigation.+/// Menu clicks still use their usual responder-chain actions.++enum ShortcutAction {+ newSwarm,+ closeSwarm,+ reopenClosedSwarm,+ showHistory,+ renameSwarm,+ nextSwarm,+ previousSwarm,+ showSettings,+ toggleRail,+ nextAgent,+ previousAgent,+ focusPaneLeft,+ focusPaneRight,+ focusPaneAbove,+ focusPaneBelow,+ movePaneLeft,+ movePaneRight,+ movePaneUp,+ movePaneDown,++ /// The agent this window was on before the current one — tmux's `prefix ;`.+ lastPane,++ /// One pane filling the grid, and back. tmux's `prefix z`.+ zoomPane,++ /// Find a live question and jump to the agent waiting for input.+ showAttention,++ findTerminal,+ findNext,+ findPrevious,++ /// Add an agent to the current swarm, independently of navigation.+ addAgent,++ closePane,+ newAgent,+ routeTask,+ reload,+ showLayout,+ pinPane,+ showShortcuts,+ showDebug,+}++enum ShortcutGroup { navigate, panes, actions }++extension ShortcutGroupLabel on ShortcutGroup {+ String get label => switch (this) {+ ShortcutGroup.navigate => 'Workspace',+ ShortcutGroup.panes => 'Panes',+ ShortcutGroup.actions => 'Actions',+ };+}++class AppShortcut {+ const AppShortcut({+ required this.action,+ required this.activator,+ required this.label,+ required this.group,+ });++ final ShortcutAction action;+ final SingleActivator activator;+ final String label;+ final ShortcutGroup group;+}++const List<AppShortcut> kAppShortcuts = [+ AppShortcut(+ action: ShortcutAction.findTerminal,+ activator: SingleActivator(LogicalKeyboardKey.keyF, meta: true),+ label: 'Find in the focused terminal',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.findNext,+ activator: SingleActivator(LogicalKeyboardKey.keyG, meta: true),+ label: 'Next terminal match',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.findPrevious,+ activator: SingleActivator(+ LogicalKeyboardKey.keyG,+ meta: true,+ shift: true,+ ),+ label: 'Previous terminal match',+ group: ShortcutGroup.navigate,+ ),+ // --- navigate -------------------------------------------------------------+ //+ // Command-arrows and H/J/K/L focus panes; bare keys stay with the terminal.+ AppShortcut(+ action: ShortcutAction.focusPaneLeft,+ activator: SingleActivator(LogicalKeyboardKey.keyH, meta: true),+ label: 'Focus the pane to the left',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.focusPaneBelow,+ activator: SingleActivator(LogicalKeyboardKey.keyJ, meta: true),+ label: 'Focus the pane below',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.focusPaneAbove,+ activator: SingleActivator(LogicalKeyboardKey.keyK, meta: true),+ label: 'Focus the pane above',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.focusPaneRight,+ activator: SingleActivator(LogicalKeyboardKey.keyL, meta: true),+ label: 'Focus the pane to the right',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.focusPaneLeft,+ activator: SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true),+ label: 'Focus the pane to the left',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.focusPaneBelow,+ activator: SingleActivator(LogicalKeyboardKey.arrowDown, meta: true),+ label: 'Focus the pane below',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.focusPaneAbove,+ activator: SingleActivator(LogicalKeyboardKey.arrowUp, meta: true),+ label: 'Focus the pane above',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.focusPaneRight,+ activator: SingleActivator(LogicalKeyboardKey.arrowRight, meta: true),+ label: 'Focus the pane to the right',+ group: ShortcutGroup.navigate,+ ),++ // --- panes ----------------------------------------------------------------+ //+ // Shift-Command-arrows move the pane itself in the same direction.+ AppShortcut(+ action: ShortcutAction.movePaneLeft,+ activator: SingleActivator(+ LogicalKeyboardKey.arrowLeft,+ meta: true,+ shift: true,+ ),+ label: 'Move this pane left',+ group: ShortcutGroup.panes,+ ),+ AppShortcut(+ action: ShortcutAction.movePaneDown,+ activator: SingleActivator(+ LogicalKeyboardKey.arrowDown,+ meta: true,+ shift: true,+ ),+ label: 'Move this pane down',+ group: ShortcutGroup.panes,+ ),+ AppShortcut(+ action: ShortcutAction.movePaneUp,+ activator: SingleActivator(+ LogicalKeyboardKey.arrowUp,+ meta: true,+ shift: true,+ ),+ label: 'Move this pane up',+ group: ShortcutGroup.panes,+ ),+ AppShortcut(+ action: ShortcutAction.movePaneRight,+ activator: SingleActivator(+ LogicalKeyboardKey.arrowRight,+ meta: true,+ shift: true,+ ),+ label: 'Move this pane right',+ group: ShortcutGroup.panes,+ ),++ // ⌘⏎ — tmux's `prefix z`, one of the most-pressed keys that multiplexer has.+ // Enter because it reads as "make THIS the thing", and because it is the one+ // chord on this list nobody has to look up twice.+ AppShortcut(+ action: ShortcutAction.zoomPane,+ activator: SingleActivator(LogicalKeyboardKey.enter, meta: true),+ label: 'Zoom this pane, or put it back',+ group: ShortcutGroup.panes,+ ),+ // ⌘; — tmux's `prefix ;`, spelled the same. Two agents at a time is the shape+ // most work actually has, and walking a list to get back to the other one is+ // the wrong motion for it.+ AppShortcut(+ action: ShortcutAction.lastPane,+ activator: SingleActivator(LogicalKeyboardKey.semicolon, meta: true),+ label: 'Back to the pane you were just on',+ group: ShortcutGroup.panes,+ ),+ AppShortcut(+ action: ShortcutAction.closePane,+ activator: SingleActivator(LogicalKeyboardKey.keyW, meta: true),+ label: 'Close the focused pane',+ group: ShortcutGroup.panes,+ ),+ AppShortcut(+ action: ShortcutAction.showLayout,+ activator: SingleActivator(LogicalKeyboardKey.keyS, meta: true),+ label: 'Choose the grid layout',+ group: ShortcutGroup.panes,+ ),++ // --- agents ---------------------------------------------------------------+ //+ // In Swarms, brackets follow Chrome's Back/Forward history. Directional+ // pane movement keeps its own keys; Shift-brackets step through tabs.+ AppShortcut(+ action: ShortcutAction.previousAgent,+ activator: SingleActivator(LogicalKeyboardKey.bracketLeft, meta: true),+ label: 'Back',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.nextAgent,+ activator: SingleActivator(LogicalKeyboardKey.bracketRight, meta: true),+ label: 'Forward',+ group: ShortcutGroup.navigate,+ ),+ // Control-Tab and Shift-brackets move through tabs. Pane directions and+ // agent history have their own shortcuts above.+ AppShortcut(+ action: ShortcutAction.nextAgent,+ activator: SingleActivator(LogicalKeyboardKey.tab, control: true),+ label: 'Next pane',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.previousAgent,+ activator: SingleActivator(+ LogicalKeyboardKey.tab,+ control: true,+ shift: true,+ ),+ label: 'Previous pane',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.toggleRail,+ activator: SingleActivator(LogicalKeyboardKey.backslash, meta: true),+ label: 'Show or hide the sidebar',+ group: ShortcutGroup.navigate,+ ),++ // --- actions --------------------------------------------------------------+ AppShortcut(+ action: ShortcutAction.newAgent,+ activator: SingleActivator(LogicalKeyboardKey.keyN, meta: true),+ label: 'New Harness',+ group: ShortcutGroup.actions,+ ),+ AppShortcut(+ action: ShortcutAction.routeTask,+ activator: SingleActivator(LogicalKeyboardKey.keyB, meta: true),+ label: 'Describe a task, and let it pick the agent',+ group: ShortcutGroup.actions,+ ),+ AppShortcut(+ action: ShortcutAction.reload,+ activator: SingleActivator(LogicalKeyboardKey.keyR, meta: true),+ label: 'Reload machines and harnesses',+ group: ShortcutGroup.actions,+ ),+ AppShortcut(+ action: ShortcutAction.showShortcuts,+ activator: SingleActivator(LogicalKeyboardKey.slash, meta: true),+ label: 'Show keyboard shortcuts',+ group: ShortcutGroup.actions,+ ),+];++/// Open Settings ▸ Debug — the app's own log, as this session still holds it.+///+/// Kept out of [kAppShortcuts] because it is not always there: a release build+/// has no Debug screen (see [kDebugSurfaceEnabled]), and a key that opens+/// nothing is worse than a key that was never taken. Shift keeps it separate+/// from the everyday Command-D split action.+const AppShortcut kDebugShortcut = AppShortcut(+ action: ShortcutAction.showDebug,+ activator: SingleActivator(LogicalKeyboardKey.keyD, meta: true, shift: true),+ label: 'Open the debug log',+ group: ShortcutGroup.actions,+);++/// Every shortcut THIS build has — [kAppShortcuts], plus the developer ones the+/// build is allowed to show.+///+/// The one list the bindings, the ⌘/ sheet and the tooltips all read, so a+/// build cannot bind a key it does not document or document one it does not+/// bind.+List<AppShortcut> appShortcuts({bool swarmMode = true}) => [+ for (final shortcut in kAppShortcuts)+ if (!swarmMode ||+ (!const {+ ShortcutAction.toggleRail,+ ShortcutAction.closePane,+ ShortcutAction.reload,+ }.contains(shortcut.action) &&+ !shortcut.activator.control))+ shortcut,+ if (swarmMode) ...kSwarmShortcuts,+ if (kDebugSurfaceEnabled) kDebugShortcut,+];++/// Swarm bindings replace the old workspace navigation in the retained legacy+/// screen. Live Swarm bindings, tooltips, and help all use this same catalog.+const kSwarmShortcuts = [+ AppShortcut(+ action: ShortcutAction.addAgent,+ activator: SingleActivator(LogicalKeyboardKey.keyO, meta: true),+ label: 'Find Harness',+ group: ShortcutGroup.actions,+ ),+ AppShortcut(+ action: ShortcutAction.showHistory,+ activator: SingleActivator(LogicalKeyboardKey.keyY, meta: true),+ label: 'Show full history',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.newSwarm,+ activator: SingleActivator(LogicalKeyboardKey.keyT, meta: true),+ label: 'New Tab',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.reopenClosedSwarm,+ activator: SingleActivator(+ LogicalKeyboardKey.keyT,+ meta: true,+ shift: true,+ ),+ label: 'Reopen last closed harness',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.closeSwarm,+ activator: SingleActivator(LogicalKeyboardKey.keyW, meta: true),+ label: 'Close Tab',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.renameSwarm,+ activator: SingleActivator(+ LogicalKeyboardKey.keyR,+ meta: true,+ shift: true,+ ),+ label: 'Rename Tab',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.nextSwarm,+ activator: SingleActivator(+ LogicalKeyboardKey.bracketRight,+ meta: true,+ shift: true,+ ),+ label: 'Next Harness',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.previousSwarm,+ activator: SingleActivator(+ LogicalKeyboardKey.bracketLeft,+ meta: true,+ shift: true,+ ),+ label: 'Previous Harness',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.nextSwarm,+ activator: SingleActivator(LogicalKeyboardKey.tab, control: true),+ label: 'Next Harness',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.previousSwarm,+ activator: SingleActivator(+ LogicalKeyboardKey.tab,+ control: true,+ shift: true,+ ),+ label: 'Previous Harness',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.showAttention,+ activator: SingleActivator(+ LogicalKeyboardKey.keyI,+ meta: true,+ shift: true,+ ),+ label: 'Show harnesses needing input',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.closePane,+ activator: SingleActivator(+ LogicalKeyboardKey.keyW,+ meta: true,+ shift: true,+ ),+ label: 'Close the focused pane',+ group: ShortcutGroup.panes,+ ),+ AppShortcut(+ action: ShortcutAction.showSettings,+ activator: SingleActivator(LogicalKeyboardKey.comma, meta: true),+ label: 'Open Settings',+ group: ShortcutGroup.actions,+ ),+];++/// Command-number selects the first nine tabs in their visible order. The+/// shortcut sheet prints one row; pane movement uses Command-arrows.+const int kTabDigitCount = 9;++List<SingleActivator> tabDigitActivators() => const [+ SingleActivator(LogicalKeyboardKey.digit1, meta: true),+ SingleActivator(LogicalKeyboardKey.digit2, meta: true),+ SingleActivator(LogicalKeyboardKey.digit3, meta: true),+ SingleActivator(LogicalKeyboardKey.digit4, meta: true),+ SingleActivator(LogicalKeyboardKey.digit5, meta: true),+ SingleActivator(LogicalKeyboardKey.digit6, meta: true),+ SingleActivator(LogicalKeyboardKey.digit7, meta: true),+ SingleActivator(LogicalKeyboardKey.digit8, meta: true),+ SingleActivator(LogicalKeyboardKey.digit9, meta: true),+];++/// One line in the shortcuts UI: what it does, and every chord that does it.+///+/// Not the same shape as [AppShortcut], and deliberately. Two activators can+/// drive one action — `⌘]` and `⌃⇥` both focus the next pane — which the+/// bindings need as two entries and the reader needs as one line. Printed as+/// two rows it reads as a duplicate the screen forgot to collapse.+class ShortcutRow {+ const ShortcutRow({+ required this.label,+ required this.chords,+ required this.group,+ });++ final String label;++ /// Every way to fire it, in declaration order — the first is the one to+ /// learn, the rest are alternates.+ final List<KeyChord> chords;++ final ShortcutGroup group;+}++/// [kAppShortcuts] as the UI prints it: one row per action, alternates folded+/// in, and `⌘1`–`⌘9` as the single line it deserves.+///+/// Derived rather than written out, so a shortcut cannot be added to the+/// bindings and forgotten here.+List<ShortcutRow> shortcutRows() {+ final byAction = <ShortcutAction, List<KeyChord>>{};+ final order = <ShortcutAction>[];+ final labels = <ShortcutAction, String>{};+ final groups = <ShortcutAction, ShortcutGroup>{};++ for (final shortcut in appShortcuts()) {+ if (byAction.putIfAbsent(shortcut.action, () => []).isEmpty) {+ order.add(shortcut.action);+ labels[shortcut.action] = shortcut.label;+ groups[shortcut.action] = shortcut.group;+ }+ byAction[shortcut.action]!.add(describeShortcutKeys(shortcut.activator));+ }++ final rows = [+ for (final action in order)+ ShortcutRow(+ label: labels[action]!,+ chords: byAction[action]!,+ group: groups[action]!,+ ),+ ];++ // The digits are not in [kAppShortcuts] — nine near-identical rows would bury+ // everything around them — so they join here, at the end of their group.+ final digits = ShortcutRow(+ label: 'Select tabs 1–9',+ chords: const [+ ['⌘', '1 – $kTabDigitCount'],+ ],+ group: ShortcutGroup.navigate,+ );+ final lastTab = rows.lastIndexWhere(+ (row) => row.group == ShortcutGroup.navigate,+ );+ rows.insert(lastTab + 1, digits);+ return rows;+}++/// A key this app deliberately does **not** take, and who has it instead.+class TerminalKey {+ const TerminalKey(this.chord, this.label);++ final KeyChord chord;+ final String label;+}++/// What the terminal keeps — the doc comment at the top of this file, stated+/// where a user can read it.+///+/// The shortcuts screen prints these beside the ones the app takes, because+/// "why is there no shortcut for X" is answered by seeing that X already+/// belongs to something.+const List<TerminalKey> kTerminalOwnedKeys = [+ TerminalKey(['⌘', 'C'], 'Copy'),+ TerminalKey(['⌘', 'V'], 'Paste'),+ TerminalKey(['⌘', 'A'], 'Select all'),+ TerminalKey(['esc'], 'Interrupt the engine'),+ TerminalKey(['⌥', '⏎'], "Newline in the engine's prompt"),+ TerminalKey(['⌃', 'C'], 'Cancel / interrupt in the agent'),+];++/// Turns the declared shortcuts into the map [CallbackShortcuts] wants.+///+/// A missing handler is left unbound rather than bound to nothing: a key that+/// silently does nothing is worse than a key that was never taken, because the+/// terminal underneath could have had it.+Map<ShortcutActivator, VoidCallback> buildShortcutBindings({+ required Map<ShortcutAction, VoidCallback> handlers,+ void Function(int index)? onSelectTabIndex,+ bool swarmMode = true,+}) {+ final bindings = <ShortcutActivator, VoidCallback>{};+ for (final shortcut in appShortcuts(swarmMode: swarmMode)) {+ final handler = handlers[shortcut.action];+ if (handler != null) bindings[shortcut.activator] = handler;+ }+ if (onSelectTabIndex != null) {+ final digits = tabDigitActivators();+ for (var i = 0; i < digits.length; i++) {+ bindings[digits[i]] = () => onSelectTabIndex(i);+ }+ }+ return bindings;+}++/// One chord, split into the keys a keyboard actually has — `['⇧', '⌘', ']']`.+///+/// Split rather than joined because the shortcuts UI draws one keycap per key.+/// [describeShortcut] is the same thing run together, for the places that want+/// a string (a tooltip, a test's failure message).+typedef KeyChord = List<String>;++/// The caps for [activator], in the order Apple prints them.+KeyChord describeShortcutKeys(SingleActivator activator) => [+ if (activator.control) '⌃',+ if (activator.alt) '⌥',+ if (activator.shift) '⇧',+ if (activator.meta) '⌘',+ _keyLabel(activator.trigger),+];++/// "⇧⌘]" — the way a Mac menu prints it, in the order Apple prints it.+String describeShortcut(SingleActivator activator) =>+ describeShortcutKeys(activator).join();++String _keyLabel(LogicalKeyboardKey key) {+ // keyLabel spells these out ("Arrow Left"), which is not how a Mac prints a+ // shortcut.+ if (key == LogicalKeyboardKey.arrowLeft) return '←';+ if (key == LogicalKeyboardKey.arrowRight) return '→';+ if (key == LogicalKeyboardKey.arrowUp) return '↑';+ if (key == LogicalKeyboardKey.arrowDown) return '↓';+ if (key == LogicalKeyboardKey.enter) return '⏎';+ if (key == LogicalKeyboardKey.tab) return '⇥';+ if (key == LogicalKeyboardKey.escape) return 'esc';+ return key.keyLabel;+}++/// The chord for [action], ready to append to a tooltip.+///+/// Tooltips read this instead of spelling the keys out, so a rebinding cannot+/// leave a button advertising a key that no longer works.+String? shortcutHintFor(ShortcutAction action, {bool swarmMode = true}) {+ for (final shortcut in appShortcuts(swarmMode: swarmMode)) {+ if (shortcut.action == action) return describeShortcut(shortcut.activator);+ }+ return null;+}++/// "Reload machines ⌘R"+String withShortcutHint(+ String tooltip,+ ShortcutAction action, {+ bool swarmMode = true,+}) {+ final hint = shortcutHintFor(action, swarmMode: swarmMode);+ return hint == null ? tooltip : '$tooltip $hint';+}diff --git a/mobile/lib/shortcuts/key_cap.dart b/mobile/lib/shortcuts/key_cap.dartnew file mode 100644index 000000000..216503250--- /dev/null+++ b/mobile/lib/shortcuts/key_cap.dart@@ -0,0 +1,105 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import 'app_shortcuts.dart';++/// One key, drawn as a key.+///+/// A chord printed as running text (`⇧⌘]`) is three glyphs the eye has to+/// separate before it can read them; drawn as caps it is three objects and+/// reads at a glance. It also gives the right-hand column a shape, which is+/// what a list of shortcuts is scanned by.+///+/// A recessed well, not a bordered box: §1 puts depth in the fill, and+/// [grid.AppSurface.wellFill] is an overlay, so a cap keeps its edge on a+/// raised card and on a recessed one without being picked for either.+class KeyCap extends StatelessWidget {+ const KeyCap(this.label, {super.key});++ final String label;++ /// Square at a single glyph, so ⌘ and W sit in caps of the same size and the+ /// column stays a column. A longer label ("esc", "1 – 9") grows past it.+ static const double _minWidth = 22;+ static const double height = 22;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Container(+ constraints: const BoxConstraints(minWidth: _minWidth),+ height: height,+ padding: const EdgeInsets.symmetric(horizontal: 6),+ decoration: BoxDecoration(+ color: grid.AppSurface.wellFill,+ borderRadius: BorderRadius.circular(6),+ ),+ // `Center(widthFactor: 1)`, never `Container(alignment:)` — a cap has to+ // be the width of the glyph on it, and an Align given a bounded width+ // FILLS it (`shrinkWrapWidth` is false unless a factor is set or the+ // constraint is infinite). The chord's Wrap bounds its children, so the+ // plain alignment blew every cap out to the whole row: one cap per line,+ // and a label squeezed to a character per line beside it.+ child: Center(+ widthFactor: 1,+ child: label == '⇥' || label == '↵' || label == '⏎'+ ? Semantics(+ label: label == '⇥' ? 'Tab' : 'Return',+ child: Icon(+ label == '⇥' ? Icons.keyboard_tab : Icons.keyboard_return,+ size: 14,+ color: grid.AppPalette.textPrimary,+ ),+ )+ : Text(+ label,+ style: TextStyle(+ color: grid.AppPalette.textPrimary,+ fontSize: 11.5,+ height: 1,+ // Tabular so ⌘1 – ⌘9 and ⌘W keep the same cap width.+ fontFeatures: const [FontFeature.tabularFigures()],+ ),+ ),+ ),+ );+ }+}++/// A whole chord — `⇧` `⌘` `]` — and, where an action has more than one, the+/// alternates after an "or".+///+/// The alternates are printed rather than hidden: `⌃⇥` is the chord people+/// arrive already knowing, and a screen that only lists `⌘]` teaches them the+/// app doesn't have the key they are about to press.+class KeyChordView extends StatelessWidget {+ const KeyChordView({super.key, required this.chords});++ final List<KeyChord> chords;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Wrap(+ spacing: 4,+ runSpacing: 4,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ for (var i = 0; i < chords.length; i++) ...[+ if (i > 0)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 2),+ child: Text(+ 'or',+ style: TextStyle(+ color: grid.AppPalette.textFaint,+ fontSize: 10.5,+ ),+ ),+ ),+ for (final key in chords[i]) KeyCap(key),+ ],+ ],+ );+ }+}diff --git a/mobile/lib/shortcuts/keymap.dart b/mobile/lib/shortcuts/keymap.dartnew file mode 100644index 000000000..9f366bc03--- /dev/null+++ b/mobile/lib/shortcuts/keymap.dart@@ -0,0 +1,400 @@+import 'dart:convert';++enum KeymapContext { workspace, terminal, picker }++/// A canonical logical key name and exact modifier set. Parsing happens on reload,+/// never on the input path. The Flutter adapter supplies the same canonical keys.+class KeyStroke {+ const KeyStroke(+ this.key, {+ this.control = false,+ this.alt = false,+ this.command = false,+ this.shift = false,+ });++ final String key;+ final bool control, alt, command, shift;++ static const _modifiers = {+ 'ctrl': 'control',+ 'control': 'control',+ 'alt': 'alt',+ 'option': 'alt',+ 'opt': 'alt',+ 'cmd': 'command',+ 'command': 'command',+ 'super': 'command',+ 'shift': 'shift',+ };+ static const _aliases = {+ 'return': 'enter',+ 'esc': 'escape',+ 'arrowleft': 'left',+ 'arrowright': 'right',+ 'arrowup': 'up',+ 'arrowdown': 'down',+ 'pgup': 'pageup',+ 'pgdn': 'pagedown',+ 'pagedn': 'pagedown',+ 'del': 'delete',+ 'backspace': 'backspace',+ ',': 'comma',+ '.': 'period',+ '/': 'slash',+ '\\': 'backslash',+ ';': 'semicolon',+ "'": 'quote',+ '`': 'backquote',+ '[': 'bracketleft',+ ']': 'bracketright',+ '-': 'minus',+ '=': 'equal',+ 'spacebar': 'space',+ };+ static const _named = {+ 'enter',+ 'escape',+ 'left',+ 'right',+ 'up',+ 'down',+ 'pageup',+ 'pagedown',+ 'home',+ 'end',+ 'delete',+ 'backspace',+ 'tab',+ 'space',+ 'comma',+ 'period',+ 'slash',+ 'backslash',+ 'semicolon',+ 'quote',+ 'backquote',+ 'bracketleft',+ 'bracketright',+ 'minus',+ 'equal',+ 'insert',+ };++ factory KeyStroke.parse(String value) {+ final parts = value.toLowerCase().split('+');+ final modifiers = <String>{};+ String? key;+ for (final part in parts) {+ final modifier = _modifiers[part];+ if (modifier != null) {+ if (!modifiers.add(modifier)) {+ throw FormatException('Repeated modifier in "$value"');+ }+ } else {+ if (key != null || part.isEmpty) {+ throw FormatException('Expected one key in "$value"');+ }+ key = _aliases[part] ?? part;+ }+ }+ if (key == null ||+ !(_named.contains(key) ||+ RegExp(r'^[a-z0-9]$').hasMatch(key) ||+ RegExp(r'^f([1-9]|1[0-9]|2[0-4])$').hasMatch(key))) {+ throw FormatException('Unknown key in "$value"');+ }+ return KeyStroke(+ key,+ control: modifiers.contains('control'),+ alt: modifiers.contains('alt'),+ command: modifiers.contains('command'),+ shift: modifiers.contains('shift'),+ );+ }++ @override+ String toString() => [+ if (control) 'ctrl',+ if (alt) 'alt',+ if (command) 'cmd',+ if (shift) 'shift',+ key,+ ].join('+');++ @override+ bool operator ==(Object other) =>+ other is KeyStroke &&+ key == other.key &&+ control == other.control &&+ alt == other.alt &&+ command == other.command &&+ shift == other.shift;++ @override+ int get hashCode => Object.hash(key, control, alt, command, shift);+}++class KeyBinding {+ KeyBinding({+ required Iterable<KeyStroke> keys,+ required this.command,+ this.context = KeymapContext.workspace,+ this.custom = false,+ }) : keys = List.unmodifiable(keys) {+ if (this.keys.isEmpty || this.keys.length > 4) {+ throw const FormatException('Use one to four keys in a sequence');+ }+ }++ final List<KeyStroke> keys;++ /// Null explicitly unbinds this sequence, including any longer descendants.+ final String? command;+ final KeymapContext context;+ final bool custom;+ String get sequence => keys.join(' ');+}++class KeymapConfig {+ const KeymapConfig.empty() : bindings = const [];+ KeymapConfig(Iterable<KeyBinding> bindings)+ : bindings = List.unmodifiable(bindings);+ final List<KeyBinding> bindings;++ factory KeymapConfig.parse(String source, {required Set<String> commands}) {+ final cleaned = _cleanJsonc(source);+ if (cleaned.trim().isEmpty) return const KeymapConfig.empty();+ final dynamic value;+ try {+ value = jsonDecode(cleaned);+ } on FormatException catch (error) {+ throw FormatException(error.message, source, error.offset);+ }+ if (value is! Map<String, dynamic>) {+ throw const FormatException('Keyboard config must be an object');+ }+ if (value.keys.any(+ (key) => !{'version', 'bindings', r'$schema'}.contains(key),+ )) {+ throw const FormatException('Unknown keyboard config property');+ }+ if ((value['version'] ?? 1) != 1) {+ throw const FormatException('Unsupported keyboard config version');+ }+ final rows = value['bindings'] ?? [];+ if (rows is! List || rows.length > 512) {+ throw const FormatException(+ 'bindings must be an array of at most 512 entries',+ );+ }+ final result = <KeyBinding>[];+ final seen = <String>{};+ for (var i = 0; i < rows.length; i++) {+ final row = rows[i];+ if (row is! Map<String, dynamic> ||+ row.keys.any((key) => !{'keys', 'command', 'when'}.contains(key)) ||+ row['keys'] is! String ||+ !row.containsKey('command')) {+ throw FormatException(+ 'bindings[$i] needs keys, command, and an optional when',+ );+ }+ final command = row['command'];+ // Retired actions must not invalidate the user's other custom shortcuts.+ if (const {'picker.preview', 'navigation.quick_open'}.contains(command) &&+ !commands.contains(command)) {+ continue;+ }+ if (command != null &&+ (command is! String || !commands.contains(command))) {+ throw FormatException('Unknown command in bindings[$i]: $command');+ }+ final scope = row['when'] ?? 'workspace';+ final contexts = KeymapContext.values.where(+ (context) => context.name == scope,+ );+ if (contexts.isEmpty) {+ throw FormatException('Unknown context in bindings[$i]: $scope');+ }+ final sequence = (row['keys'] as String).trim().replaceAll(+ RegExp(r'\s*\+\s*'),+ '+',+ );+ final binding = KeyBinding(+ keys: sequence.split(RegExp(r'\s+')).map(KeyStroke.parse),+ command: command as String?,+ context: contexts.first,+ custom: true,+ );+ if (!seen.add('${binding.context.name}:${binding.sequence}')) {+ throw FormatException(+ 'Duplicate binding: ${binding.sequence} in $scope',+ );+ }+ result.add(binding);+ }+ return KeymapConfig(result);+ }+}++class KeymapMatch {+ const KeymapMatch({this.command, this.prefix = false});+ final String? command;+ final bool prefix;+ bool get matched => command != null || prefix;+}++class _KeyNode {+ final children = <KeyStroke, _KeyNode>{};+ String? command;+}++/// Immutable lookup tables for each input context. Workspace commands are+/// inherited by a terminal; a modal picker owns its own keys.+class ResolvedKeymap {+ ResolvedKeymap(Iterable<KeyBinding> defaults, KeymapConfig config) {+ for (final context in KeymapContext.values) {+ final effective = <String, KeyBinding>{};+ void apply(Iterable<KeyBinding> entries, KeymapContext scope) {+ for (final entry in entries.where(+ (binding) => binding.context == scope,+ )) {+ if (entry.command == null) {+ effective.removeWhere(+ (key, _) =>+ key == entry.sequence || key.startsWith('${entry.sequence} '),+ );+ } else {+ effective[entry.sequence] = entry;+ }+ }+ }++ if (context != KeymapContext.workspace) {+ apply(defaults, KeymapContext.workspace);+ }+ apply(defaults, context);+ if (context != KeymapContext.workspace) {+ apply(config.bindings, KeymapContext.workspace);+ }+ apply(config.bindings, context);+ _bindings[context] = List.unmodifiable(effective.values);+ final root = _KeyNode();+ for (final entry in effective.values) {+ var node = root;+ for (final key in entry.keys) {+ if (node.command != null) _ambiguous(entry, context);+ node = node.children.putIfAbsent(key, _KeyNode.new);+ }+ if (node.children.isNotEmpty) _ambiguous(entry, context);+ node.command = entry.command;+ }+ _roots[context] = root;+ }+ }++ final _roots = <KeymapContext, _KeyNode>{};+ final _bindings = <KeymapContext, List<KeyBinding>>{};++ Never _ambiguous(KeyBinding binding, KeymapContext context) =>+ throw FormatException(+ 'Ambiguous prefix for ${binding.sequence} in ${context.name}; '+ 'unbind the shorter command before defining a sequence',+ );++ List<KeyBinding> bindingsFor(KeymapContext context) => _bindings[context]!;++ Iterable<KeyBinding> continuations(+ KeymapContext context,+ List<KeyStroke> prefix,+ ) => _bindings[context]!.where(+ (binding) =>+ binding.keys.length > prefix.length &&+ Iterable.generate(prefix.length)+ .every((i) => binding.keys[i] == prefix[i]),+ );++ KeymapMatch match(KeymapContext context, Iterable<KeyStroke> keys) {+ var node = _roots[context]!;+ for (final key in keys) {+ final next = node.children[key];+ if (next == null) return const KeymapMatch();+ node = next;+ }+ return KeymapMatch(command: node.command, prefix: node.children.isNotEmpty);+ }+}++/// Strip comments/trailing commas without shifting JSON decoder error offsets.+/// String contents, escapes and newlines remain byte-for-byte intact.+String _cleanJsonc(String source) {+ final chars = source.codeUnits.toList();+ var inString = false;+ for (var i = 0; i < chars.length; i++) {+ final c = chars[i];+ if (inString) {+ if (c == 92) {+ i++;+ } else if (c == 34) {+ inString = false;+ }+ continue;+ }+ if (c == 34) {+ inString = true;+ continue;+ }+ if (c != 47 || i + 1 >= chars.length) continue;+ final next = chars[i + 1];+ if (next == 47) {+ while (i < chars.length && chars[i] != 10 && chars[i] != 13) {+ chars[i++] = 32;+ }+ i--;+ } else if (next == 42) {+ final start = i;+ chars[i++] = 32;+ chars[i++] = 32;+ while (i < chars.length &&+ !(chars[i] == 42 && i + 1 < chars.length && chars[i + 1] == 47)) {+ if (chars[i] != 10 && chars[i] != 13) chars[i] = 32;+ i++;+ }+ if (i + 1 >= chars.length) {+ throw FormatException('Unterminated block comment', source, start);+ }+ chars[i] = 32;+ chars[++i] = 32;+ }+ }+ inString = false;+ for (var i = 0; i < chars.length; i++) {+ if (inString) {+ if (chars[i] == 92) {+ i++;+ } else if (chars[i] == 34) {+ inString = false;+ }+ } else if (chars[i] == 34) {+ inString = true;+ } else if (chars[i] == 44) {+ var next = i + 1;+ while (next < chars.length &&+ const {9, 10, 13, 32}.contains(chars[next])) {+ next++;+ }+ var previous = i - 1;+ while (previous >= 0 && const {9, 10, 13, 32}.contains(chars[previous])) {+ previous--;+ }+ if (previous >= 0 &&+ !const {91, 123, 44, 58}.contains(chars[previous]) &&+ next < chars.length &&+ (chars[next] == 93 || chars[next] == 125)) {+ chars[i] = 32;+ }+ }+ }+ return String.fromCharCodes(chars);+}diff --git a/mobile/lib/shortcuts/keymap_commands.dart b/mobile/lib/shortcuts/keymap_commands.dartnew file mode 100644index 000000000..3038781e0--- /dev/null+++ b/mobile/lib/shortcuts/keymap_commands.dart@@ -0,0 +1,434 @@+import '../logging/debug_surface.dart';+import 'app_shortcuts.dart';+import 'keymap.dart';+import 'keymap_keyboard.dart';++/// Stable identities connect search to workspace actions. The same catalog+/// supplies the file-remapping foundation; native runtime wiring is separate.+class HarnessCommand {+ const HarnessCommand(+ this.id,+ this.label,+ this.group, {+ this.extraKeys = const [],+ this.action,+ this.nativeAction,+ this.context = KeymapContext.workspace,+ this.repeatable = false,+ });+ final String id, label;+ final ShortcutGroup group;+ final List<String> extraKeys;++ /// Workspace defaults come from the live shortcut table. A command cannot+ /// quietly propose different keys from the ones the user already uses.+ List<String> get keys =>+ action == null ? extraKeys : _workspaceKeys[action] ?? const [];+ final ShortcutAction? action;+ final String? nativeAction;+ final KeymapContext context;+ final bool repeatable;+}++final _workspaceKeys = _readWorkspaceKeys();+Map<ShortcutAction, List<String>> _readWorkspaceKeys() {+ final result = <ShortcutAction, List<String>>{};+ for (final shortcut in appShortcuts()) {+ final keys = keyStrokeFor(+ shortcut.activator.trigger,+ command: shortcut.activator.meta,+ control: shortcut.activator.control,+ alt: shortcut.activator.alt,+ shift: shortcut.activator.shift,+ )!.toString();+ (result[shortcut.action] ??= []).add(keys);+ }+ return result;+}++final harnessCommands = <HarnessCommand>[+ const HarnessCommand(+ 'navigation.commands',+ 'Search commands',+ ShortcutGroup.actions,+ extraKeys: ['cmd+shift+p'],+ nativeAction: 'commands',+ ),+ const HarnessCommand(+ 'swarm.new',+ 'New Tab',+ ShortcutGroup.navigate,+ action: ShortcutAction.newSwarm,+ nativeAction: 'new',+ ),+ const HarnessCommand(+ 'swarm.close',+ 'Close Tab',+ ShortcutGroup.navigate,+ action: ShortcutAction.closeSwarm,+ nativeAction: 'closeActive',+ ),+ const HarnessCommand(+ 'swarm.reopen',+ 'Reopen last closed harness',+ ShortcutGroup.navigate,+ action: ShortcutAction.reopenClosedSwarm,+ nativeAction: 'reopen',+ ),+ const HarnessCommand(+ 'swarm.next',+ 'Next Harness',+ ShortcutGroup.navigate,+ action: ShortcutAction.nextSwarm,+ nativeAction: 'next',+ repeatable: true,+ ),+ const HarnessCommand(+ 'swarm.previous',+ 'Previous Harness',+ ShortcutGroup.navigate,+ action: ShortcutAction.previousSwarm,+ nativeAction: 'previous',+ repeatable: true,+ ),+ const HarnessCommand(+ 'swarm.rename',+ 'Rename Tab',+ ShortcutGroup.actions,+ action: ShortcutAction.renameSwarm,+ nativeAction: 'renameActive',+ ),+ const HarnessCommand(+ 'navigation.back',+ 'Go back',+ ShortcutGroup.navigate,+ action: ShortcutAction.previousAgent,+ nativeAction: 'historyBack',+ repeatable: true,+ ),+ const HarnessCommand(+ 'navigation.forward',+ 'Go forward',+ ShortcutGroup.navigate,+ action: ShortcutAction.nextAgent,+ nativeAction: 'historyForward',+ repeatable: true,+ ),+ const HarnessCommand(+ 'navigation.history',+ 'Show full history',+ ShortcutGroup.navigate,+ action: ShortcutAction.showHistory,+ nativeAction: 'showHistory',+ ),+ const HarnessCommand(+ 'navigation.needs_input',+ 'Show harnesses needing input',+ ShortcutGroup.navigate,+ action: ShortcutAction.showAttention,+ nativeAction: 'notifications',+ ),+ for (var i = 1; i <= 9; i++)+ HarnessCommand(+ 'swarm.select_$i',+ 'Select tab $i',+ ShortcutGroup.navigate,+ extraKeys: ['cmd+$i'],+ ),+ for (var i = 1; i <= 9; i++)+ HarnessCommand('pane.focus_$i', 'Focus pane $i', ShortcutGroup.panes),+ const HarnessCommand(+ 'pane.focus_left',+ 'Focus the pane to the left',+ ShortcutGroup.panes,+ action: ShortcutAction.focusPaneLeft,+ repeatable: true,+ ),+ const HarnessCommand(+ 'pane.focus_right',+ 'Focus the pane to the right',+ ShortcutGroup.panes,+ action: ShortcutAction.focusPaneRight,+ repeatable: true,+ ),+ const HarnessCommand(+ 'pane.focus_above',+ 'Focus the pane above',+ ShortcutGroup.panes,+ action: ShortcutAction.focusPaneAbove,+ repeatable: true,+ ),+ const HarnessCommand(+ 'pane.focus_below',+ 'Focus the pane below',+ ShortcutGroup.panes,+ action: ShortcutAction.focusPaneBelow,+ repeatable: true,+ ),+ const HarnessCommand(+ 'pane.move_left',+ 'Move the pane left',+ ShortcutGroup.panes,+ action: ShortcutAction.movePaneLeft,+ repeatable: true,+ ),+ const HarnessCommand(+ 'pane.move_right',+ 'Move the pane right',+ ShortcutGroup.panes,+ action: ShortcutAction.movePaneRight,+ repeatable: true,+ ),+ const HarnessCommand(+ 'pane.move_up',+ 'Move the pane up',+ ShortcutGroup.panes,+ action: ShortcutAction.movePaneUp,+ repeatable: true,+ ),+ const HarnessCommand(+ 'pane.move_down',+ 'Move the pane down',+ ShortcutGroup.panes,+ action: ShortcutAction.movePaneDown,+ repeatable: true,+ ),+ const HarnessCommand(+ 'pane.zoom',+ 'Zoom or restore the focused pane',+ ShortcutGroup.panes,+ action: ShortcutAction.zoomPane,+ nativeAction: 'zoomPane',+ ),+ const HarnessCommand(+ 'pane.close',+ 'Close the focused pane',+ ShortcutGroup.panes,+ action: ShortcutAction.closePane,+ nativeAction: 'closePane',+ ),+ const HarnessCommand(+ 'pane.last',+ 'Return to the last pane',+ ShortcutGroup.panes,+ action: ShortcutAction.lastPane,+ ),+ const HarnessCommand(+ 'pane.pin',+ 'Pin or unpin the focused pane',+ ShortcutGroup.panes,+ action: ShortcutAction.pinPane,+ nativeAction: 'pinPane',+ ),+ const HarnessCommand(+ 'pane.layout',+ 'Choose a layout',+ ShortcutGroup.panes,+ action: ShortcutAction.showLayout,+ nativeAction: 'layout',+ ),+ const HarnessCommand('pane.resize', 'Resize panes', ShortcutGroup.panes),+ const HarnessCommand(+ 'pane.split_right',+ 'Split right…',+ ShortcutGroup.panes,+ extraKeys: ['cmd+r'],+ nativeAction: 'splitRight',+ ),+ const HarnessCommand(+ 'pane.split_down',+ 'Split down…',+ ShortcutGroup.panes,+ extraKeys: ['cmd+d'],+ nativeAction: 'splitDown',+ ),+ const HarnessCommand(+ 'pane.reset_sizes',+ 'Reset pane sizes',+ ShortcutGroup.panes,+ ),+ const HarnessCommand(+ 'terminal.find',+ 'Find in the focused terminal',+ ShortcutGroup.navigate,+ action: ShortcutAction.findTerminal,+ nativeAction: 'findTerminal',+ ),+ const HarnessCommand(+ 'terminal.find_next',+ 'Next terminal match',+ ShortcutGroup.navigate,+ action: ShortcutAction.findNext,+ nativeAction: 'findNext',+ repeatable: true,+ ),+ const HarnessCommand(+ 'terminal.find_previous',+ 'Previous terminal match',+ ShortcutGroup.navigate,+ action: ShortcutAction.findPrevious,+ nativeAction: 'findPrevious',+ repeatable: true,+ ),+ const HarnessCommand(+ 'agent.add',+ 'Open Harness',+ ShortcutGroup.actions,+ action: ShortcutAction.addAgent,+ nativeAction: 'addAgent',+ ),+ const HarnessCommand(+ 'agent.new',+ 'New Harness',+ ShortcutGroup.actions,+ action: ShortcutAction.newAgent,+ nativeAction: 'newAgent',+ ),+ const HarnessCommand(+ 'machines.manage',+ 'Open Machines Manager',+ ShortcutGroup.actions,+ nativeAction: 'manageMachines',+ ),+ const HarnessCommand(+ 'machine.link',+ 'Link machine',+ ShortcutGroup.actions,+ nativeAction: 'linkMachine',+ ),+ const HarnessCommand(+ 'project.add',+ 'Add project',+ ShortcutGroup.actions,+ nativeAction: 'addProject',+ ),+ const HarnessCommand(+ 'machines.refresh',+ 'Refresh machines and harnesses',+ ShortcutGroup.actions,+ action: ShortcutAction.reload,+ nativeAction: 'reload',+ ),+ const HarnessCommand(+ 'task.route',+ 'Boss mode: route a task',+ ShortcutGroup.actions,+ action: ShortcutAction.routeTask,+ ),+ const HarnessCommand(+ 'app.settings',+ 'Open Settings',+ ShortcutGroup.actions,+ action: ShortcutAction.showSettings,+ nativeAction: 'settings',+ ),+ const HarnessCommand(+ 'keyboard.help',+ 'Keyboard shortcuts',+ ShortcutGroup.actions,+ action: ShortcutAction.showShortcuts,+ nativeAction: 'showShortcuts',+ ),+ const HarnessCommand(+ 'keyboard.open_config',+ 'Open keyboard config',+ ShortcutGroup.actions,+ nativeAction: 'openKeymap',+ ),+ if (kDebugSurfaceEnabled)+ const HarnessCommand(+ 'app.debug',+ 'Open the debug log',+ ShortcutGroup.actions,+ action: ShortcutAction.showDebug,+ ),+ const HarnessCommand(+ 'picker.next',+ 'Next result',+ ShortcutGroup.navigate,+ extraKeys: ['down', 'ctrl+n', 'ctrl+j'],+ context: KeymapContext.picker,+ repeatable: true,+ ),+ const HarnessCommand(+ 'picker.previous',+ 'Previous result',+ ShortcutGroup.navigate,+ extraKeys: ['up', 'ctrl+p', 'ctrl+k'],+ context: KeymapContext.picker,+ repeatable: true,+ ),+ const HarnessCommand(+ 'picker.accept',+ 'Open the selected result',+ ShortcutGroup.navigate,+ extraKeys: ['enter'],+ context: KeymapContext.picker,+ ),+ const HarnessCommand(+ 'picker.add_here',+ 'Add the selected harness',+ ShortcutGroup.actions,+ extraKeys: ['cmd+enter'],+ context: KeymapContext.picker,+ ),+ const HarnessCommand(+ 'picker.cancel',+ 'Close search',+ ShortcutGroup.navigate,+ extraKeys: ['escape', 'ctrl+g'],+ context: KeymapContext.picker,+ ),+];++final harnessCommandById = {+ for (final command in harnessCommands) command.id: command,+};+final harnessDefaultBindings = [+ for (final command in harnessCommands)+ for (final keys in command.keys)+ KeyBinding(+ keys: keys.split(' ').map(KeyStroke.parse),+ command: command.id,+ context: command.context,+ ),+];+final harnessDefaultKeymap = ResolvedKeymap(+ harnessDefaultBindings,+ const KeymapConfig.empty(),+);++List<String> describeKeyStrokeKeys(KeyStroke stroke) => [+ if (stroke.control) '⌃',+ if (stroke.alt) '⌥',+ if (stroke.shift) '⇧',+ if (stroke.command) '⌘',+ const {+ 'left': '←',+ 'right': '→',+ 'up': '↑',+ 'down': '↓',+ 'enter': '↵',+ 'escape': 'Esc',+ 'tab': '⇥',+ 'space': 'Space',+ 'comma': ',',+ 'period': '.',+ 'slash': '/',+ 'backslash': r'\',+ 'semicolon': ';',+ 'quote': "'",+ 'backquote': '`',+ 'bracketleft': '[',+ 'bracketright': ']',+ 'minus': '-',+ 'equal': '=',+ 'backspace': '⌫',+ 'delete': '⌦',+ }[stroke.key] ??+ stroke.key.toUpperCase(),+];+String describeKeyStroke(KeyStroke stroke) =>+ describeKeyStrokeKeys(stroke).join();+String describeKeyBinding(KeyBinding binding) =>+ binding.keys.map(describeKeyStroke).join(' ');diff --git a/mobile/lib/shortcuts/keymap_keyboard.dart b/mobile/lib/shortcuts/keymap_keyboard.dartnew file mode 100644index 000000000..c4941e211--- /dev/null+++ b/mobile/lib/shortcuts/keymap_keyboard.dart@@ -0,0 +1,128 @@+import 'package:flutter/services.dart';++import 'keymap.dart';++/// Canonical logical keys, shared by configured bindings and keyboard events.+/// This does not guess a QWERTY position for a letter on another layout.+final _logicalKeys = <LogicalKeyboardKey, String>{+ LogicalKeyboardKey.enter: 'enter',+ LogicalKeyboardKey.numpadEnter: 'enter',+ LogicalKeyboardKey.escape: 'escape',+ LogicalKeyboardKey.arrowLeft: 'left',+ LogicalKeyboardKey.arrowRight: 'right',+ LogicalKeyboardKey.arrowUp: 'up',+ LogicalKeyboardKey.arrowDown: 'down',+ LogicalKeyboardKey.pageUp: 'pageup',+ LogicalKeyboardKey.pageDown: 'pagedown',+ LogicalKeyboardKey.home: 'home',+ LogicalKeyboardKey.end: 'end',+ LogicalKeyboardKey.delete: 'delete',+ LogicalKeyboardKey.backspace: 'backspace',+ LogicalKeyboardKey.tab: 'tab',+ LogicalKeyboardKey.space: 'space',+ LogicalKeyboardKey.comma: 'comma',+ LogicalKeyboardKey.period: 'period',+ LogicalKeyboardKey.slash: 'slash',+ LogicalKeyboardKey.backslash: 'backslash',+ LogicalKeyboardKey.semicolon: 'semicolon',+ LogicalKeyboardKey.quote: 'quote',+ LogicalKeyboardKey.backquote: 'backquote',+ LogicalKeyboardKey.bracketLeft: 'bracketleft',+ LogicalKeyboardKey.bracketRight: 'bracketright',+ LogicalKeyboardKey.minus: 'minus',+ LogicalKeyboardKey.equal: 'equal',+ LogicalKeyboardKey.insert: 'insert',+ for (final key in [+ LogicalKeyboardKey.keyA,+ LogicalKeyboardKey.keyB,+ LogicalKeyboardKey.keyC,+ LogicalKeyboardKey.keyD,+ LogicalKeyboardKey.keyE,+ LogicalKeyboardKey.keyF,+ LogicalKeyboardKey.keyG,+ LogicalKeyboardKey.keyH,+ LogicalKeyboardKey.keyI,+ LogicalKeyboardKey.keyJ,+ LogicalKeyboardKey.keyK,+ LogicalKeyboardKey.keyL,+ LogicalKeyboardKey.keyM,+ LogicalKeyboardKey.keyN,+ LogicalKeyboardKey.keyO,+ LogicalKeyboardKey.keyP,+ LogicalKeyboardKey.keyQ,+ LogicalKeyboardKey.keyR,+ LogicalKeyboardKey.keyS,+ LogicalKeyboardKey.keyT,+ LogicalKeyboardKey.keyU,+ LogicalKeyboardKey.keyV,+ LogicalKeyboardKey.keyW,+ LogicalKeyboardKey.keyX,+ LogicalKeyboardKey.keyY,+ LogicalKeyboardKey.keyZ,+ LogicalKeyboardKey.digit0,+ LogicalKeyboardKey.digit1,+ LogicalKeyboardKey.digit2,+ LogicalKeyboardKey.digit3,+ LogicalKeyboardKey.digit4,+ LogicalKeyboardKey.digit5,+ LogicalKeyboardKey.digit6,+ LogicalKeyboardKey.digit7,+ LogicalKeyboardKey.digit8,+ LogicalKeyboardKey.digit9,+ LogicalKeyboardKey.f1,+ LogicalKeyboardKey.f2,+ LogicalKeyboardKey.f3,+ LogicalKeyboardKey.f4,+ LogicalKeyboardKey.f5,+ LogicalKeyboardKey.f6,+ LogicalKeyboardKey.f7,+ LogicalKeyboardKey.f8,+ LogicalKeyboardKey.f9,+ LogicalKeyboardKey.f10,+ LogicalKeyboardKey.f11,+ LogicalKeyboardKey.f12,+ LogicalKeyboardKey.f13,+ LogicalKeyboardKey.f14,+ LogicalKeyboardKey.f15,+ LogicalKeyboardKey.f16,+ LogicalKeyboardKey.f17,+ LogicalKeyboardKey.f18,+ LogicalKeyboardKey.f19,+ LogicalKeyboardKey.f20,+ LogicalKeyboardKey.f21,+ LogicalKeyboardKey.f22,+ LogicalKeyboardKey.f23,+ LogicalKeyboardKey.f24,+ ])+ key: key.keyLabel.toLowerCase(),+};++KeyStroke? keyStrokeFor(+ LogicalKeyboardKey key, {+ bool control = false,+ bool alt = false,+ bool command = false,+ bool shift = false,+}) {+ final name = _logicalKeys[key];+ return name == null+ ? null+ : KeyStroke(+ name,+ control: control,+ alt: alt,+ command: command,+ shift: shift,+ );+}++KeyStroke? keyStrokeForEvent(KeyEvent event) {+ final keyboard = HardwareKeyboard.instance;+ return keyStrokeFor(+ event.logicalKey,+ control: keyboard.isControlPressed,+ alt: keyboard.isAltPressed,+ command: keyboard.isMetaPressed,+ shift: keyboard.isShiftPressed,+ );+}diff --git a/mobile/lib/shortcuts/keymap_settings.dart b/mobile/lib/shortcuts/keymap_settings.dartnew file mode 100644index 000000000..d63b50533--- /dev/null+++ b/mobile/lib/shortcuts/keymap_settings.dart@@ -0,0 +1,101 @@+import 'package:flutter/material.dart';+import 'package:url_launcher/url_launcher.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_select_field.dart';+import 'app_keymap.dart';+import 'keymap.dart';++Future<void> openKeyboardConfig(BuildContext context) async {+ final store = KeymapTheme.of(context, listen: false)?.store;+ if (store == null) return;+ try {+ final file = await store.ensureFile();+ if (!await launchUrl(file.uri)) {+ throw StateError(+ 'No editor is associated with .jsonc files. Open ${file.path} in your editor.',+ );+ }+ } catch (error) {+ if (context.mounted) {+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ SnackBar(content: Text('Couldn’t open keyboard config. $error')),+ );+ }+ }+}++class KeymapSettings extends StatelessWidget {+ const KeymapSettings({+ super.key,+ required this.contextKind,+ required this.onContextChanged,+ });+ final KeymapContext contextKind;+ final ValueChanged<KeymapContext> onContextChanged;++ @override+ Widget build(BuildContext context) {+ final keymap = KeymapTheme.of(context);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Wrap(+ spacing: 12,+ runSpacing: 8,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ AppSelectField<KeymapContext>(+ value: contextKind,+ width: 160,+ options: const [+ SelectOption(+ value: KeymapContext.workspace,+ label: 'Workspace',+ ),+ SelectOption(+ value: KeymapContext.terminal,+ label: 'Agent input',+ ),+ SelectOption(value: KeymapContext.picker, label: 'Search'),+ ],+ onChanged: onContextChanged,+ ),+ if (keymap?.store != null)+ TextButton.icon(+ onPressed: () => openKeyboardConfig(context),+ icon: const Icon(Icons.edit_outlined, size: 16),+ label: const Text('Edit keyboard config'),+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textPrimary,+ ),+ ),+ ],+ ),+ if (keymap?.path != null) ...[+ const SizedBox(height: 8),+ Text(+ 'Saves apply automatically. Invalid edits keep your last working shortcuts.',+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 12,+ ),+ ),+ const SizedBox(height: 4),+ SelectableText(+ keymap!.path!,+ style: TextStyle(color: grid.AppPalette.textFaint, fontSize: 11),+ ),+ ],+ if (keymap?.error != null) ...[+ const SizedBox(height: 8),+ SelectableText(+ keymap!.error!,+ style: const TextStyle(color: Colors.orangeAccent, fontSize: 12),+ ),+ ],+ const SizedBox(height: 16),+ ],+ );+ }+}diff --git a/mobile/lib/shortcuts/keymap_store.dart b/mobile/lib/shortcuts/keymap_store.dartnew file mode 100644index 000000000..63d019016--- /dev/null+++ b/mobile/lib/shortcuts/keymap_store.dart@@ -0,0 +1,313 @@+import '../core/host_platform.dart';+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:flutter/foundation.dart';+import 'package:path/path.dart' as p;++import 'keymap.dart';++/// Owns one dotfile. Invalid edits retain the last working keymap, and file+/// activity never performs work on the keyboard event path.+class KeymapStore extends ChangeNotifier {+ KeymapStore({+ required this.file,+ required Iterable<KeyBinding> defaults,+ required Set<String> commands,+ this.watchFiles = true,+ this.validate,+ }) : _defaults = List.unmodifiable(defaults),+ _commands = Set.unmodifiable(commands) {+ current = ResolvedKeymap(_defaults, const KeymapConfig.empty());+ validate?.call(current);+ _signature = _describe(current);+ }++ static const maximumBytes = 128 * 1024;+ final File file;+ final bool watchFiles;+ final void Function(ResolvedKeymap)? validate;+ final List<KeyBinding> _defaults;+ final Set<String> _commands;+ late ResolvedKeymap current;+ late String _signature;+ int revision = 0;+ String? _readError, _watchError;+ String? get error => _readError ?? _watchError;+ bool _disposed = false;+ int _generation = 0, _watchFailures = 0;+ final _watchers = <String, StreamSubscription<FileSystemEvent>>{};+ Set<String> _targets = {};+ Timer? _debounce;++ static String defaultPath({Map<String, String>? environment}) {+ final env = environment ?? Platform.environment;+ final xdg = env['XDG_CONFIG_HOME'];+ var home = env['HOME'] ?? env['USERPROFILE'];+ if (home == null || home.isEmpty) home = containerHome;+ final String root;+ if (xdg != null && p.isAbsolute(xdg)) {+ root = xdg;+ } else if (home != null && home.isNotEmpty) {+ root = p.join(home, '.config');+ } else {+ throw const FileSystemException(+ 'No home directory for keyboard configuration',+ );+ }+ return p.join(root, 'harness', 'keybindings.jsonc');+ }++ Future<void> start() async {+ if (watchFiles && !_disposed) await _refreshWatches(_generation);+ await reload();+ }++ Future<void> reload({bool fromWatcher = false}) async {+ if (_disposed) return;+ if (!fromWatcher) _watchFailures = 0;+ final generation = ++_generation;+ final priorError = error;+ var changed = false;+ try {+ String source;+ try {+ final bytes = await file+ .openRead(0, maximumBytes + 1)+ .fold(+ BytesBuilder(copy: false),+ (builder, chunk) => builder..add(chunk),+ );+ if (bytes.length > maximumBytes) {+ throw const FormatException('Keyboard config exceeds 128 KiB');+ }+ source = utf8.decode(bytes.takeBytes());+ } on FileSystemException catch (error) {+ if (!const {2, 3}.contains(error.osError?.errorCode)) rethrow;+ source = ''; // A missing file inherits defaults.+ }+ final next = ResolvedKeymap(+ _defaults,+ KeymapConfig.parse(source, commands: _commands),+ );+ validate?.call(next);+ if (_disposed || generation != _generation) return;+ final signature = _describe(next);+ if (_signature != signature) {+ current = next;+ _signature = signature;+ revision++;+ changed = true;+ }+ _readError = null;+ } catch (failure) {+ if (_disposed || generation != _generation) return;+ _readError = 'Keyboard config: $failure';+ }+ if (!_disposed &&+ generation == _generation &&+ (changed || priorError != error)) {+ notifyListeners();+ }+ final priorWatchError = error;+ if (watchFiles && !_disposed) await _refreshWatches(generation);+ if (!_disposed && generation == _generation && priorWatchError != error) {+ notifyListeners();+ }+ }++ String _describe(ResolvedKeymap map) => [+ for (final context in KeymapContext.values)+ for (final binding in map.bindingsFor(context))+ '${context.name}:${binding.sequence}:${binding.command}:${binding.custom}',+ ].join('\n');++ Future<void> _refreshWatches(int generation) async {+ try {+ await _updateWatches(generation);+ } catch (failure) {+ if (_disposed || generation != _generation) return;+ _watchError = 'Could not watch keyboard config: $failure';+ if (++_watchFailures <= 3) {+ _scheduleReload(Duration(milliseconds: 200 * _watchFailures));+ }+ }+ }++ Future<void> _updateWatches(int generation) async {+ final targets = {p.normalize(file.absolute.path)};+ var linkPath = targets.first;+ for (var depth = 0; depth < 8; depth++) {+ try {+ if (await FileSystemEntity.type(linkPath, followLinks: false) !=+ FileSystemEntityType.link) {+ break;+ }+ final destination = await Link(linkPath).target();+ final next = p.normalize(+ p.isAbsolute(destination)+ ? destination+ : p.join(p.dirname(linkPath), destination),+ );+ if (!targets.add(next)) break;+ linkPath = next;+ } on FileSystemException {+ break;+ }+ }+ try {+ targets.add(p.normalize(await file.resolveSymbolicLinks()));+ } on FileSystemException {+ /* Missing file or target. */+ }+ final directories = <String>{};+ for (final target in targets.toList()) {+ var directory = Directory(p.dirname(target));+ final original = directory.path;+ while (!await directory.exists()) {+ final parent = directory.parent;+ if (parent.path == directory.path) break;+ directory = parent;+ }+ // Observe creation of missing config directories without watching an+ // entire filesystem root. No recursive subscriptions are needed.+ if (directory.parent.path != directory.path) {+ final canonical = await directory.resolveSymbolicLinks();+ targets.add(+ p.normalize(+ p.join(canonical, p.relative(target, from: directory.path)),+ ),+ );+ directories.add(canonical);+ }+ if (directory.path == original &&+ directory.parent.parent.path != directory.parent.path) {+ directories.add(await directory.parent.resolveSymbolicLinks());+ }+ }+ if (_disposed || generation != _generation) return;+ _targets = targets;+ for (final path+ in _watchers.keys+ .where((path) => !directories.contains(path))+ .toList()) {+ unawaited(_watchers.remove(path)!.cancel());+ }+ _watchError = directories.isEmpty+ ? 'Create the keyboard config directory to enable automatic reload.'+ : null;+ for (final path in directories) {+ if (_watchers.containsKey(path)) continue;+ late StreamSubscription<FileSystemEvent> subscription;+ void lost(Object? failure) {+ if (_disposed || _watchers[path] != subscription) return;+ _watchers.remove(path);+ unawaited(subscription.cancel());+ _watchError =+ 'Keyboard config watch stopped. Reload to retry${failure == null ? '.' : ': $failure'}';+ notifyListeners();+ if (++_watchFailures <= 3) {+ _scheduleReload(Duration(milliseconds: 200 * _watchFailures));+ }+ }++ try {+ subscription = Directory(path).watch().listen(+ (event) {+ if (_related(event.path) ||+ event is FileSystemMoveEvent &&+ event.destination != null &&+ _related(event.destination!)) {+ if (event.isDirectory) {+ final changed = p.normalize(p.absolute(event.path));+ for (final watched+ in _watchers.keys+ .where(+ (path) =>+ path == changed || p.isWithin(changed, path),+ )+ .toList()) {+ unawaited(_watchers.remove(watched)!.cancel());+ }+ }+ _watchFailures = 0;+ _scheduleReload(const Duration(milliseconds: 80));+ }+ },+ onError: (Object failure) => lost(failure),+ onDone: () => lost(null),+ cancelOnError: true,+ );+ _watchers[path] = subscription;+ } catch (failure) {+ _watchError = 'Could not watch keyboard config: $failure';+ }+ }+ }++ bool _related(String path) {+ final normalized = p.normalize(p.absolute(path));+ return _targets.any(+ (target) => target == normalized || p.isWithin(normalized, target),+ );+ }++ void _scheduleReload(Duration delay) {+ if (_disposed) return;+ _debounce?.cancel();+ _debounce = Timer(delay, () {+ _debounce = null;+ unawaited(reload(fromWatcher: true));+ });+ }++ /// Invoked only by the explicit Open Keyboard Config action. Starting the+ /// app never creates a dotfile or rewrites existing user configuration.+ Future<File> ensureFile() async {+ await file.parent.create(recursive: true);+ final handle = await file.open(mode: FileMode.append);+ try {+ await handle.lock(FileLock.exclusive);+ if (await handle.length() == 0) {+ await handle.writeString(+ '''// Harness keyboard overrides. Defaults are inherited.+// Save this file to apply changes. Invalid edits keep the last working keys.+// A null command unbinds a key or a sequence prefix.+// "when" can be "workspace" (default), "terminal", or "picker".+// Workspace bindings are inherited by the other two contexts.+{+ "version": 1,+ "bindings": [+ // Example: move search from Command-P to Command-O.+ // { "keys": "cmd+p", "command": null },+ // { "keys": "cmd+o", "command": "swarm.new" },+ ],+}++// Available command names:+${(_commands.toList()..sort()).map((id) => '// $id').join('\n')}+''',+ );+ await handle.flush();+ }+ } finally {+ await handle.close();+ }+ await reload();+ return file;+ }++ @override+ void dispose() {+ _disposed = true;+ _generation++;+ _debounce?.cancel();+ for (final watcher in _watchers.values) {+ unawaited(watcher.cancel());+ }+ _watchers.clear();+ super.dispose();+ }+}diff --git a/mobile/lib/shortcuts/shortcuts_list.dart b/mobile/lib/shortcuts/shortcuts_list.dartnew file mode 100644index 000000000..a0598204e--- /dev/null+++ b/mobile/lib/shortcuts/shortcuts_list.dart@@ -0,0 +1,360 @@+import 'dart:math' as math;++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import 'app_shortcuts.dart';+import 'app_keymap.dart';+import 'keymap.dart';+import 'key_cap.dart';++/// Every shortcut, grouped and printed — in the two shapes the app needs.+///+/// [ShortcutsList] is the column the ⌘/ sheet draws inside a 420px dialog.+/// [ShortcutsDeck] is the same rows as cards across the Settings pane, which+/// is four times that wide.+///+/// Two layouts, one set of rows: both build from [shortcutRows], so the sheet+/// and the settings screen cannot disagree about what a key does, and neither+/// can drift from what the keys actually do.++/// The sheet's body: one column, group headers, no card chrome — it is already+/// inside a dialog, and a card in a card is one surface too many.+class ShortcutsList extends StatelessWidget {+ const ShortcutsList({super.key, this.contextKind = KeymapContext.workspace});+ final KeymapContext contextKind;++ @override+ Widget build(BuildContext context) {+ final rows = effectiveShortcutRows(context, contextKind);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ for (final group in ShortcutGroup.values) ...[+ _GroupHeader(label: group.label),+ for (final row in rows.where((row) => row.group == group))+ _ShortcutRowView(row: row),+ ],+ const SizedBox(height: 14),+ // The one thing users will otherwise file a bug about.+ const ShortcutsNote(),+ ],+ );+ }+}++/// The Settings pane's body: one card per group, laid out across the width the+/// pane actually has.+///+/// The list this replaced was built for the sheet and clamped to 460px, which+/// left two thirds of a settings window empty and every group in one long+/// column. Cards let the groups sit side by side, so the whole set is one+/// screenful — which is the only reason to open this screen rather than the+/// sheet.+class ShortcutsDeck extends StatelessWidget {+ const ShortcutsDeck({super.key, this.contextKind = KeymapContext.workspace});+ final KeymapContext contextKind;++ /// Narrower than this and a label wraps under its own keycaps. Public so the+ /// deck's tests can render a card at exactly the width it is least able to+ /// fit a chord in, which is the only width the overflow ever showed up at.+ static const double minCardWidth = 280;+ static const double _gap = 12;++ /// Past three columns the cards are wider than the deck needs and the eye+ /// has to travel the full window to read one group.+ static const int _maxColumns = 3;++ /// The deck stops growing here — a shortcut row is a label and a chord, and+ /// stretching that across a maximised display puts a metre of nothing+ /// between them.+ static const double maxWidth = 1040;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final rows = effectiveShortcutRows(context, contextKind);+ final cards = <Widget>[+ for (final group in ShortcutGroup.values)+ _ShortcutCard(+ title: group.label,+ rows: rows.where((row) => row.group == group).toList(),+ ),+ const _TerminalCard(),+ ];++ return LayoutBuilder(+ builder: (context, constraints) {+ final width = math.min(constraints.maxWidth, maxWidth);+ final columns = ((width + _gap) / (minCardWidth + _gap)).floor().clamp(+ 1,+ _maxColumns,+ );++ // Dealt round-robin rather than split into runs, so the cards keep+ // reading left to right in declaration order across the first row.+ // Columns then end at their own heights instead of every card in a row+ // stretching to the tallest — which is what a plain grid would do, and+ // what would leave a three-row card padded out to match a nine-row one.+ final lanes = List.generate(columns, (_) => <Widget>[]);+ for (var i = 0; i < cards.length; i++) {+ lanes[i % columns].add(cards[i]);+ }++ return ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: maxWidth),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ for (var lane = 0; lane < lanes.length; lane++) ...[+ if (lane > 0) const SizedBox(width: _gap),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (var i = 0; i < lanes[lane].length; i++) ...[+ if (i > 0) const SizedBox(height: _gap),+ lanes[lane][i],+ ],+ ],+ ),+ ),+ ],+ ],+ ),+ );+ },+ );+ }+}++/// One group as a raised block — the same recipe a setting is stated in one+/// pane over, so Settings reads as one screen rather than four.+class _ShortcutCard extends StatelessWidget {+ const _ShortcutCard({required this.title, required this.rows});++ final String title;+ final List<ShortcutRow> rows;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Container(+ decoration: BoxDecoration(+ color: grid.AppGlass.surfaceFill,+ borderRadius: BorderRadius.circular(14),+ boxShadow: grid.AppGlass.cardShadow,+ ),+ padding: const EdgeInsets.fromLTRB(6, 14, 6, 10),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(12, 0, 12, 6),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.baseline,+ textBaseline: TextBaseline.alphabetic,+ children: [+ Expanded(child: _CardTitle(title)),+ Text(+ '${rows.length}',+ style: TextStyle(+ color: grid.AppPalette.textFaint,+ fontSize: 10.5,+ fontFeatures: const [FontFeature.tabularFigures()],+ ),+ ),+ ],+ ),+ ),+ for (final row in rows)+ _ShortcutRowView(row: row, padding: _rowPadding),+ ],+ ),+ );+ }++ static const _rowPadding = EdgeInsets.symmetric(horizontal: 12, vertical: 5);+}++/// The keys this app does not take, and who has them.+///+/// Recessed, not raised: it is the one card here that is *not* a list of things+/// you can press in this app, and reading as a well rather than a block is what+/// says so before the title does.+class _TerminalCard extends StatelessWidget {+ const _TerminalCard();++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Container(+ decoration: BoxDecoration(+ color: grid.AppSurface.recess,+ borderRadius: BorderRadius.circular(14),+ ),+ padding: const EdgeInsets.fromLTRB(6, 14, 6, 12),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const Padding(+ padding: EdgeInsets.fromLTRB(12, 0, 12, 6),+ child: _CardTitle('Agent input'),+ ),+ for (final key in kTerminalOwnedKeys)+ Padding(+ padding: _ShortcutCard._rowPadding,+ child: Row(+ children: [+ Expanded(+ child: Text(+ key.label,+ style: TextStyle(+ color: grid.AppPalette.textFaint,+ fontSize: 12.5,+ ),+ ),+ ),+ const SizedBox(width: 16),+ KeyChordView(chords: [key.chord]),+ ],+ ),+ ),+ const Padding(+ padding: EdgeInsets.fromLTRB(12, 8, 12, 0),+ child: ShortcutsNote(bare: true),+ ),+ ],+ ),+ );+ }+}++class _CardTitle extends StatelessWidget {+ const _CardTitle(this.label);++ final String label;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Text(+ label.toUpperCase(),+ style: TextStyle(+ color: grid.AppPalette.textFaint,+ fontSize: 10.5,+ letterSpacing: 0.08 * 10.5,+ fontWeight: grid.AppFont.medium,+ ),+ );+ }+}++/// Why the app takes so few keys — the sentence that turns "these shortcuts are+/// missing" into "those keys belong to the agent".+class ShortcutsNote extends StatelessWidget {+ const ShortcutsNote({super.key, this.bare = false});++ /// Inside the terminal card the wash would be a second surface on a surface,+ /// and the card's own recess already says the same thing. The sheet, which+ /// has nothing around it, keeps the wash.+ final bool bare;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final text = Text(+ 'Harness shortcuts control your workspace. Other input goes to the '+ 'focused agent, where prompt editing and cancellation follow that '+ 'coding agent’s behavior.',+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 11.5,+ height: 1.5,+ ),+ );+ if (bare) return text;+ return Container(+ padding: const EdgeInsets.fromLTRB(11, 10, 11, 10),+ decoration: BoxDecoration(+ color: grid.AppSurface.accentWash,+ borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),+ ),+ child: text,+ );+ }+}++class _GroupHeader extends StatelessWidget {+ const _GroupHeader({required this.label});++ final String label;++ @override+ Widget build(BuildContext context) {+ return Padding(+ padding: const EdgeInsets.only(top: 14, bottom: 6),+ child: _CardTitle(label),+ );+ }+}++/// One shortcut: what it does on the left, the keys that do it on the right.+class _ShortcutRowView extends StatelessWidget {+ const _ShortcutRowView({required this.row, this.padding});++ final ShortcutRow row;+ final EdgeInsets? padding;++ /// Between the label and its keycaps.+ static const double _gutter = 16;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Padding(+ padding: padding ?? const EdgeInsets.symmetric(vertical: 3),+ // [KeyChordView] is a Wrap, but a Row hands an INFLEXIBLE child unbounded+ // width — so it never had the chance to wrap, and a chord wider than the+ // space left simply overflowed the card. Capping it at the row gives the+ // Wrap something to wrap inside.+ //+ // It took a flaky test to find: the widest chord ("Focus the previous+ // pane", 246.5px) fits the 268px row of a three-column deck with 5.5px to+ // spare, and only overflows — by 6.5px — once a card lands on+ // [ShortcutsDeck.minCardWidth] exactly. So the deck looked fine at every+ // width anyone had tried, and CI failed on a layout nobody could see.+ child: LayoutBuilder(+ builder: (context, constraints) => Row(+ crossAxisAlignment: CrossAxisAlignment.center,+ children: [+ Expanded(+ child: Text(+ row.label,+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 12.5,+ ),+ ),+ ),+ const SizedBox(width: _gutter),+ ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth: math.max(0, constraints.maxWidth - _gutter),+ ),+ child: row.chords.isEmpty+ ? Text(+ 'Unassigned',+ style: TextStyle(+ color: grid.AppPalette.textFaint,+ fontSize: 11.5,+ ),+ )+ : KeyChordView(chords: row.chords),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartnew file mode 100644index 000000000..32a04545b--- /dev/null+++ b/mobile/lib/state/app_state.dart@@ -0,0 +1,5621 @@+import 'dart:async';+import 'dart:io' show exit, pid;+import 'dart:math' show Random;++import 'package:dio/dio.dart';+import 'package:flutter/foundation.dart';+import 'package:flutter_riverpod/flutter_riverpod.dart';++import '../analytics/analytics.dart';+import '../api/api_client.dart';+import '../viewer/sign_in_browser.dart';+import '../viewer/viewer_services.dart';+import '../auth/auth_session.dart';+import '../auth/peer_link_client.dart';+import '../auth/sign_in_client.dart';+import '../auth/cli_link.dart';+import '../auth/cli_login.dart';+import '../bootstrap/environment_provisioner.dart';+import '../core/viewer_mode.dart';+import '../core/config.dart';+import '../core/agent_preference.dart';+import '../core/engine_availability.dart';+import '../core/local_hostname.dart';+import '../core/local_git_projects.dart';+import '../core/test_run.dart';+import '../core/models.dart';+import '../core/retry.dart';+import '../settings/config_store.dart';+import '../stats/harness_stats.dart';+import '../terminal/terminal_session.dart';+import '../terminal/remote_media_download.dart';+import '../widgets/engine_identity.dart' show allEngines;+import 'dial_status.dart';+import 'pane_layout_store.dart';+import 'terminal_pane.dart';+import 'swarm.dart';+import '../terminal/terminal_binary.dart';+import '../update/desktop_updater.dart';+import '../update/manual_update_check.dart';+import '../ws/ws_conn.dart';+import '../ws/local_cli_discovery.dart';+import '../ws/ws_pool.dart';+import 'pane_preset.dart';+import 'pane_arrangement.dart';+import 'pending_question.dart';+import '../usage/remote_usage.dart';+import '../usage/usage_accounts.dart';++enum AppStatus {+ bootstrapping,+ checkingEnvironment,+ preparingEnvironment,+ unauthenticated,+ authenticated,+}++enum AgentLoadStatus { idle, needsLink, loading, loaded, error }++enum MachineTransportMode { cloudE2ee, localPlaintext, localOffline }++/// Result of [AppNotifier.restartAgent]. [error] null means the RPC succeeded; [resumed] then says+/// whether the daemon reattached the agent's prior session or fell back to a fresh one (e.g. the+/// engine's resume flag wasn't recognized) — worth telling the user about, since it's not a failure+/// but the conversation may not have continued the way "Restart" implies.+class RestartAgentResult {+ final String? error;+ final bool resumed;++ const RestartAgentResult({this.error, this.resumed = true});+}++/// One deliberate creation, retained by the form if its reply is lost. Reusing+/// it checks the original request; opening New agent starts a fresh intent.+class AgentCreationAttempt {+ AgentCreationAttempt() {+ final random = Random.secure();+ _id = List.generate(+ 16,+ (_) => random.nextInt(256),+ ).map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();+ }++ late final String _id;+ String? _machineId, _targetId;+ Map<String, dynamic>? _choices;+ PaneSplitRequest? _split;+ Future<String?>? _inFlight;+ bool _awaitingConfirmation = false, _finished = false;+ String? _outcome;++ bool get awaitingConfirmation => _awaitingConfirmation;++ String? _complete(String? error) {+ _finished = true;+ _awaitingConfirmation = false;+ return _outcome = error;+ }+}++String? _normalizeComputerId(String? raw) {+ if (raw == null) return null;+ final value = raw.trim().toLowerCase().replaceAll('-', '');+ return RegExp(r'^[a-f0-9]{16,64}$').hasMatch(value) ? value : null;+}++/// Explicit, compile-time guarded fixture used only by `main_local_manual.dart`.+///+/// It lets a normal Flutter window exercise the local Backend -> Harness CLI ->+/// tmux path without depending on SSO. The API key and setup token are random,+/// disposable values produced by the local launcher and are never persisted.+class LocalManualFixture {+ final String apiBaseUrl;+ final String apiKey;+ final String machineId;+ final String machineName;+ final String setupToken;++ const LocalManualFixture({+ required this.apiBaseUrl,+ required this.apiKey,+ required this.machineId,+ required this.machineName,+ required this.setupToken,+ });+}++@visibleForTesting+Map<String, dynamic> eventWithClearPayload(+ Map<String, dynamic> frame,+ String type,+ Map<String, dynamic> payload,+) => {...frame, 'type': type, 'payload': payload};++class MachineState {+ Machine machine;+ ConnectionStatus connectionStatus = ConnectionStatus.disconnected;+ MachineTransportMode transportMode = MachineTransportMode.cloudE2ee;++ /// Set when this machine is bound to the local CLI's stable computer id. A+ /// local machine never falls back to cloud E2EE while that identity exists.+ bool localOnly = false;+ LocalCliEndpoint? localEndpoint;+ Map<String, AgentProject> localProjects = const {};+ // Set when the local CLI's relay reports NO_PEER_LINK for this (non-local) machine — it needs+ // `harness link connect <machineId>` (the other machine's remote password) before it can+ // connect. The CLI owns E2EE entirely now; this is just "is trust established yet", not a+ // crypto/pairing state the app has any data for.+ bool needsLink = false;+ List<Agent> agents = [];+ AgentLoadStatus agentLoadStatus = AgentLoadStatus.idle;+ bool agentsRefreshing = false;+ String? agentsLoadError;+ Future<void>? agentsLoadInFlight;+ Future<void>? terminalCapabilityLoadInFlight;+ String? activeAgentId;+ bool terminalCapabilityLoaded = false;+ bool terminalCapabilityAvailable = false;+ String? terminalCapabilityError;+ // Whether this machine's CLI daemon understands `terminal_paste` (a clipboard paste delivered as+ // one atomic tmux paste-buffer, not chunked like ordinary keystrokes — see TerminalSession.pasteText).+ // False for any CLI published before this existed; the panel falls back to the old chunked path.+ bool terminalPasteRawAvailable = false;+ // Whether this machine's CLI daemon understands TerminalBinaryKind.imagePaste (a native clipboard+ // IMAGE paste — see TerminalSession.pasteImage). False for any CLI published before this existed;+ // the panel falls back to forwarding a bare Ctrl+V, today's only option for an image paste.+ bool terminalImagePasteAvailable = false;+ // Whether this machine's CLI daemon understands TerminalBinaryKind.pasteFile (a dropped non-image+ // file, written to disk on that machine and pasted as a path — see TerminalSession.pasteFile).+ // Only consulted for a REMOTE pane; a local one pastes its own path directly and never needs this.+ bool terminalPasteFileAvailable = false;+ bool mediaPreviewAvailable = false;+ // Which engines this machine actually has, as this machine answered it. Kept+ // on MachineState rather than globally because that is the whole point: two+ // machines on one account hold different engines, and the Docker rig holds+ // exactly one. See `engines_probe` in the CLI's backendSocket.+ final MachineEngines engines = MachineEngines();+ // Adapter/manager presence for this machine, from `node_status` pushes —+ // distinct from `connectionStatus`, which only reflects OUR websocket to+ // the backend. null = not seen yet (initial connect).+ bool? nodeOnline;+ // The agent the user selected while the Harness adapter was offline. Keep+ // this separate from activeAgentId so the UI can show a join guide without+ // opening a terminal stream against an unavailable node.+ String? pendingOfflineAgentId;+ final Set<String> processingAgentIds = {};++ /// Agents on this machine that have stopped to ask something, by agentId.+ /// At most one per agent: a pane shows one dialog at a time, and the daemon+ /// re-announces the same open question rather than queueing a second.+ final Map<String, PendingQuestion> blockedAgents = {};+ final Map<String, String> sessionAgentIds = {};+ // Turn events can arrive while the initial agents_list RPC is still in+ // flight. Retain session correlation until that snapshot binds the row.+ final Set<String> pendingProcessingSessions = {};++ MachineState(this.machine);++ bool get isRemote => machine.authMode == MachineAuthMode.remote;+ bool get isLocalMachine => localOnly || localEndpoint != null;+ bool get usesLocalTransport => localEndpoint != null;++ AgentProject? projectOf(Agent agent) =>+ agent.project ??+ localProjects[agent.id] ??+ localEndpoint?.agentProjects[agent.id];++ Agent? get activeAgent {+ for (final agent in agents) {+ if (agent.id == activeAgentId) return agent;+ }+ return null;+ }+}++/// 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;+}++/// One line in the rail: a machine, or an agent under one.+///+/// A record rather than a widget key, because the cursor has to survive a+/// rebuild that changes what is on screen — an agent finishing, a machine going+/// offline — and an index into a list of widgets does not.+@immutable+class RailRow {+ const RailRow({required this.machineId, this.agentId});++ final String machineId;++ /// Null for the machine's own row.+ final String? agentId;++ @override+ bool operator ==(Object other) =>+ other is RailRow &&+ other.machineId == machineId &&+ other.agentId == agentId;++ @override+ int get hashCode => Object.hash(machineId, agentId);+}++class AppNotifier extends ChangeNotifier {+ final AuthSession session;+ AppConfig config;+ late ApiClient api;+ /// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,+ /// [ViewerServices.login] in a viewer build — which has no CLI — under one name, so every call+ /// site reads the same in both.+ late final SignInClient cliLogin;+ final CliLink cliLink;++ /// Links to other machines by remote password: [cliLink] in a desktop build, the app itself in a+ /// viewer. THIS machine's own remote password stays on [cliLink] — a viewer is not a machine, and+ /// has no password for anyone to link to.+ late final PeerLinkClient peerLinks;++ /// A viewer build's stand-ins for the harness CLI (`lib/viewer/`); null on a desktop build.+ 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 LocalManualFixture? localManualFixture;+ final Duration turnActivityTimeout;+ final LocalCliDiscovery? localCliDiscovery;++ /// ONE discovery for the whole notifier. It used to be built fresh at each of+ /// three call sites, which was harmless while it was stateless and is not+ /// now that the supervisor's ready-transition callback lives on it.+ ///+ /// `late`, so it reads `config` on first use — which is [ensureCliDaemonReady]+ /// during bootstrap, AFTER the persisted config has been loaded over the+ /// default. Touch it earlier and it freezes the wrong `localCliBaseUrl`.+ late final LocalCliDiscovery _discovery =+ localCliDiscovery ?? LocalCliDiscovery(config: config);+ final EnvironmentProvisioner? environmentProvisioner;+ final DesktopUpdater? desktopUpdater;+ @visibleForTesting+ final WsConn Function(String machineId)? connectionForTest;+ final Map<String, Timer> _turnActivityWatchdogs = {};++ /// When this launch became signed in, and by which route — until the first+ /// message of that session has been reported, after which it is null.+ ///+ /// One record for the whole app, not one per agent: the question is how long+ /// somebody sits signed in before talking to anything at all, and which agent+ /// they finally picked is `agent_created`'s business. A session where nobody+ /// ever sends a message simply leaves this set until sign-out or quit, which+ /// is exactly the population the event exists to measure the absence of.+ ({DateTime at, String from})? _awaitingFirstMessage;++ final Map<String, Timer> _offlineRetryTimers = {};+ // Periodic retry for a machine the relay reported NO_PEER_LINK for — a `harness link connect` run+ // in a terminal (or another app instance) has no way to notify this one, so this is what makes the+ // app pick up a fresh link within a few seconds instead of only on the next manual click/restart.+ final Map<String, Timer> _linkRetryTimers = {};+ // Safety-net reconciliation for a connected machine's agent list, on top of the push events+ // (agent_synced/agent_created/agent_renamed/agent_deleted) that normally keep it live — catches the+ // rare case a push event was dropped. Runs silently: see _syncAgentsIfChanged.+ final Map<String, Timer> _agentSyncTimers = {};+ // Keeps the local `harness` daemon alive for the whole app run — started once after the first+ // successful bootstrap (see `ensureCliDaemonReady`), cancelled on dispose. Cancelling only stops this+ // Dart-side loop; the daemon itself self-daemonizes and must keep running after the app quits.+ Timer? _daemonSupervisionTimer;++ /// The last [ensureCliDaemonReady] did not reach a ready daemon — the one+ /// error the supervisor's ready transition is allowed to retry away.+ bool _daemonGateFailed = false;+ // Update checks do not depend on the daemon or SSO. A signed-out user should+ // still be able to replace a broken desktop build from the login screen.+ Timer? _updateCheckTimer;+ String? _skippedDesktopUpdateVersion;+ UpdateInfo? availableUpdate;+ bool isCheckingForUpdate = false;+ bool isInstallingUpdate = false;+ String? updateError;+ final Set<String> _offlinePollsInFlight = {};+ final Set<String> _offlineRecoveryInFlight = {};+ bool _disposed = false;++ // Account and inventory replies belong to the session that requested them.+ // Signing out invalidates them before asynchronous connection cleanup.+ int _authRevision = 0;+ Future<void>? _profileInFlight;++ bool _authWorkCurrent(int revision) =>+ !_disposed && revision == _authRevision;++ int _invalidateAuthWork() {+ _resetLoginBrowser();+ _loginAuthorized = false;+ _profileInFlight = null;+ _retryInFlight = null;+ machinesLoading = false;+ return ++_authRevision;+ }++ WsPool? _pool;+ late String _autonomousEnv;+ String? _lastError;+ // Retrying re-runs `refreshMachines()` — a real fix for "could not load+ // machines" or a daemon hiccup, but a no-op for a failure that already+ // finished (an agent's launch), where the only honest control is to+ // dismiss it.+ bool _lastErrorRetryable = true;+ // Shown on the pre-navigation `bootstrapping` screen while [_finishBootstrapSignedIn] waits on the+ // local daemon — null the rest of the time, including once [status] flips to `authenticated`.+ String? _bootStatusMessage;+ EnvironmentReadiness environmentReadiness = EnvironmentReadiness.initial();+ bool _environmentSetupInFlight = false;+ // Polls a step stuck in needsTerminal/failed every 5s (see `_scheduleEnvironmentRecheck`) so a user+ // who fixes it by hand in their own terminal doesn't have to remember to click Recheck. A one-shot+ // Timer that reschedules itself rather than `Timer.periodic`, so a slow recheck can't overlap with+ // the next tick.+ Timer? _environmentRecheckTimer;++ /// Whether a stuck step is being auto-polled right now — drives the "Checking automatically…"+ /// caption on [EnvironmentSetupScreen] alongside its Recheck button.+ bool get environmentRecheckPending => _environmentRecheckTimer != null;++ /// Whether a provisioning run (initial or a per-step recheck) is in flight — lets the setup+ /// screen disable its Recheck/Start over buttons and show a spinner instead of a second click+ /// racing the first.+ bool get environmentSetupInFlight => _environmentSetupInFlight;++ // The daemon's own advertised local-ws endpoint — the dial target for EVERY machine's data plane+ // now, not just this computer's own one (see src/lib/remoteRelay.ts in the harness CLI repo: a+ // foreign machineId is relayed to backend transparently, so the app never dials backend directly).+ LocalCliEndpoint? _cliEndpoint;+ late final _localGitProjects = LocalGitProjects(+ onChanged: _applyLocalGitProjects,+ );++ AppStatus status = AppStatus.bootstrapping;+ CurrentUserProfile? currentUser;+ List<Machine> machines = [];+ final Map<String, MachineState> machineStates = {};+ final Set<String> expandedMachines = {};+ String? selectedMachineId;++ /// Swarms own arrangements; a shared pane owns one live terminal controller.+ final List<Swarm> swarms = [Swarm(id: 'swarm-1')];+ String _activeSwarmId = 'swarm-1';+ int _nextSwarmId = 2;+ static const maxSwarms = 24;+ static const maxClosedSwarms = 24;+ final List<ClosedWork> _closedHistory = [];+ int _nextClosedHistoryId = 1;+ List<ClosedWork> get closedHistory =>+ List.unmodifiable(_closedHistory.reversed);+ List<ClosedSwarm> get closedSwarms =>+ List.unmodifiable(_closedHistory.reversed.whereType<ClosedSwarm>());+ bool get canReopenClosedSwarm {+ final saved = _closedHistory.whereType<ClosedSwarm>().lastOrNull;+ return saved != null && _canReopenSwarm(saved);+ }++ bool get canReopenLastClosed =>+ _closedHistory.isNotEmpty &&+ canReopenClosed(_closedHistory.last.historyId);++ bool canReopenClosed(String historyId) {+ if (_disposed) return false;+ final entry = _closedHistory+ .where((entry) => entry.historyId == historyId)+ .firstOrNull;+ if (entry is ClosedSwarm) return _canReopenSwarm(entry);+ if (entry is! ClosedAgent) return false;+ final target = swarms.where((s) => s.id == entry.swarmId).firstOrNull;+ return target == null+ ? swarms.length < maxSwarms+ : target.panes.length < maxPanes ||+ target.panes.any(+ (p) =>+ p.machineId == entry.machineId &&+ p.agentId == entry.agentId,+ );+ }++ bool _canReopenSwarm(ClosedSwarm saved) {+ if (_disposed) return false;+ final target = swarms.where((swarm) => swarm.id == saved.id).firstOrNull;+ if (target == null) return swarms.length < maxSwarms;+ final present = {+ for (final pane in target.panes) (pane.machineId, pane.agentId),+ };+ final missing = {+ for (final pane in saved.panes)+ if (!present.contains((pane.machineId, pane.agentId)))+ (pane.machineId, pane.agentId),+ };+ return target.panes.length + missing.length <= maxPanes;+ }++ void _rememberClosed(ClosedWork entry) {+ // An unused starter has no work to recover. This also covers empty pages+ // restored from builds that did not mark them as drafts.+ if (entry is ClosedSwarm &&+ entry.name == 'New Harness' &&+ entry.panes.isEmpty &&+ entry.presets.isEmpty) {+ return;+ }+ _closedHistory.add(entry);+ if (_closedHistory.length > maxClosedSwarms) _closedHistory.removeAt(0);+ }++ Swarm get activeSwarm => swarms.firstWhere(+ (s) => s.id == _activeSwarmId,+ orElse: () => swarms.first,+ );+ List<TerminalPane> get panes => activeSwarm.panes;+ Iterable<TerminalPane> get allPanes => swarms.expand((s) => s.panes).toSet();+ String get activeSwarmId => activeSwarm.id;+ bool get canOpenNewTab =>+ swarms.length < maxSwarms || swarms.any((swarm) => swarm.isEmptyStarter);++ // A New Harness remains temporary until it has content or a custom name.+ // The return destination is session-local; abandoned drafts are never saved.+ final _draftSwarmReturns = <String, String>{};++ bool isDraftSwarm(String id) {+ if (!_draftSwarmReturns.containsKey(id)) return false;+ final swarm = swarms.where((swarm) => swarm.id == id).firstOrNull;+ return swarm != null &&+ swarm.panes.isEmpty &&+ swarm.name == 'New Harness' &&+ swarm.presets.isEmpty;+ }++ void newSwarm({String name = 'New Harness', bool draft = false}) {+ // Every New Tab entry point reuses the existing start page, including+ // when another tab is selected or the tab limit has been reached.+ if (name == 'New Harness') {+ final starter = activeSwarm.isEmptyStarter+ ? activeSwarm+ : swarms.where((swarm) => swarm.isEmptyStarter).firstOrNull;+ if (starter != null) {+ if (starter.id != activeSwarmId) selectSwarm(starter.id);+ return;+ }+ }+ if (swarms.length >= maxSwarms) return;+ while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {+ _nextSwarmId++;+ }+ final swarm = Swarm(id: 'swarm-${_nextSwarmId++}', name: name);+ if (draft) {+ _draftSwarmReturns[swarm.id] =+ _draftSwarmReturns[activeSwarmId] ?? activeSwarmId;+ }+ swarms.add(swarm);+ selectSwarm(swarm.id);+ }++ void selectSwarm(String id, {bool attachPending = true}) {+ if (!swarms.any((s) => s.id == id)) return;+ if (id != activeSwarmId && isDraftSwarm(activeSwarmId)) {+ final abandoned = activeSwarmId;+ swarms.removeWhere((swarm) => swarm.id == abandoned);+ _draftSwarmReturns.remove(abandoned);+ }+ _activeSwarmId = id;+ railFocused = false;+ final pane = focusedPane;+ selectedMachineId = pane?.machineId;+ _persistLayout();+ _announceAppFocus();+ if (attachPending) {+ for (final machine in machineStates.values) {+ _attachPendingPanes(machine, retryExisting: false);+ }+ }+ notifyListeners();+ }++ /// Cancel an untouched New Harness without closing a session or recording+ /// Recently Closed. A sole workspace remains the app's starting screen.+ bool cancelSwarmDraft(String id) {+ final returnId = _draftSwarmReturns[id];+ final target = swarms.where((swarm) => swarm.id == id).firstOrNull;+ if (returnId == null ||+ target == null ||+ target.panes.isNotEmpty ||+ target.name != 'New Harness' ||+ target.presets.isNotEmpty ||+ swarms.length == 1) {+ return false;+ }+ final wasActive = activeSwarmId == id;+ swarms.remove(target);+ _draftSwarmReturns.remove(id);+ if (wasActive) {+ selectSwarm(+ swarms.any((swarm) => swarm.id == returnId) ? returnId : swarms.last.id,+ );+ } else {+ _persistLayout();+ notifyListeners();+ }+ return true;+ }++ /// Navigate to an existing view without opening, retrying or taking control+ /// of a terminal. A shared view prefers the current Swarm, then the requested+ /// owner. Publish the destination and its focus together, preserving layout.+ bool revealAgentView(+ String machineId,+ String agentId, {+ String? preferredSwarmId,+ }) {+ if (_disposed) return false;+ bool contains(Swarm swarm) => swarm.panes.any(+ (p) => p.machineId == machineId && p.agentId == agentId,+ );+ final owner = contains(activeSwarm)+ ? activeSwarm+ : swarms+ .where((s) => s.id == preferredSwarmId && contains(s))+ .firstOrNull ??+ swarms.where(contains).firstOrNull;+ if (owner == null) return false;+ final pane = owner.panes.firstWhere(+ (p) => p.machineId == machineId && p.agentId == agentId,+ );+ if (owner == activeSwarm) {+ focusPane(pane.id, reveal: true);+ return true;+ }+ if (owner.focusedPaneId != pane.id) {+ owner.previousPaneId = owner.focusedPaneId;+ owner.focusedPaneId = pane.id;+ }+ if (owner.zoomedPaneId != null) owner.zoomedPaneId = pane.id;+ _activeSwarmId = owner.id;+ railFocused = false;+ selectedMachineId = machineId;+ _paneFocusRequest++;+ _persistLayout();+ _announceAppFocus();+ notifyListeners();+ return true;+ }++ /// Command-number follows the current visual tab order, retaining each tab's+ /// focused pane. A missing position is a no-op, never a pane selection.+ void selectSwarmByIndex(int index) {+ if (index < 0 || index >= swarms.length) return;+ selectSwarm(swarms[index].id);+ }++ void stepSwarm(int delta) {+ final index = swarms.indexOf(activeSwarm);+ selectSwarm(swarms[(index + delta) % swarms.length].id);+ }++ void renameSwarm(String id, String name) {+ final clean = name.trim();+ if (clean.isEmpty) return;+ final swarm = swarms.where((s) => s.id == id).firstOrNull;+ if (swarm == null) return;+ swarm.name = clean.length > 80 ? clean.substring(0, 80) : clean;+ _persistLayout();+ notifyListeners();+ }++ void reorderSwarm(String id, int destination) {+ final index = swarms.indexWhere((s) => s.id == id);+ if (index < 0) return;+ final swarm = swarms.removeAt(index);+ swarms.insert(destination.clamp(0, swarms.length), swarm);+ _persistLayout();+ notifyListeners();+ }++ Future<void> closeSwarm(String id) async {+ if (cancelSwarmDraft(id)) return;+ final index = swarms.indexWhere((s) => s.id == id);+ if (index < 0) return;+ // Held ⌘W must not manufacture and close an endless sequence of blank+ // welcome tabs, evicting the real work from recently closed history.+ if (swarms.length == 1 &&+ swarms.single.panes.isEmpty &&+ swarms.single.name == 'New Harness' &&+ swarms.single.presets.isEmpty) {+ return;+ }+ final removed = swarms.removeAt(index);+ Swarm? replacement;+ if (swarms.isEmpty) {+ replacement = Swarm(id: 'swarm-${_nextSwarmId++}');+ swarms.add(replacement);+ }+ _rememberClosed(+ ClosedSwarm(+ removed,+ historyId: 'closed-${_nextClosedHistoryId++}',+ index: index,+ replacement: replacement,+ engine: removed.panes.length == 1+ ? stateOf(removed.panes.single.machineId)?.agents+ .where(+ (agent) => agent.id == removed.panes.single.agentId,+ )+ .firstOrNull+ ?.engine ??+ removed.panes.single.session?.engineId+ : null,+ ),+ );+ if (_activeSwarmId == id) {+ _activeSwarmId = swarms[index.clamp(0, swarms.length - 1)].id;+ }+ _persistLayout();+ notifyListeners();+ selectedMachineId = focusedPane?.machineId;+ _announceAppFocus();+ for (final machine in machineStates.values) {+ _attachPendingPanes(machine);+ }+ for (final pane in removed.panes) {+ if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);+ }+ }++ void reopenClosedSwarm({String? historyId}) {+ if (_disposed) return;+ final index = _closedHistory.lastIndexWhere(+ (entry) =>+ entry is ClosedSwarm &&+ (historyId == null || entry.historyId == historyId),+ );+ if (index < 0) return;+ final saved = _closedHistory[index] as ClosedSwarm;+ if (!_canReopenSwarm(saved)) return;+ _closedHistory.removeAt(index);+ if (swarms.length == 1 && saved.replacesUntouchedWelcome(swarms.single)) {+ swarms.clear();+ }+ final pool = {+ for (final pane in allPanes) (pane.machineId, pane.agentId): pane,+ };+ final target = swarms.where((swarm) => swarm.id == saved.id).firstOrNull;+ if (target != null) {+ // Reopening an individual agent may have restored this swarm already.+ // Reunite its missing views without cloning the tab or overwriting edits+ // made since then. Live peers keep their terminal, draft and selection.+ final present = {+ for (final pane in target.panes) (pane.machineId, pane.agentId),+ };+ final previousCount = target.panes.length;+ for (final entry in saved.panes) {+ if (!present.add((entry.machineId, entry.agentId))) continue;+ target.panes.add(+ pool.putIfAbsent(+ (entry.machineId, entry.agentId),+ () => TerminalPane(+ id: _nextPaneId++,+ machineId: entry.machineId,+ agentId: entry.agentId,+ )..composerVisible = entry.composerVisible,+ ),+ );+ }+ if (target.panes.length != previousCount) {+ // An old manual shape for this count describes different membership.+ // Keep current presets/pins and use the normal layout for added views.+ target.paneSizes.remove('${target.panes.length}:manual');+ target.arranged = null;+ target.arrangedKey = null;+ }+ target.focusedPaneId ??= target.panes.firstOrNull?.id;+ _paneFocusRequest++;+ selectSwarm(target.id);+ return;+ }+ final restored = Swarm(id: saved.id, name: saved.name)+ ..gridColumns = saved.gridColumns+ ..presets.addAll(saved.presets)+ ..paneSizes.addAll(saved.paneSizes);+ for (final entry in saved.panes) {+ final pane = pool.putIfAbsent(+ (entry.machineId, entry.agentId),+ () => TerminalPane(+ id: _nextPaneId++,+ machineId: entry.machineId,+ agentId: entry.agentId,+ )..composerVisible = entry.composerVisible,+ );+ restored.panes.add(pane);+ if (entry.pinnedSlot != null) {+ restored.pinnedSlots[pane.id] = entry.pinnedSlot!;+ }+ }+ int? paneAt(int index) => index >= 0 && index < restored.panes.length+ ? restored.panes[index].id+ : null;+ restored.focusedPaneId =+ paneAt(saved.focus) ?? restored.panes.firstOrNull?.id;+ restored.previousPaneId = paneAt(saved.previousFocus);+ restored.zoomedPaneId = paneAt(saved.zoom);+ swarms.insert(saved.index.clamp(0, swarms.length), restored);+ selectSwarm(restored.id);+ }++ /// Reopen the chosen closure, or the newest closure for Cmd-Shift-T.+ /// Membership is restored synchronously; a slow detach cannot resurrect an+ /// old controller or redirect the destination after a network wait.+ bool reopenClosed({String? historyId}) {+ final id = historyId ?? _closedHistory.lastOrNull?.historyId;+ if (id == null || !canReopenClosed(id)) return false;+ final index = _closedHistory.indexWhere((entry) => entry.historyId == id);+ final saved = _closedHistory[index];+ if (saved is ClosedSwarm) {+ reopenClosedSwarm(historyId: id);+ return true;+ }+ final agent = saved as ClosedAgent;+ _closedHistory.removeAt(index);+ var target = swarms.where((s) => s.id == agent.swarmId).firstOrNull;+ if (target == null) {+ target = Swarm(id: agent.swarmId, name: agent.swarmName);+ swarms.add(target);+ }+ final pane =+ allPanes+ .where(+ (p) =>+ p.machineId == agent.machineId && p.agentId == agent.agentId,+ )+ .firstOrNull ??+ (TerminalPane(+ id: _nextPaneId++,+ machineId: agent.machineId,+ agentId: agent.agentId,+ )..composerVisible = agent.composerVisible);+ if (!target.panes.contains(pane)) {+ final restoreManual =+ agent.manualLayout != null &&+ listEquals(+ target.panes.map((p) => (p.machineId, p.agentId)).toList(),+ agent.remainingAgents,+ ) &&+ (target.panes.length == 1 ||+ listEquals(+ target.manualLayout?.tiles,+ agent.manualLayout!.remove(agent.index)?.tiles,+ ));+ if (restoreManual) {+ target.pinnedSlots.updateAll(+ (_, slot) => slot >= agent.index ? slot + 1 : slot,+ );+ }+ target.panes.insert(agent.index.clamp(0, target.panes.length), pane);+ if (restoreManual) {+ target.savePaneSizes(+ '${target.panes.length}:manual',+ agent.manualLayout!,+ );+ } else if (agent.manualLayout != null) {+ target.paneSizes.remove('${target.panes.length}:manual');+ }+ if (agent.pinnedSlot != null &&+ !target.pinnedSlots.containsValue(agent.pinnedSlot)) {+ target.pinnedSlots[pane.id] = agent.pinnedSlot!;+ }+ }+ if (target.focusedPaneId != pane.id) {+ target.previousPaneId = target.focusedPaneId;+ }+ target.focusedPaneId = pane.id;+ if (agent.zoomed || target.zoomedPaneId != null) {+ target.zoomedPaneId = pane.id;+ }+ _activeSwarmId = target.id;+ _settlePins();+ _paneFocusRequest++;+ selectSwarm(target.id);+ return true;+ }++ /// Capture the destination before any network wait or tab change.+ Future<void> addAgentToSwarm(+ String machineId,+ String agentId, {+ String? swarmId,+ }) => assignAgentToPane(null, machineId, agentId, swarmId: swarmId);++ 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+ /// WebView, so a click makes that pane's WKWebView the first responder and+ /// AppKit routes keys there without asking. This is for everything that has+ /// no pointer behind it: the dial's scroll and focus frames, and which agent+ /// the rail draws as current.+ 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;++ /// An explicit relayout reveals live output even in tiles whose rectangle+ /// does not change. This is view intent, so it is never persisted.+ int _paneLayoutRequest = 0;+ int get paneLayoutRequest => _paneLayoutRequest;++ /// The chosen shape for a grid of this size, or the shipped one.+ Map<int, PanePreset> get panePresets => activeSwarm.presets;++ PanePreset? presetFor(int paneCount) =>+ panePresets[paneCount] ?? PanePreset.defaultFor(paneCount);++ /// Choosing a preset also resets custom sizes for that pane count. Selecting+ /// the current preset in Command-S is the quick way back to its proportions.+ void setPreset(int paneCount, PanePreset preset) {+ if (!preset.supportsCount(paneCount)) return;+ final resized = activeSwarm.paneSizes.keys.any(+ (key) => key.startsWith('$paneCount:'),+ );+ _paneLayoutRequest++;+ if (presetFor(paneCount) == preset && !resized) {+ notifyListeners();+ return;+ }+ panePresets[paneCount] = preset;+ activeSwarm.paneSizes.removeWhere(+ (key, _) => key.startsWith('$paneCount:'),+ );+ activeSwarm.arranged = null;+ activeSwarm.arrangedKey = null;+ notifyListeners();+ _persistLayout();+ }++ int _paneResizeRequest = 0;+ int get paneResizeRequest => _paneResizeRequest;+ void beginPaneResize() {+ if (panes.length < 2 || zoomedPaneId != null) return;+ _paneResizeRequest++;+ notifyListeners();+ }++ PaneSplitRequest? preparePaneSplit(PaneResizeAxis axis, {int? paneId}) {+ if (zoomedPaneId != null || panes.length >= maxPanes) return null;+ final targetId = paneId ?? focusedPaneId;+ final before = activeSwarm.arranged;+ final minimum = activeSwarm.arrangedMinimum;+ final index = panes.indexWhere(+ (p) => p.id == targetId && p.agentId != null,+ );+ if (before == null ||+ minimum == null ||+ before.tiles.length != panes.length) {+ return null;+ }+ final after = before.split(index, axis, minimum: minimum);+ if (after == null || targetId == null) return null;+ return PaneSplitRequest(+ swarmId: activeSwarmId,+ paneId: targetId,+ axis: axis,+ paneIds: panes.map((p) => p.id),+ before: before,+ after: after,+ );+ }++ bool isPaneSplitCurrent(PaneSplitRequest split) {+ final target = swarms.where((s) => s.id == split.swarmId).firstOrNull;+ final minimum = target?.arrangedMinimum;+ return !_disposed &&+ target != null &&+ target.zoomedPaneId == null &&+ minimum != null &&+ listEquals(target.panes.map((p) => p.id).toList(), split.paneIds) &&+ listEquals(target.arranged?.tiles, split.before.tiles) &&+ split.before.split(+ split.paneIds.indexOf(split.paneId),+ split.axis,+ minimum: minimum,+ ) !=+ null;+ }++ /// Drag frames only update in-memory intent. The completed gesture performs+ /// one ordinary coalesced layout save; terminal sessions remain untouched.+ bool resizePanes(+ String swarmId,+ String layoutKey,+ PaneArrangement arrangement, {+ bool persist = true,+ }) {+ if (activeSwarmId != swarmId ||+ zoomedPaneId != null ||+ arrangement.tiles.length != panes.length ||+ activeSwarm.arrangedKey != layoutKey) {+ return false;+ }+ if (identical(activeSwarm.paneSizes[layoutKey], arrangement)) {+ if (persist) _persistLayout();+ return true;+ }+ activeSwarm.savePaneSizes(layoutKey, arrangement);+ activeSwarm.arranged = arrangement;+ _paneLayoutRequest++;+ notifyListeners();+ if (persist) _persistLayout();+ return true;+ }++ void resetPaneSizes() {+ setPreset(panes.length, presetFor(panes.length) ?? PanePreset.auto);+ }++ int _nextPaneId = 1;++ static const maxPanes = 64;+ // Set only while `harness login --force --json` is waiting for the user to finish SSO in their system+ // browser. It arrives PART WAY THROUGH the flow — the CLI has to start before it can hand one+ // over. It identifies the current sign-in link; [signingIn] tracks the whole+ // attempt, including CLI startup and workspace restoration.+ String? pendingAuthorizeUrl;+ bool openingLoginBrowser = false;+ String? loginBrowserError;+ int _loginBrowserRevision = 0;+ bool _loginAuthorized = false;+ bool get canCancelLogin => signingIn && !_loginAuthorized;++ /// True from the moment the user presses Sign in until the flow settles, one way or the other.+ ///+ /// **Not the same question as `pendingAuthorizeUrl != null`, and the difference was a bug.**+ /// `login()` flips [status] to `bootstrapping` immediately, but the authorize URL only lands+ /// once the CLI has spawned Node and got as far as printing one — seconds later — and it is+ /// cleared again in `finally` while `_finishBootstrapSignedIn()` is still restoring panes and+ /// fetching machines. `RootShell` keyed the sign-in screen off the URL, so both of those windows+ /// dropped the user onto a bare full-screen spinner: the card they were looking at vanished on+ /// the click, came back, then vanished again on success.+ ///+ /// This flag spans the whole flow, so the screen the user pressed a button on stays put.+ bool signingIn = false;++ AppNotifier({+ required AppConfig config,+ required AuthSession authSession,+ ConfigStore? configStore,+ this.localManualFixture,+ this.localCliDiscovery,+ this.environmentProvisioner,+ this.desktopUpdater,+ this.connectionForTest,+ SignInClient? cliLogin,+ CliLink? cliLink,+ PeerLinkClient? peerLinks,+ ViewerServices? viewer,+ PaneLayoutStore? paneLayoutStore,+ this.turnActivityTimeout = const Duration(seconds: 12),+ }) : _paneLayout = paneLayoutStore,+ // Remembers "a dial has been seen here" on the same terms the pane+ // layout is remembered: with a layout store there is a state file, and+ // without one (the tests) nothing is written anywhere.+ dial = DialState(paneLayoutStore?.storage),+ agentPreference = AgentPreference(paneLayoutStore?.storage),+ session = authSession,+ _store = configStore,+ cliLink = cliLink ?? CliLink(),+ config = configStore?.config ?? config,+ viewer =+ viewer ??+ (kViewerMode+ ? ViewerServices(+ config: configStore?.config ?? config,+ session: authSession,+ )+ : null) {+ this.cliLogin = cliLogin ?? this.viewer?.login ?? CliLogin();+ this.peerLinks = peerLinks ?? this.viewer?.links ?? this.cliLink;+ _autonomousEnv = this.config.autonomousEnv;+ api = _newApiClient();+ }++ /// Through the local CLI in a desktop build; straight to the backend, signed, in a viewer.+ ApiClient _newApiClient() =>+ ApiClient(config: config, session: session, auth: viewer?.auth);++ String? get lastError => _lastError;+ bool get lastErrorRetryable => _lastErrorRetryable;+ String? get bootStatusMessage => _bootStatusMessage;++ /// Clears the error strip without retrying anything, for a failure retrying+ /// cannot fix (see [_lastErrorRetryable]).+ void dismissError() {+ _lastError = null;+ notifyListeners();+ }++ String get autonomousEnv => _autonomousEnv;+ bool get hasAvailableUpdate => availableUpdate != null;++ static const offlineRetryInterval = Duration(seconds: 5);+ static const agentSyncInterval = Duration(seconds: 60);++ MachineState? stateOf(String machineId) => machineStates[machineId];++ // ── the grid ────────────────────────────────────────────────────────────────────────────────────++ /// Null means "remember nothing", which is what a test gets by default.+ ///+ /// Deliberately NOT `?? PaneLayoutStore()` like the stores above it. Those+ /// only read, and only when asked; this one WRITES on every pane change, and+ /// a widget test that opens an agent would otherwise rewrite the layout in+ /// the developer's own ~/.harness state file. Production passes one; see+ /// [appStateProvider].+ final PaneLayoutStore? _paneLayout;++ /// The dial on this desk, for the rail's device row. Fed by `dial_status`+ /// frames from the local daemon; its own notifier, so the row rebuilds+ /// without dragging the whole rail through a machine-list rebuild.+ final DialState dial;+ final AgentPreference agentPreference;++ TerminalPane? get focusedPane {+ final id = focusedPaneId;+ if (id == null) return null;+ for (final pane in panes) {+ if (pane.id == id) return pane;+ }+ return null;+ }++ /// The one tile everything single-terminal still means.+ ///+ /// Kept as a getter rather than deleted because the alternative — teaching+ /// every caller about tiles — would have spread the grid across code that has+ /// no business knowing there is one (a rename arriving, an agent being+ /// deleted, the window closing). The handful of callers that must reach EVERY+ /// tile of a machine, rather than only the focused one, call [panesFor]+ /// instead; those are the transport-wide events, and they are marked.+ TerminalSession? get activeTerminal => focusedPane?.session;++ bool get canAddPane => panes.length < maxPanes;++ Iterable<TerminalPane> panesFor(String machineId) =>+ allPanes.where((pane) => pane.machineId == machineId);++ TerminalPane? paneOfAgent(String machineId, String agentId) {+ for (final pane in panes) {+ if (pane.machineId == machineId && pane.agentId == agentId) return pane;+ }+ return null;+ }++ bool isAgentInPane(String machineId, String agentId) =>+ paneOfAgent(machineId, agentId) != null;++ /// True while the KEYBOARD is in the rail rather than on the grid.+ ///+ /// Folded into [isPaneFocused] on purpose, and it does two jobs at once. The+ /// terminal re-claims the native input connection when `focused` goes false →+ /// true (TerminalPanel.didUpdateWidget), so flipping this is what hands the+ /// keys over and what takes them back. And the focus ring leaves the tile+ /// while the rail has the cursor, which is the honest thing to draw: a ring on+ /// a pane that is not receiving keys is a lie the whole feature would rest on.+ bool railFocused = false;++ /// Which row the rail's cursor is on, indexing [railRows].+ int railCursor = 0;++ bool isPaneFocused(int paneId) => !railFocused && focusedPaneId == paneId;++ /// The rail as a flat list of rows, in the order it is drawn.+ ///+ /// ONE source for the cursor and for the highlight. The rail builds its own+ /// tree from the same pieces, and a second traversal that "should" agree is+ /// exactly how an arrow key ends up selecting a different row than the one+ /// lit up — so the widget reads its highlight from this list too.+ ///+ /// Local machine first, then the backend's order, which is what the rail has+ /// always drawn; a machine that is collapsed contributes its own row and none+ /// of its agents, because a cursor cannot rest on something not on screen.+ List<RailRow> railRows() {+ final rows = <RailRow>[];+ final ordered = <Machine>[+ ...machines.where((m) => stateOf(m.machineId)?.isLocalMachine == true),+ ...machines.where((m) => stateOf(m.machineId)?.isLocalMachine != true),+ ];+ for (final machine in ordered) {+ rows.add(RailRow(machineId: machine.machineId));+ if (!expandedMachines.contains(machine.machineId)) continue;+ for (final agent+ in stateOf(machine.machineId)?.agents ?? const <Agent>[]) {+ rows.add(RailRow(machineId: machine.machineId, agentId: agent.id));+ }+ }+ return rows;+ }++ /// Hand the keyboard to the rail — ⌘h off the left edge of the grid.+ ///+ /// The cursor starts on the agent the window is already looking at, so the+ /// first press of `j` steps off it rather than jumping to the top of a list+ /// of thirty. Same reasoning as the layout palette's cursor.+ void focusRail() {+ final rows = railRows();+ if (rows.isEmpty) return;+ final pane = panes.where((p) => p.id == focusedPaneId).firstOrNull;+ var at = 0;+ if (pane?.agentId != null) {+ final found = rows.indexWhere(+ (row) =>+ row.agentId == pane!.agentId && row.machineId == pane.machineId,+ );+ if (found >= 0) at = found;+ }+ railFocused = true;+ railCursor = at;+ notifyListeners();+ }++ /// Give it back. The focused tile re-claims the keys on the next frame.+ void unfocusRail() {+ if (!railFocused) return;+ railFocused = false;+ notifyListeners();+ }++ /// The row the cursor is on, or null when the rail has changed under it.+ ///+ /// Bounds-checked rather than clamped, and that distinction is the point: an+ /// agent finishing or a machine collapsing can shorten the list between a+ /// keypress and the frame that draws it, and clamping would silently light up+ /// a DIFFERENT row than the one the cursor was on. Null draws nothing, which+ /// is the honest answer for one frame.+ RailRow? railRowAt(int index) {+ final rows = railRows();+ if (index < 0 || index >= rows.length) return null;+ return rows[index];+ }++ void moveRailCursor(int delta) {+ final rows = railRows();+ if (rows.isEmpty) return;+ // Clamped, not wrapped: the rail is a column you can see the ends of, and a+ // cursor that leaps from the last machine back to the first reads as a+ // mis-key. The grid's own focus wraps because it is a loop of tiles.+ railCursor = (railCursor + delta).clamp(0, rows.length - 1);+ notifyListeners();+ }++ /// Enter on the cursor's row.+ ///+ /// A machine row toggles; an agent row opens and gives the keyboard back —+ /// because "go to this agent" is a request to work in it, and leaving the+ /// keys in the sidebar would make every open a two-step.+ Future<void> activateRailRow() async {+ final rows = railRows();+ if (railCursor < 0 || railCursor >= rows.length) return;+ final row = rows[railCursor];+ if (row.agentId == null) {+ toggleExpand(row.machineId);+ return;+ }+ railFocused = false;+ notifyListeners();+ await selectAgent(row.machineId, row.agentId!);+ }++ /// `h` in the rail — out of an agent list, then out of the rail.+ ///+ /// Two steps rather than one, and that is the vim shape: `h` at the top level+ /// leaves, `h` inside something closes it first. Pressed on an agent it jumps+ /// to that agent's machine row and folds it, which is where the eye already+ /// is; pressed on a machine row it hands the keyboard back to the grid.+ void railCollapseOrExit() {+ final rows = railRows();+ if (railCursor < 0 || railCursor >= rows.length) {+ unfocusRail();+ return;+ }+ final row = rows[railCursor];+ if (row.agentId != null) {+ final head = rows.indexWhere(+ (r) => r.machineId == row.machineId && r.agentId == null,+ );+ if (head >= 0) railCursor = head;+ toggleExpand(row.machineId);+ notifyListeners();+ return;+ }+ if (expandedMachines.contains(row.machineId)) {+ toggleExpand(row.machineId);+ return;+ }+ unfocusRail();+ }++ /// Show or hide one tile's composer textbox, and remember the choice.+ void toggleComposer(int paneId) {+ for (final pane in panes) {+ if (pane.id != paneId) continue;+ pane.composerVisible = !pane.composerVisible;+ _persistLayout();+ notifyListeners();+ return;+ }+ }++ void focusPane(int paneId, {bool reveal = false}) {+ if (!panes.any((pane) => pane.id == paneId)) return;+ final moved = focusedPaneId != paneId || railFocused;+ railFocused = false;+ // Remembered only on a REAL move. Re-focusing the tile you are already on+ // happens constantly — see the note below about why it is announced anyway+ // — and recording it would make ⌘; a key that returns you to where you+ // already are, which is the same as a key that does nothing.+ if (moved) _previousPaneId = focusedPaneId;+ focusedPaneId = paneId;+ selectedMachineId = focusedPane?.machineId;+ if (reveal) _paneFocusRequest++;+ if (zoomedPaneId != null) zoomedPaneId = paneId;+ // Announced even when this tile was ALREADY focused.+ //+ // The dial can be turned by hand, and then the two disagree with nobody+ // knowing. Choosing this agent — from the rail or by clicking its tile — is+ // how someone says "no, look at THIS one", so it has to be able to say it.+ //+ // The old guard here made that impossible in exactly the case that needed+ // it. An agent that is NOT open yet gets a fresh stream, and the daemon+ // follows `terminal_open` as a side effect; one that IS open opens nothing,+ // so `app_focus` is the only thing that can move the dial — and this+ // returned before sending it. That is why a single pane always worked+ // (every switch re-attached) and a second pane broke it.+ //+ // Re-sending the same agent is safe: the daemon drops it against the dial's+ // real position (`agentId === this.dialFocus` in cableSession), which is the+ // only side that can judge, because only it knows where the dial is.+ _announceAppFocus();+ if (moved) _persistLayout();+ if (moved || reveal) notifyListeners();+ }++ String? _announcedFocusMachineId;+ String? _deviceFocusRevision;++ @visibleForTesting+ Future<bool> Function(String machineId, String? agentId)?+ focusFrameSenderForTest;++ /// Publish the selected pane to the existing local CLI connection. The CLI+ /// shares this focus with paired devices and the dial; terminal attachments+ /// and operating-system window activation do not define the selected agent.+ void _announceAppFocus() {+ final pane = focusedPane;+ final machineId = pane?.agentId == null ? null : pane?.machineId;+ final previousMachineId = _announcedFocusMachineId;+ _announcedFocusMachineId = machineId;+ if (previousMachineId != null && previousMachineId != machineId) {+ _sendAppFocus(previousMachineId, null);+ }+ if (machineId != null) _sendAppFocus(machineId, pane!.agentId);+ }++ void _sendAppFocus(String machineId, String? agentId) {+ // Never create a socket just to move focus, and never queue stale focus+ // across a reconnect. The connected callback reasserts the current pane.+ final send = focusFrameSenderForTest;+ final pending = send != null+ ? send(machineId, agentId)+ : _pool?[machineId]?.sendTerminalFrame('app_focus', {+ 'agentId': agentId,+ if (_deviceFocusRevision != null)+ 'focusRevision': _deviceFocusRevision,+ });+ if (pending != null) unawaited(pending.catchError((_) => false));+ }++ /// Tell the daemon which agents have a tile on the grid, so the dial can stay+ /// quiet about a turn that finished in front of the person.+ ///+ /// An OPEN tile counts as seen. Not a focused one: with four tiles all four+ /// are on screen, and the window has no honest way to say which the eye is+ /// on. Nor is the window's own focus consulted — a decision, not an+ /// oversight: it means a turn that lands while the app is behind a browser+ /// stays silent, and the alternative is a dial that beeps about tiles you are+ /// looking straight at.+ ///+ /// Sent to EVERY connected daemon, with the full list across all machines.+ /// The dial belongs to whichever daemon owns the cable, and only a complete+ /// roster lets that one judge; the others store a list they never use, which+ /// costs nothing and saves the window from having to know which is which.+ void _announceOpenPanesToDial() {+ final pool = _pool;+ if (pool == null) return;+ final agentIds = <String>[for (final pane in panes) ?pane.agentId];+ // The swarms travel with the tiles: the dial names the one on screen above the agent and offers+ // the others, and a pick there comes back as `dial_swarm`. Names and member ids only — the layout+ // inside a swarm is this window's business.+ final swarmRows = [+ for (final swarm in swarms)+ {+ 'id': swarm.id,+ 'name': swarm.name,+ 'agentIds': [for (final pane in swarm.panes) ?pane.agentId],+ },+ ];+ for (final machineId in machineStates.keys) {+ final connection = pool[machineId];+ if (connection == null) continue;+ unawaited(+ connection+ .sendTerminalFrame('app_panes', {'agentIds': agentIds})+ .catchError((_) => false),+ );+ unawaited(+ connection+ .sendTerminalFrame('app_swarms', {+ 'active': activeSwarmId,+ 'swarms': swarmRows,+ })+ .catchError((_) => false),+ );+ }+ }++ /// Machines whose link prompt the user has waved away.+ ///+ /// Dismissing cannot mean "deselect": [activeMachineState] falls back to the+ /// first expanded machine, so clearing the selection would often re-arrive at+ /// the very machine that was just closed. And it must not mean "linked" —+ /// nothing changed about the machine, which still cannot be read and still+ /// says so in the rail. It means only that the pane stops insisting.+ ///+ /// Held in memory, not on disk, and cleared the moment the machine is chosen+ /// again: someone who clicks that row is asking to see it.+ final Set<String> _dismissedLinkPrompts = {};++ bool isLinkPromptDismissed(String machineId) =>+ _dismissedLinkPrompts.contains(machineId);++ void dismissLinkPrompt(String machineId) {+ if (_dismissedLinkPrompts.add(machineId)) notifyListeners();+ }++ /// The person asked to see the prompt again — a deliberate open, not the+ /// reactive gate. Without this, every way in that does not go through+ /// [showMachinePane] (the welcome's Machines row) opened a dialog that its+ /// own "still needed?" check closed on the first frame: one popup, then+ /// nothing, for as long as the app ran.+ void revisitLinkPrompt(String machineId) {+ if (_dismissedLinkPrompts.remove(machineId)) notifyListeners();+ }++ // ── ⌘B: a typed task, and which agent it belongs to ────────────────────────────────────────────++ /// The machine this window is running ON — where the daemon that ANSWERS ⌘B lives.+ ///+ /// It is not the scope of the search: the daemon weighs agents on every machine and answers with the+ /// one each pick belongs to. This is only the socket the question travels on, because the router, the+ /// registry and the recap mirror it reads are all on this computer.+ MachineState? get localMachineState {+ for (final state in machineStates.values) {+ if (state.isLocalMachine) {+ return state; // the flag is the STATE's, not the machine row's+ }+ }+ return null;+ }++ /// Ask the daemon which agent a typed task belongs to. Sends nothing.+ ///+ /// Rides the app's own rpc convention (`ws_conn.request`), so the pending map, the timeout and the+ /// logging are the ones every other request already uses. Returns null when there is nobody to ask —+ /// no local machine, or its socket is not up — which the palette says out loud rather than spinning.+ /// 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 ⌘B uses: the question+ /// travelled the other way this time, 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),+ );+ }++ Future<RouteAnswer?> routeTask(String text) async {+ final machineId = localMachineState?.machine.machineId;+ final connection = machineId == null ? null : _pool?[machineId];+ if (connection == null) return null;+ try {+ final reply = await connection.request(+ 'route_task',+ payload: {'text': text},+ // Over the daemon's own classification budget — which is 20s on this path — plus room for+ // gathering the candidates and the round trip. A request that gives up BEFORE the router does+ // leaves the person with nothing WHILE the answer is on its way, which is the one outcome worse+ // than waiting; and at exactly 20s each it would be a coin toss which of the two fired first.+ timeout: const Duration(seconds: 35),+ );+ return RouteAnswer.fromJson(reply);+ } catch (_) {+ // A timeout or a transport failure is not an error the person can act on — the palette shows the+ // candidates it has and lets them choose, which is the same thing it does for a weak answer.+ return null;+ }+ }++ /// Commit: deliver the task, then bring the agent onto the grid the way a rail click does.+ ///+ /// The daemon delivers it through the SAME door as the web's messages and the dial's — queueing,+ /// retries and the per-engine slash-command adaptation are not re-implemented for the caller that+ /// types instead of speaking.+ /// Commit: deliver the task, then bring the agent onto the grid the way a rail click does.+ ///+ /// Returns null when it landed, or a sentence saying why it did not — which the palette shows instead+ /// of closing. It ASKS rather than tells for a reason measured on the desk: the remote leg carries no+ /// ack of its own, so a machine that has gone deaf takes the turn and nothing comes back. A confident+ /// route closes this window silently, so without an answer that is a task that vanished with no mark+ /// anywhere — the worst outcome this flow can produce.+ ///+ /// [agentMachineId] is the agent's OWN machine, which is not this one when the router reached across.+ Future<String?> sendRoutedTask(+ String agentId,+ String agentMachineId,+ String text,+ ) async {+ final localId = localMachineState?.machine.machineId;+ if (localId == null) return 'No local machine is connected.';+ final connection = _pool?[localId];+ if (connection == null) return 'No local machine is connected.';+ // The task goes to the LOCAL daemon whichever machine the agent is on: it owns the dispatch that+ // knows the difference (its own registry, or the fleet link to the other computer). Sending it down+ // the remote machine's own socket would be a second delivery path for the same thing.+ try {+ final reply = await connection.request(+ 'route_send',+ payload: {'agentId': agentId, 'text': text},+ timeout: const Duration(seconds: 15),+ );+ if (reply['ok'] != true) {+ final machine = (reply['machine'] as String?) ?? '';+ final reason =+ (reply['reason'] as String?) ?? 'it could not be delivered';+ return machine.isEmpty+ ? 'Not sent — $reason.'+ : 'Not sent to $machine — $reason.';+ }+ } catch (_) {+ return 'The daemon did not answer. Nothing was sent.';+ }+ // …the PANE opens on the agent's machine. Falling back to this computer would open a tile for an+ // agent it does not have and leave the person looking at an empty terminal.+ final target = agentMachineId.isNotEmpty ? agentMachineId : localId;+ await selectAgent(target, agentId);+ return null;+ }++ MachineState? get activeMachineState {+ final terminal = activeTerminal;+ if (terminal != null) return machineStates[terminal.machineId];+ final selected = selectedMachineId;+ if (selected != null) return machineStates[selected];+ return expandedMachines.isEmpty+ ? null+ : machineStates[expandedMachines.first];+ }++ bool? _nodeOnlineFromStatus(String? status) {+ switch (status?.trim().toLowerCase()) {+ case 'running':+ case 'online':+ case 'connected':+ case 'ready':+ return true;+ case 'offline':+ case 'stopped':+ case 'disconnected':+ case 'unreachable':+ case 'error':+ case 'failed':+ return false;+ default:+ return null;+ }+ }++ 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 {+ final localFixture = localManualFixture;+ if (localFixture != null) {+ _bootstrapLocalManual(localFixture);+ return;+ }+ try {+ if (_store != null) {+ try {+ config = await _store.load().timeout(const Duration(seconds: 5));+ } catch (error) {+ // Connection settings are optional local preferences. An unavailable+ // state file must not invalidate an otherwise recoverable SSO flow;+ // use the store's safe cached/default production config.+ debugPrint(+ 'bootstrap: config store unavailable, using defaults: $error',+ );+ config = _store.config;+ }+ // Forced, not read from persisted config: staging is a dev-only+ // escape hatch with no UI to reach it anymore (see login_screen.dart+ // history) — a stale `stag` value saved before that removal must+ // never silently resurrect it.+ _autonomousEnv = 'prod';+ api = _newApiClient();+ _skippedDesktopUpdateVersion = _store.skippedDesktopUpdateVersion;+ }+ // A viewer installs nothing and is updated by its store: provisioning and the updater both+ // serve a computer that runs the harness CLI. The updater is not merely useless there — it+ // throws on an architecture it has no channel for (`ios_arm64`), from inside bootstrap.+ if (viewer == null) {+ _startUpdateChecking();+ final environmentReady = await _prepareEnvironment();+ if (!environmentReady) return;+ }+ await _continueAfterEnvironmentReady();+ } catch (error, stack) {+ debugPrint('bootstrap: fallback to login after error: $error\n$stack');+ currentUser = null;+ status = AppStatus.unauthenticated;+ notifyListeners();+ } finally {+ // A `finally` rather than a call per exit path: bootstrap resolves four+ // ways (environment not ready, signed out, signed in, thrown) and the+ // launch happened in all four. `retryEnvironmentSetup` re-enters here,+ // which is why the event itself is once-per-launch.+ _trackAppOpened();+ }+ }++ bool _appOpenedTracked = false;++ /// `app_opened`, once, with the answer bootstrap actually reached. Sent from+ /// here rather than from the first frame because `signed_in` is not known+ /// until the CLI has been asked, and a first-frame event would report every+ /// launch as signed out.+ void _trackAppOpened() {+ if (_appOpenedTracked) return;+ _appOpenedTracked = true;+ final signedIn = status == AppStatus.authenticated;+ analytics.appOpened(signedIn: signedIn);+ // A returning user is signed in before the app is even on screen, so their+ // wait starts here rather than at a sign-in that never happens.+ if (signedIn) _armFirstMessage('launch');+ }++ /// Runs before we invoke a single Harness subcommand. A fresh mac used to+ /// fail here with a generic Sign in error because `harness` and its Node+ /// runtime were absent; provisioning now makes that a visible, recoverable+ /// first-run phase instead.+ Future<bool> _prepareEnvironment() async {+ // A viewer has nothing to provision. The provisioner looks for a shell, the+ // POSIX tools, tmux and a managed Node runtime under `~/.harness` — all of+ // which exist to host the local `harness` CLI, which a viewer build does+ // not have and does not want. Running it on a phone reported every step+ // missing and parked the app on a setup screen whose two actions, Retry+ // and Switch to Manual, could not succeed either. Treated as ready so+ // bootstrap goes on to ask about sign-in, which a viewer can answer.+ if (viewer != null) return true;+ if (_environmentSetupInFlight) return false;+ _environmentSetupInFlight = true;+ status = AppStatus.checkingEnvironment;+ environmentReadiness = EnvironmentReadiness.initial();+ notifyListeners();+ try {+ // Always read-only here. Installation starts only after explicit confirmation in the wizard.+ final result = await _runProvisioner(install: false);+ if (!result.isReady) {+ status = AppStatus.preparingEnvironment;+ notifyListeners();+ return false;+ }+ _cancelEnvironmentRecheckTimer();+ return true;+ } finally {+ _environmentSetupInFlight = false;+ }+ }++ /// Shared with [_prepareEnvironment]: runs the provisioner, updates+ /// [environmentReadiness] as it streams progress, and reports the outcome.+ Future<EnvironmentReadiness> _runProvisioner({+ EnvironmentReadiness? resumeFrom,+ bool install = false,+ EnvironmentSetupMode? mode,+ bool quiet = false,+ }) async {+ final provisioner = environmentProvisioner ?? EnvironmentProvisioner();+ final result = await provisioner.ensureReady(+ onProgress: (value) {+ if (quiet &&+ value.phase != EnvironmentSetupPhase.ready &&+ value.phase != EnvironmentSetupPhase.failed) {+ // A 5-second Terminal poll must not repaint the wizard through+ // preflight -> review -> waiting. Keep the stable handoff surface+ // and only stream its diagnostics until there is a real terminal+ // outcome or installation can continue.+ environmentReadiness = environmentReadiness.copyWith(+ output: value.output,+ terminalLogPath: value.terminalLogPath,+ terminalResultPath: value.terminalResultPath,+ terminalSetup: value.terminalSetup,+ systemReady: value.systemReady,+ );+ } else {+ environmentReadiness = value;+ }+ // A successful probe belongs to the quiet pre-flight surface, never+ // the installation wizard. This also prevents the setup screen from+ // flashing its own ready phase for one frame after an install/recheck.+ if (value.isReady) status = AppStatus.checkingEnvironment;+ notifyListeners();+ },+ resumeFrom: resumeFrom,+ install: install,+ mode: mode,+ );+ environmentReadiness = result;+ if (!quiet ||+ result.isReady ||+ result.phase == EnvironmentSetupPhase.failed) {+ analytics.environmentPrepared(ready: result.isReady);+ }+ return result;+ }++ /// What `bootstrap()` does right after the environment is confirmed ready — pulled out so+ /// [recheckEnvironmentStep] can reach the same destination without repeating `bootstrap()`'s config+ /// load and update-check startup, which already ran on the launch that got stuck here.+ Future<void> _continueAfterEnvironmentReady() async {+ final revision = _authRevision;+ if (!_authWorkCurrent(revision)) return;+ _cancelEnvironmentRecheckTimer();+ // A viewer skipped the preflight (see [_prepareEnvironment]), so there is no+ // preflight screen to hold while the sign-in is checked — it stays on the+ // boot spinner instead.+ status = viewer == null+ ? AppStatus.checkingEnvironment+ : AppStatus.bootstrapping;+ notifyListeners();+ // Auth now lives entirely with the local `harness` CLI — it owns the SSO session on disk and+ // refreshes it itself. This app never reads, stores, or refreshes a token of its own; it just+ // asks the CLI whether this computer is currently signed in.+ try {+ final authStatus = await cliLogin.checkStatus();+ if (!_authWorkCurrent(revision)) return;+ if (!authStatus.loggedIn) {+ currentUser = null;+ status = AppStatus.unauthenticated;+ notifyListeners();+ return;+ }+ status = AppStatus.bootstrapping;+ notifyListeners();+ await _finishBootstrapSignedIn();+ } catch (error, stack) {+ if (!_authWorkCurrent(revision)) return;+ debugPrint(+ 'continueAfterEnvironmentReady: fallback to login after error: '+ '$error\n$stack',+ );+ currentUser = null;+ status = AppStatus.unauthenticated;+ notifyListeners();+ }+ }++ void showEnvironmentReview() {+ environmentReadiness = environmentReadiness.copyWith(+ phase: EnvironmentSetupPhase.review,+ );+ notifyListeners();+ }++ void showEnvironmentMethodChoice() {+ environmentReadiness = environmentReadiness.copyWith(+ phase: EnvironmentSetupPhase.chooseMethod,+ );+ notifyListeners();+ }++ void selectEnvironmentSetupMode(EnvironmentSetupMode mode) {+ environmentReadiness = environmentReadiness.copyWith(mode: mode);+ notifyListeners();+ }++ Future<void> startEnvironmentSetup() async {+ if (_environmentSetupInFlight) return;+ _cancelEnvironmentRecheckTimer();+ final mode = environmentReadiness.mode ?? EnvironmentSetupMode.automatic;+ if (mode == EnvironmentSetupMode.manual) {+ notifyListeners();+ return;+ }+ _environmentSetupInFlight = true;+ notifyListeners();+ try {+ final result = await _runProvisioner(+ resumeFrom: environmentReadiness,+ install: true,+ mode: mode,+ );+ if (!result.isReady) {+ _scheduleEnvironmentRecheck();+ return;+ }+ await _continueAfterEnvironmentReady();+ } finally {+ _environmentSetupInFlight = false;+ notifyListeners();+ }+ }++ Future<void> continueAfterEnvironmentSetup() async {+ if (!environmentReadiness.isReady) return;+ await _continueAfterEnvironmentReady();+ }++ /// A manual repair always returns to a read-only probe.+ Future<void> retryEnvironmentSetup() async {+ if (_environmentSetupInFlight) return;+ _environmentSetupInFlight = true;+ notifyListeners();+ try {+ final result = await _runProvisioner(+ install: false,+ mode: environmentReadiness.mode,+ );+ if (result.isReady) await _continueAfterEnvironmentReady();+ } finally {+ _environmentSetupInFlight = false;+ notifyListeners();+ }+ }++ /// Rechecks a single stuck step (`failed`/`needsTerminal`) without re-running steps already+ /// `ready` — the user fixed it by hand (see `environment_step_guidance.dart`'s command) and this+ /// confirms it, then falls through to whatever step comes next, exactly like a fresh `bootstrap()`+ /// would have. [step] identifies which row's Recheck button was pressed; the provisioner itself+ /// decides what to (re-)attempt from the current [environmentReadiness], so an already-resolved+ /// step is never disturbed regardless of which row triggered this.+ Future<void> recheckEnvironmentStep(EnvironmentStep step) async {+ if (_environmentSetupInFlight) return;+ _cancelEnvironmentRecheckTimer();+ _environmentSetupInFlight = true;+ notifyListeners();+ try {+ final visibleBeforeProbe = environmentReadiness;+ final mode = environmentReadiness.mode;+ var result = await _runProvisioner(+ resumeFrom: environmentReadiness,+ install: false,+ mode: mode,+ quiet:+ mode == EnvironmentSetupMode.automatic &&+ environmentReadiness.phase ==+ EnvironmentSetupPhase.waitingForTerminal,+ );+ if (!result.isReady &&+ mode == EnvironmentSetupMode.automatic &&+ result.phase != EnvironmentSetupPhase.waitingForTerminal &&+ result.systemReady &&+ result.steps[EnvironmentStep.tmux] == EnvironmentStepStatus.ready &&+ (result.steps[EnvironmentStep.clipboard] ==+ EnvironmentStepStatus.ready ||+ result.steps[EnvironmentStep.clipboard] ==+ EnvironmentStepStatus.notApplicable)) {+ result = await _runProvisioner(+ resumeFrom: result,+ install: true,+ mode: mode,+ );+ }+ if (!result.isReady) {+ if (mode == EnvironmentSetupMode.automatic &&+ result.phase != EnvironmentSetupPhase.failed) {+ environmentReadiness = visibleBeforeProbe.copyWith(+ phase: EnvironmentSetupPhase.waitingForTerminal,+ output: result.output,+ terminalLogPath: result.terminalLogPath,+ terminalResultPath: result.terminalResultPath,+ terminalSetup: result.terminalSetup,+ systemReady: result.systemReady,+ );+ }+ _scheduleEnvironmentRecheck();+ return;+ }+ await _continueAfterEnvironmentReady();+ } catch (error, stack) {+ debugPrint(+ 'recheckEnvironmentStep: fallback to login after error: $error\n$stack',+ );+ currentUser = null;+ status = AppStatus.unauthenticated;+ } finally {+ _environmentSetupInFlight = false;+ notifyListeners();+ _trackAppOpened();+ }+ }++ /// Polls the currently-stuck required step every 5s (see `_environmentRecheckTimer`'s doc) so+ /// fixing it in another window and forgetting to click Recheck still moves the app forward.+ /// A no-op unless automatic setup is waiting on the real Terminal window.+ void _scheduleEnvironmentRecheck() {+ _environmentRecheckTimer?.cancel();+ if (environmentReadiness.phase !=+ EnvironmentSetupPhase.waitingForTerminal ||+ environmentReadiness.mode != EnvironmentSetupMode.automatic) {+ return;+ }+ EnvironmentStep? stuck;+ for (final entry in environmentReadiness.steps.entries) {+ if (!entry.key.isRequired) continue;+ if (entry.value == EnvironmentStepStatus.needsTerminal ||+ entry.value == EnvironmentStepStatus.failed) {+ stuck = entry.key;+ break;+ }+ }+ if (stuck == null && environmentReadiness.terminalSetup == null) return;+ // Base system setup has no EnvironmentStep row of its own. The callback+ // argument is only a UI trigger; the provisioner rechecks the complete+ // environment and uses terminalSetup to attribute any failure.+ final step = stuck ?? EnvironmentStep.tmux;+ _environmentRecheckTimer = Timer(const Duration(seconds: 5), () {+ unawaited(recheckEnvironmentStep(step));+ });+ }++ void _cancelEnvironmentRecheckTimer() {+ _environmentRecheckTimer?.cancel();+ _environmentRecheckTimer = null;+ }++ void _bootstrapLocalManual(LocalManualFixture fixture) {+ _autonomousEnv = 'prod';+ config = AppConfig(apiBaseUrl: fixture.apiBaseUrl);+ api = _newApiClient();+ currentUser = const CurrentUserProfile.local();+ final machine = Machine(+ machineId: fixture.machineId,+ apiKey: fixture.apiKey,+ authMode: MachineAuthMode.remote,+ name: fixture.machineName,+ status: 'online',+ );+ machines = [machine];+ machineStates+ ..clear()+ ..[machine.machineId] = MachineState(machine);+ machineStates[machine.machineId]!.nodeOnline = true;+ expandedMachines.clear();+ selectedMachineId = null;+ status = AppStatus.authenticated;+ _lastError = null;+ _ensurePool();+ _autoConnectAndLoadMachines();+ notifyListeners();+ }++ /// Both `bootstrap()` (already signed in) and `login()` (just finished signing in) land here once+ /// the CLI confirms a session exists — ensure the local daemon is actually up first (it does not+ /// start on its own, and every call below is a local-CLI-proxied request that needs it), then fetch+ /// the profile and machine list independently over it.+ Future<void> _finishBootstrapSignedIn() async {+ final revision = _authRevision;+ if (!_authWorkCurrent(revision)) return;+ // Stays on the pre-navigation `bootstrapping` screen (main.dart) until the daemon is+ // confirmed reachable — flipping to `authenticated` any earlier is what let the home UI+ // race `harness start`'s own backend handshake and surface a bogus 30s "Could not load+ // machines" timeout. A daemon that never comes up still gets a home screen below, with+ // the failure shown there as before, since that's where the retry affordance lives.+ _bootStatusMessage = 'Starting local service…';+ notifyListeners();+ // Before the machines, deliberately: the tiles are intent, they render as+ // "waiting for that machine" on their own, and each attaches as its machine+ // answers. Waiting for the machine list first would leave the window empty+ // for as long as the slowest one takes, and would hand the first-run+ // auto-pick a window in which the grid still looks empty.+ await _restorePaneLayout();+ if (!_authWorkCurrent(revision)) return;+ await dial.restore();+ if (!_authWorkCurrent(revision)) return;+ _ensurePool();+ try {+ await ensureCliDaemonReady();+ } catch (error) {+ if (!_authWorkCurrent(revision)) return;+ _bootStatusMessage = null;+ status = AppStatus.authenticated;+ _lastError = '$error';+ _lastErrorRetryable = true;+ notifyListeners();+ return;+ }+ if (!_authWorkCurrent(revision)) return;+ _bootStatusMessage = null;+ // `ensureCliDaemonReady` may have signed the app out instead of succeeding (daemon absent AND+ // the saved session gone) — that already routed to the login screen, so don't clobber it.+ if (status == AppStatus.unauthenticated) return;+ status = AppStatus.authenticated;+ notifyListeners();+ // The CLI has confirmed sign-in and daemon readiness. Display-name/avatar+ // metadata is independent of machine discovery and must not delay work.+ unawaited(_loadProfile());+ try {+ await refreshMachines();+ } catch (error) {+ if (!_authWorkCurrent(revision)) return;+ _lastError = 'Could not load machines: ${describeApiError(error)}';+ _lastErrorRetryable = true;+ }+ if (_authWorkCurrent(revision)) notifyListeners();+ }++ /// The local daemon (`harness start`) must be up before any local REST/WS call can work — unlike+ /// `harness login`, it does not start on its own. Sets [_cliEndpoint], the dial target every+ /// machine's WsConn now uses. Public (like [refreshMachines]) so a test subclass can stub it+ /// without shelling out to a real `harness` binary.+ /// Who is signed in, from the daemon. Shared by the boot path and by the+ /// retry path, because a boot that found the daemon still connecting now+ /// finishes THROUGH the retry path — and a session that never learns its+ /// own account has an empty footer and unattributed analytics.+ Future<void> _loadProfile() {+ final pending = _profileInFlight;+ if (pending != null) return pending;+ final revision = _authRevision;+ late final Future<void> load;+ load = _readProfile(revision).whenComplete(() {+ if (identical(_profileInFlight, load)) _profileInFlight = null;+ });+ _profileInFlight = load;+ return load;+ }++ Future<void> _readProfile(int revision) async {+ try {+ final me = await api.me();+ if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {+ return;+ }+ if (me != null) {+ final profile = CurrentUserProfile.fromMe(me);+ currentUser = profile;+ // Every event from here on is filed under the account, including ones+ // queued while this call was still in flight — the queue reads the+ // account per event, not per launch.+ analyticsAccount.set(id: profile.id, email: profile.email);+ notifyListeners();+ }+ } catch (error) {+ if (_authWorkCurrent(revision)) {+ debugPrint('bootstrap: profile unavailable: $error');+ }+ }+ }++ Future<void> ensureCliDaemonReady() async {+ // A viewer has no daemon to start: it reaches every machine through the relay.+ if (viewer != null) return;+ final revision = _authRevision;+ final discovery = _discovery;+ final probe = await discovery.ensureRunning();+ if (!_authWorkCurrent(revision)) return;+ switch (probe.state) {+ case LocalCliProbeState.ready:+ _cliEndpoint = probe.endpoint;+ _daemonGateFailed = false;+ case LocalCliProbeState.notReady:+ _daemonGateFailed = true;+ // Running, not ready — most often a daemon fresh from a self-update still shaking hands+ // with the backend. Not "did not start": that sentence sends people to run `harness start`+ // against a daemon that is up, and the CLI's own lock will just tell them so. It keeps+ // retrying by itself; the supervisor below picks the app up the moment it gets there.+ _startDaemonSupervision(discovery);+ throw StateError(+ 'Harness is running${probe.version == null ? '' : ' (v${probe.version})'} but has not '+ 'connected to the backend yet — ${probe.reason}. It usually finishes on its own; '+ 'retry in a moment.',+ );+ case LocalCliProbeState.down:+ _daemonGateFailed = true;+ // Before blaming the environment, check whether the daemon is missing because it signed itself+ // out. "Try running `harness start` yourself" is advice that cannot work in that case — the+ // session file is gone, so every start exits again — and it is the advice this branch used to+ // give unconditionally.+ final authStatus = await cliLogin.checkStatus();+ if (!_authWorkCurrent(revision)) return;+ if (!authStatus.loggedIn) {+ _signedOutAtRuntime(_signedOutMessage);+ return;+ }+ throw StateError(+ 'The local Harness daemon did not start. Try running `harness start` yourself, then reopen the app.',+ );+ }+ _startDaemonSupervision(discovery);+ }++ /// Supervision starts once the daemon is at least ANSWERING — ready or still connecting. It used to+ /// wait for ready, out of fear of a concurrent `harness start` from both places; the supervisor+ /// no longer spawns while anything answers on the port, so that race is gone, and starting it on+ /// a not-ready daemon is what lets a boot that landed mid-update recover without a click.+ void _startDaemonSupervision(LocalCliDiscovery discovery) {+ _daemonSupervisionTimer ??= discovery.startSupervising(+ stillSignedIn: () async => (await cliLogin.checkStatus()).loggedIn,+ onSignedOut: () => _signedOutAtRuntime(_signedOutMessage),+ onSnapshot: _updateLocalProjectSnapshot,+ onReady: (endpoint) {+ // Back (or here for the first time). If the app is sitting on the error strip from a boot+ // or reload that found the daemon not ready, this is the moment it was waiting for.+ //+ // Gated on OUR failure, not on `_lastError`: that strip is shared with errors this cannot+ // fix (an agent that failed to launch, say), and the supervisor's first tick after every+ // boot would otherwise clear one of those five seconds after it appeared.+ if (_cliEndpoint == null || _daemonGateFailed) {+ _cliEndpoint ??= endpoint;+ unawaited(retryMachines());+ }+ },+ );+ }++ void _updateLocalProjectSnapshot(LocalCliEndpoint endpoint) {+ if (_disposed) return;+ var changed = false;+ for (final machine in machineStates.values) {+ final previous = machine.localEndpoint;+ if (previous == null || previous.computerId != endpoint.computerId) {+ continue;+ }+ if (!mapEquals(previous.agentProjects, endpoint.agentProjects)) {+ machine.localEndpoint = endpoint;+ changed = true;+ }+ if (!kUnderTest) {+ for (final project in endpoint.agentProjects.values) {+ unawaited(_localGitProjects.read(project.cwd));+ }+ }+ }+ _applyLocalGitProjects();+ if (changed) notifyListeners();+ }++ void _applyLocalGitProjects() {+ if (_disposed) return;+ var changed = false;+ for (final machine in machineStates.values) {+ final projects = <String, AgentProject>{+ for (final entry+ in (machine.localEndpoint?.agentProjects ??+ const <String, AgentProject>{})+ .entries)+ entry.key: ?_localGitProjects.cached(entry.value.cwd),+ };+ if (mapEquals(machine.localProjects, projects)) continue;+ machine.localProjects = Map.unmodifiable(projects);+ changed = true;+ }+ if (changed) notifyListeners();+ }++ /// Deliberately says nothing about WHY. The daemon clears its session identically whether the+ /// machine was deleted from another machine or the SSO token simply expired, and guessing between+ /// them in the copy would sometimes be wrong. Signing in again is the answer to both.+ static const _signedOutMessage =+ 'You were signed out on this computer. Sign in again to reconnect.';++ /// The session went away while the app was already running — send the user to [LoginScreen] with a+ /// reason, and stop the background work that can only fail from here.+ ///+ /// Cold start already handles this: [bootstrap] asks the CLI whether it is signed in. The hole this+ /// fills is the app that was ALREADY authenticated when the session disappeared underneath it,+ /// where nothing re-checked and the daemon supervisor simply respawned `harness start` forever.+ void _signedOutAtRuntime(String message) {+ if (status == AppStatus.unauthenticated) {+ return; // idempotent: several sources can race here+ }+ _invalidateAuthWork();+ currentUser = null;+ signingIn = false;+ pendingAuthorizeUrl = null;+ _awaitingFirstMessage = null;+ analyticsAccount.clear();+ _daemonSupervisionTimer?.cancel();+ _daemonSupervisionTimer = null;+ _cliEndpoint = null;+ unawaited(_pool?.closeAll());+ _pool = null;+ _lastError = message;+ _lastErrorRetryable = true;+ status = AppStatus.unauthenticated;+ notifyListeners();+ }++ void _startUpdateChecking() {+ _updateCheckTimer ??= (desktopUpdater ?? DesktopUpdater()).startChecking(+ onUpdateAvailable: _handleBackgroundUpdate,+ );+ }++ void _handleBackgroundUpdate(UpdateInfo info) {+ if (_disposed) return;+ if (_skippedDesktopUpdateVersion == info.version) return;+ if (availableUpdate?.version == info.version) return;+ availableUpdate = info;+ updateError = null;+ notifyListeners();+ }++ /// A manual check deliberately returns a skipped version too, so the user+ /// can choose to install it from the account menu after changing their mind.+ Future<ManualUpdateCheck> checkForUpdates() async {+ if (isCheckingForUpdate) {+ return ManualUpdateCheck(update: availableUpdate);+ }+ isCheckingForUpdate = true;+ updateError = null;+ notifyListeners();+ try {+ final info = await (desktopUpdater ?? DesktopUpdater()).checkOnce();+ if (info == null) return const ManualUpdateCheck();+ final skipped = _skippedDesktopUpdateVersion == info.version;+ availableUpdate = info;+ return ManualUpdateCheck(update: info, isSkipped: skipped);+ } finally {+ isCheckingForUpdate = false;+ if (!_disposed) notifyListeners();+ }+ }++ /// Clears a failed install without burying the offer.+ ///+ /// Skipping is permanent — it records the version so the background check+ /// stops raising it. A failure is not a decision about the version, so the+ /// way out of one has to leave the update on the table.+ void dismissUpdateError() {+ if (updateError == null) return;+ updateError = null;+ notifyListeners();+ }++ Future<void> skipAvailableUpdate() async {+ final info = availableUpdate;+ if (info == null) return;+ _skippedDesktopUpdateVersion = info.version;+ await _store?.saveSkippedDesktopUpdateVersion(info.version);+ availableUpdate = null;+ updateError = null;+ notifyListeners();+ }++ /// Downloads, verifies, and installs only after an explicit user action.+ /// A failed operation leaves the running app untouched and retryable.+ Future<bool> installAvailableUpdate() async {+ final info = availableUpdate;+ if (info == null || isInstallingUpdate) return false;+ isInstallingUpdate = true;+ updateError = null;+ notifyListeners();+ try {+ final updater = desktopUpdater ?? DesktopUpdater();+ final staged = await updater.downloadAndStage(info);+ if (staged == null) {+ updateError = 'Could not download and verify Harness ${info.version}.';+ return false;+ }+ final applied = await updater.applyStaged(staged, selfPid: pid);+ if (!applied) {+ updateError =+ 'This copy of Harness cannot install updates automatically.';+ return false;+ }+ exit(0);+ } catch (error) {+ updateError = 'Could not install Harness ${info.version}: $error';+ return false;+ } finally {+ isInstallingUpdate = false;+ if (!_disposed) notifyListeners();+ }+ }++ Future<void> login() async {+ if (_disposed || signingIn) return;+ final revision = _invalidateAuthWork();+ _closedHistory.clear();+ _lastError = null;+ status = AppStatus.bootstrapping;+ signingIn = true;+ pendingAuthorizeUrl = null;+ notifyListeners();+ try {+ await cliLogin.login(+ onAuthorizeUrl: (url) {+ if (!_authWorkCurrent(revision)) return;+ if (pendingAuthorizeUrl == url) return;+ _resetLoginBrowser();+ pendingAuthorizeUrl = url;+ notifyListeners();+ // Through [openLoginBrowser] rather than straight to the launcher, so+ // the first handoff is the same one the login screen's retry button+ // takes and reports its outcome the same way. WHICH browser it opens+ // is decided in `viewer/sign_in_browser.dart`.+ unawaited(openLoginBrowser());+ },+ );+ if (!_authWorkCurrent(revision)) return;+ _loginAuthorized = true;+ pendingAuthorizeUrl = null;+ _resetLoginBrowser();+ notifyListeners();+ await _finishBootstrapSignedIn();+ if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {+ return;+ }+ analytics.signedIn();+ // Restarts the clock even if `_trackAppOpened` already started one: this+ // person met the login screen, so their wait begins where the launch's+ // did not.+ _armFirstMessage('sign_in');+ } catch (error) {+ if (!_authWorkCurrent(revision)) return;+ status = AppStatus.unauthenticated;+ _lastError = error.toString();+ _lastErrorRetryable = true;+ // A short code, never `error.toString()` — a CLI failure carries paths+ // and host names, and this stream is not the place for them. Only the+ // two the TYPE can tell apart: a cancelled sign-in and a refused one both+ // arrive as a `StateError` differing in message text, and matching on+ // English sentences is how a stream starts lying after a copy edit.+ analytics.signInFailed(+ error is CliNotAvailableException ? 'cli_missing' : 'failed',+ );+ } finally {+ // Takes the in-app browser view down once the redirect has landed; a no-op+ // where the page opened in a browser of its own.+ unawaited(closeSignInPage());+ // Cleared last, and only here: everything above may still be running when the URL goes, and+ // dropping the flag any earlier is what put a bare spinner over the user's own screen.+ if (_authWorkCurrent(revision)) {+ _resetLoginBrowser();+ _loginAuthorized = false;+ pendingAuthorizeUrl = null;+ signingIn = false;+ }+ }+ if (_authWorkCurrent(revision)) notifyListeners();+ }++ void _resetLoginBrowser() {+ ++_loginBrowserRevision;+ openingLoginBrowser = false;+ loginBrowserError = null;+ }++ /// Reopens the current authorization URL without creating another login.+ Future<void> openLoginBrowser() async {+ final url = pendingAuthorizeUrl;+ if (_disposed || !signingIn || url == null || openingLoginBrowser) return;+ final authRevision = _authRevision;+ final browserRevision = ++_loginBrowserRevision;+ openingLoginBrowser = true;+ loginBrowserError = null;+ notifyListeners();+ var opened = false;+ try {+ final uri = Uri.tryParse(url);+ if (uri != null &&+ uri.hasAuthority &&+ (uri.scheme == 'https' || uri.scheme == 'http')) {+ // Not `launchUrl(..., externalApplication)` directly: on a desktop+ // [openSignInPage] IS that call, and on a phone it must not be. Handing+ // a phone to Safari suspends this app, and with it the loopback listener+ // the page redirects back to — the sign-in could then never land.+ // ⚠️ The reason the desktop insists on a real browser survives here: this+ // SSO page's Google button uses Google's popup-based Identity Services+ // flow, where a popup window posts the result back to its opener. Whether+ // an in-app browser view can satisfy that is open, and flagged in+ // `sign_in_browser.dart`; it is why the phone case is confined to phones+ // rather than made the rule.+ opened = await openSignInPage(uri);+ }+ } catch (_) {+ // Browser handoff failure is recoverable within the same sign-in. Never+ // put a credential-bearing URL or a raw platform exception in the UI.+ }+ if (!_authWorkCurrent(authRevision) ||+ browserRevision != _loginBrowserRevision ||+ pendingAuthorizeUrl != url) {+ return;+ }+ openingLoginBrowser = false;+ if (!opened) {+ loginBrowserError =+ 'Couldn’t open your browser. Open it again or copy the sign-in link.';+ }+ notifyListeners();+ }++ /// Return immediately; late URLs, results and browser replies belong to the+ /// cancelled attempt and cannot change a subsequent sign-in.+ void cancelLogin() {+ if (_disposed || !canCancelLogin) return;+ _invalidateAuthWork();+ signingIn = false;+ pendingAuthorizeUrl = null;+ status = AppStatus.unauthenticated;+ _lastError = null;+ _lastErrorRetryable = false;+ cliLogin.cancel();+ notifyListeners();+ }++ Future<void> logout() async {+ final revision = _invalidateAuthWork();+ cliLogin.cancel();+ signingIn = false;+ pendingAuthorizeUrl = null;+ _closedHistory.clear();+ // Best-effort and fire-and-forget: local state is cleared below regardless of whether the CLI+ // process could be reached, but a real `harness logout` clears its saved session so the NEXT+ // launch doesn't silently sign back in without ever showing the login screen.+ unawaited(cliLogin.logout());+ _stopAllOfflineRetries();+ _stopAllLinkRetries();+ _stopAllAgentSyncTimers();+ // Tiles go, the saved layout stays: signing out and back in is the same+ // person at the same desk, and the file is only read once machines exist.+ await _closeAllPanes(persist: false);+ if (!_authWorkCurrent(revision)) return;+ _closedHistory.clear();+ await _pool?.closeAll();+ if (!_authWorkCurrent(revision)) return;+ _pool = null;+ _cliEndpoint = null;+ // Nothing to supervise for a signed-out app — and a daemon started by hand+ // on the login screen must not have its ready transition retry the machines.+ _daemonSupervisionTimer?.cancel();+ _daemonSupervisionTimer = null;+ _daemonGateFailed = false;+ _clearAllTurnActivity();+ currentUser = null;+ machines = [];+ machineStates.clear();+ expandedMachines.clear();+ selectedMachineId = null;+ status = AppStatus.unauthenticated;+ analytics.signedOut();+ // A session that ended without a message reports nothing — its absence IS+ // the finding, and a stale clock would attach that wait to whoever signs in+ // next.+ _awaitingFirstMessage = null;+ analyticsAccount.clear();+ notifyListeners();+ }++ void _onLocalFailure(String machineId, int code, String reason) {+ final machine = machineStates[machineId];+ if (machine == null || code != 4404) return;+ // The local CLI's relay found no linked trust for this machine — it now owns E2EE entirely.+ // A `harness link connect` run in a terminal (or another app instance) has no way to notify+ // this one directly, so poll every few seconds until it's picked up instead of waiting for+ // the user to click back into this machine.+ machine.needsLink = true;+ machine.agentLoadStatus = AgentLoadStatus.needsLink;+ // A 4404 can also arrive MID-SESSION ("peer revoked trust" in the CLI's+ // remoteRelay.ts) with terminals open on this machine. The disconnect+ // that follows deliberately no longer marks the node offline (see the+ // onStatus branch in _ensurePool), so the tiles have to be told here+ // instead — otherwise they keep rendering as live until a heartbeat+ // fails, and nothing records what to reattach once the machine is linked+ // again.+ _markSessionsUnreachable(+ machine,+ 'This machine is no longer linked. Link it again to reconnect.',+ );+ notifyListeners();+ _startLinkRetry(machineId);+ }++ void _ensurePool() {+ if (_pool != null) return;+ _pool = WsPool(+ wsBaseUrl: config.wsBaseUrl,+ autonomousEnv: _autonomousEnv,+ // Every real desktop WsConn dials the local CLI's loopback WS (transportKind.localPlaintext, see+ // _conn()), which never calls this — only the compile-time-only local-manual dev fixture (see+ // LocalManualFixture) still dials a backend directly with a token.+ accessTokenProvider: (force, failedToken) async {+ final directAuth = viewer?.auth;+ if (directAuth != null) {+ return directAuth.accessToken(force: force, failedToken: failedToken);+ }+ final fixture = localManualFixture;+ if (fixture != null) return fixture.apiKey;+ throw StateError(+ 'unreachable: only a viewer build and the local-manual dev fixture use a token-bearing WS transport',+ );+ },+ relayCodecs: viewer?.relayCodecs,+ transportPlugins: viewer?.transportPlugins,+ onAuthFailure: _signedOutAtRuntime,+ onLocalFailure: _onLocalFailure,+ onEvent: _handleEvent,+ onStatus: (machineId, nextStatus) {+ final machine = machineStates[machineId];+ if (machine == null) return;+ machine.connectionStatus = nextStatus;+ if (nextStatus == ConnectionStatus.connected) {+ machine.needsLink = false;+ _stopLinkRetry(machineId);+ // A daemon that just came up — first connect, or a reconnect after it+ // restarted — has never been told what is on the grid. Without this+ // the dial goes back to beeping about tiles in plain sight until the+ // next time a pane happens to change.+ _announceOpenPanesToDial();+ // ...nor which tile this window is looking at. The daemon repeats that to the dial after every+ // list push, which is what keeps the two screens from drifting apart — but it can only repeat+ // something it has been told, and until now the first telling waited for the focus to CHANGE.+ // A daemon restarted mid-session therefore had nothing to say, and a dial that re-anchored onto+ // the wrong tile stayed there.+ _announceAppFocus();+ // The local CLI never hands back `connected` until it has terminated E2EE (or confirmed+ // none is needed, for its own machine) — every machine's data is ready to load right away,+ // with no separate app-side readiness gate to wait on anymore.+ if (machine.isLocalMachine) {+ machine.transportMode = MachineTransportMode.localPlaintext;+ } else {+ machine.transportMode = MachineTransportMode.cloudE2ee;+ }+ // Route through _applyNodeStatus (not just `machine.nodeOnline = true`) for every machine,+ // not only the local one — a successful select IS the machine being reachable again, and+ // this is what lets a pending agent (captured below on disconnect) reattach automatically+ // instead of leaving the user stuck on the empty "select a machine" placeholder.+ unawaited(_applyNodeStatus(machine, true));+ unawaited(_loadMachineData(machine, force: true));+ _startAgentSyncTimer(machineId);+ } else if (nextStatus == ConnectionStatus.reconnecting ||+ nextStatus == ConnectionStatus.disconnected) {+ _stopAgentSyncTimer(machineId);+ _clearMachineActivity(machine);+ if (machine.isLocalMachine) {+ machine.transportMode = MachineTransportMode.localOffline;+ }+ // Same reasoning as above, mirrored: capture pendingOfflineAgentId from the currently-open+ // terminal (if any) so the connected branch above can reattach it, for every machine — this+ // used to be local-only, which is why a remote machine's terminal never came back on its own+ // after `harness start` on that machine, even though the guide screen promised it would.+ //+ // NOT while the machine is unlinked. NO_PEER_LINK is the local CLI failing a lookup in its+ // own peer table (remoteRelay.ts `dial`) before anything is dialled, so neither that close+ // nor the one `_startLinkRetry`'s `closeMachine` fires every few seconds says anything about+ // whether the OTHER computer is up — our socket never reaches it. Forcing nodeOnline false+ // here overwrote the REST `/api/machines` status, the one signal that does, and painted+ // every unlinked machine as off. Keyed on the sticky flag rather than the 4404 close on+ // purpose: the retry loop's own close() lands as a plain `disconnected` too. needsLink is+ // set by onLocalFailure, which runs before this branch for 4404 (see WsConn._onDone).+ if (!machine.needsLink) {+ unawaited(_applyNodeStatus(machine, false));+ }+ }+ notifyListeners();+ },+ );+ }++ /// The machine list is being fetched and there is nothing to show meanwhile.+ ///+ /// Only the FIRST fetch sets it: a refresh over a list already on screen+ /// keeps that list up (the rows are still true, just not from a moment ago)+ /// and reports nothing. The rail reads this to tell "loading" from "no+ /// machines", which an empty list alone cannot say.+ bool machinesLoading = false;++ Future<void> refreshMachines() async {+ final revision = _authRevision;+ if (!_authWorkCurrent(revision)) return;+ if (localManualFixture != null) {+ notifyListeners();+ return;+ }+ if (machines.isEmpty && !machinesLoading) {+ machinesLoading = true;+ notifyListeners();+ }+ try {+ await _refreshMachines(revision);+ } finally {+ // Said out loud: the list's own notify fires before this, so a flag+ // dropped silently here would leave the rail on its placeholders.+ if (_authWorkCurrent(revision) && machinesLoading) {+ machinesLoading = false;+ notifyListeners();+ }+ }+ }++ Future<void> _refreshMachines(int revision) async {+ // No machine is "this computer" to a viewer, which has no local CLI: every one — even the one+ // it runs on — is reached through the relay.+ final discovery = viewer == null ? _discovery : null;+ // The CLI computer id is the local identity source of truth. The loopback+ // status endpoint is trusted only when it advertises that same identity.+ final localComputerId = await discovery?.computerId();+ if (!_authWorkCurrent(revision)) return;+ final localFuture =+ discovery?.discover(expectedComputerId: localComputerId) ??+ Future<LocalCliEndpoint?>.value();+ final list = await _fetchMachines();+ final localEndpoint = await localFuture;+ if (!_authWorkCurrent(revision)) return;+ machines = list+ .where((machine) => machine.authMode == MachineAuthMode.remote)+ .toList();+ final visible = machines.map((machine) => machine.machineId).toSet();+ for (final entry in machineStates.entries) {+ if (!visible.contains(entry.key)) {+ _clearMachineActivity(entry.value);+ _stopOfflineRetry(entry.key);+ _stopLinkRetry(entry.key);+ _stopAgentSyncTimer(entry.key);+ }+ }+ machineStates.removeWhere((id, _) => !visible.contains(id));+ for (final machine in machines) {+ final state = machineStates.update(+ machine.machineId,+ (state) => state..machine = machine,+ ifAbsent: () => MachineState(machine),+ );+ state.localOnly =+ localComputerId != null &&+ _normalizeComputerId(machine.computerId) == localComputerId;+ if (state.localOnly && localEndpoint?.computerId == localComputerId) {+ state.localEndpoint = localEndpoint;+ if (state.connectionStatus == ConnectionStatus.connected) {+ state.transportMode = MachineTransportMode.localPlaintext;+ } else {+ state.transportMode = MachineTransportMode.localOffline;+ }+ } else if (state.localOnly) {+ // The token still identifies this as local, but the CLI is offline or+ // failed its identity/capability check. Never fall back to cloud E2EE.+ state.localEndpoint = null;+ state.transportMode = MachineTransportMode.localOffline;+ state.nodeOnline = false;+ _startOfflineRetry(state);+ } else {+ state.localEndpoint = null;+ state.transportMode = MachineTransportMode.cloudE2ee;+ }+ final reportedOnline = _nodeOnlineFromStatus(machine.status);+ if (!state.isLocalMachine &&+ reportedOnline != null &&+ (state.nodeOnline == null || state.nodeOnline != reportedOnline)) {+ unawaited(_applyNodeStatus(state, reportedOnline));+ }+ }+ if (localEndpoint != null) _updateLocalProjectSnapshot(localEndpoint);+ _autoConnectAndLoadMachines();+ notifyListeners();+ }++ // The daemon reports `connected` only once its own backend socket is open, but+ // `/api/machines` is a separate REST leg (fresh token refresh + fetch) that can still stall+ // briefly right after that — a bounded retry absorbs that transient window without falling+ // back to the 30s Dio timeout. Never retries an `ApiException` (a real HTTP error response);+ // only a `DioException` (timeout/connection failure) is worth a second try.+ // Capped at 2 attempts, not 3: `receiveTimeout` is 30s, so every retried attempt can cost+ // another 30s on a genuine failure — one retry absorbs the transient window above without+ // tripling how long a truly broken backend takes to surface its error.+ Future<List<Machine>> _fetchMachines() => withRetry(+ api.machines,+ maxAttempts: 2,+ initialDelay: const Duration(milliseconds: 500),+ isRetryable: (error) => error is DioException,+ );++ void _startOfflineRetry(MachineState machine) {+ final machineId = machine.machine.machineId;+ if (machine.nodeOnline != false ||+ (!machine.isLocalMachine && machine.pendingOfflineAgentId == null)) {+ _stopOfflineRetry(machineId);+ return;+ }+ if (_offlineRetryTimers.containsKey(machineId)) return;+ _offlineRetryTimers[machineId] = Timer.periodic(+ offlineRetryInterval,+ (_) => unawaited(_pollOfflineMachine(machineId)),+ );+ }++ void _stopOfflineRetry(String machineId) {+ _offlineRetryTimers.remove(machineId)?.cancel();+ }++ void _startLinkRetry(String machineId) {+ if (_linkRetryTimers.containsKey(machineId)) return;+ _linkRetryTimers[machineId] = Timer.periodic(offlineRetryInterval, (_) {+ final state = machineStates[machineId];+ if (state == null || !state.needsLink) {+ _stopLinkRetry(machineId);+ return;+ }+ unawaited(_pool?.closeMachine(machineId));+ _connectMachine(state);+ });+ }++ void _stopLinkRetry(String machineId) {+ _linkRetryTimers.remove(machineId)?.cancel();+ }++ void _stopAllLinkRetries() {+ for (final timer in _linkRetryTimers.values) {+ timer.cancel();+ }+ _linkRetryTimers.clear();+ }++ void _stopAllOfflineRetries() {+ for (final timer in _offlineRetryTimers.values) {+ timer.cancel();+ }+ _offlineRetryTimers.clear();+ _offlinePollsInFlight.clear();+ }++ void _startAgentSyncTimer(String machineId) {+ if (_agentSyncTimers.containsKey(machineId)) return;+ _agentSyncTimers[machineId] = Timer.periodic(agentSyncInterval, (_) {+ final machine = machineStates[machineId];+ if (machine == null) {+ _stopAgentSyncTimer(machineId);+ return;+ }+ unawaited(_syncAgentsIfChanged(machine));+ });+ }++ void _stopAgentSyncTimer(String machineId) {+ _agentSyncTimers.remove(machineId)?.cancel();+ }++ void _stopAllAgentSyncTimers() {+ for (final timer in _agentSyncTimers.values) {+ timer.cancel();+ }+ _agentSyncTimers.clear();+ }++ /// Silent safety-net reconciliation, ticked every [agentSyncInterval] while a machine is connected.+ /// Only writes/notifies if the fetched list actually differs from what's already shown — a steady+ /// state where push events (agent_synced et al.) have kept everything in sync produces zero visible+ /// effect. Deliberately does not touch agentLoadStatus/agentsLoadError/notifyListeners on failure:+ /// a real connectivity problem is already surfaced by the push path and the existing offline+ /// detection in _performMachineDataLoad, and a quiet background tick should not fight either.+ Future<void> _syncAgentsIfChanged(MachineState machine) async {+ if (machine.connectionStatus != ConnectionStatus.connected) return;+ if (machine.agentsLoadInFlight != null) {+ return; // a real (foreground) load already owns this tick+ }+ final connection = _conn(machine.machine.machineId);+ try {+ final response = await connection.request(+ 'agents_list',+ timeout: const Duration(seconds: 10),+ );+ final agents = (response['agents'] as List<dynamic>? ?? [])+ .map((item) => Agent.fromJson(item as Map<String, dynamic>))+ .toList();+ if (agentsEqual(machine.agents, agents)) return;+ _replaceAgents(machine, agents);+ notifyListeners();+ } catch (_) {+ // Silent by design — see doc comment above.+ }+ }++ /// Order-insensitive value equality for [Agent] lists — [Agent] has no operator== override, and a+ /// backend that returns the same agents in a different order must not register as "changed".+ ///+ /// ⚠️ Every field of [Agent] that the UI reads belongs here. This list is hand-maintained, and the+ /// cost of forgetting one is silent: the poll fetches the truth, compares it, decides nothing+ /// happened, and throws it away — so the field stays frozen at whatever it was for as long as the+ /// app runs. Add the field here in the same commit you add it to [Agent].+ @visibleForTesting+ static bool agentsEqual(List<Agent> a, List<Agent> b) {+ if (a.length != b.length) return false;+ final byId = {for (final agent in a) agent.id: agent};+ for (final agent in b) {+ final prev = byId[agent.id];+ if (prev == null ||+ prev.name != agent.name ||+ prev.sessionId != agent.sessionId ||+ prev.engine != agent.engine ||+ prev.engineDisplayName != agent.engineDisplayName ||+ prev.engineIconHint != agent.engineIconHint ||+ prev.codexHome != agent.codexHome ||+ prev.parentAgentId != agent.parentAgentId ||+ prev.project != agent.project ||+ prev.launchState != agent.launchState ||+ prev.launchError != agent.launchError ||+ prev.launchDetail != agent.launchDetail ||+ prev.status != agent.status ||+ prev.terminalAvailable != agent.terminalAvailable ||+ prev.terminalUnavailableReason != agent.terminalUnavailableReason) {+ return false;+ }+ }+ return true;+ }++ /// Public retry hook used by the offline join guide's "Retry now" action.+ Future<void> retryOfflineMachine(String machineId) =>+ _pollOfflineMachine(machineId);++ /// Runs `harness link connect <machineId> --stdin --json` (via [CliLink]) for a machine the+ /// relay reported `NO_PEER_LINK` for, then reconnects it. Returns null on success, or an error+ /// message to show inline. The app never sees the password's cryptographic use — this just+ /// pipes it to the CLI on stdin, the same as typing it at a terminal prompt would.+ Future<String?> connectWithPassword(+ String machineId,+ String password, {+ void Function(String stage)? onProgress,+ }) async {+ if (password.isEmpty) return 'Enter the remote password first';+ final result = await peerLinks.connect(+ machineId,+ password,+ onProgress: onProgress,+ displayName: machineStates[machineId]?.machine.displayName,+ );+ if (result.error != null) return result.error;+ final targetId = result.linkedMachineId ?? machineId;+ final state = machineStates[targetId];+ if (state != null) {+ state.needsLink = false;+ state.agentLoadStatus = AgentLoadStatus.idle;+ notifyListeners();+ // The old WsConn closed itself permanently on NO_PEER_LINK — connFor() would otherwise see a+ // matching endpointKey and hand back that dead connection instead of dialing a fresh one.+ await _pool?.closeMachine(targetId);+ _connectMachine(state);+ }+ return null;+ }++ List<LinkedMachine> linkedMachines = [];+ bool linkedMachinesLoading = false;+ String? linkedMachinesError;++ /// Sets (or replaces) THIS machine's persistent remote password (`harness remote-password+ /// set --stdin --json`) — another machine later connects with `connectWithPassword` using the+ /// same password, no token copy/paste involved.+ Future<RemotePasswordSetResult> setRemotePassword(String password) =>+ cliLink.setRemotePassword(password);++ /// Queries THIS machine's remote-password state (`harness remote-password status --json`).+ Future<RemotePasswordStatus> remotePasswordStatus() =>+ cliLink.remotePasswordStatus();++ /// Clears THIS machine's remote password (`harness remote-password clear --json`). Returns null+ /// on success.+ Future<String?> clearRemotePassword() => cliLink.clearRemotePassword();++ /// Refreshes the "machines this one trusts" list (`harness link list`).+ Future<void> refreshLinkedMachines() async {+ linkedMachinesLoading = true;+ notifyListeners();+ final result = await peerLinks.list();+ linkedMachinesLoading = false;+ linkedMachinesError = result.error;+ linkedMachines = result.machines;+ notifyListeners();+ }++ /// Removes a linked machine's trust pin, then refreshes the list. Returns null on success.+ Future<String?> unlinkMachine(String machineId) async {+ final error = await peerLinks.unlink(machineId);+ if (error == null) await refreshLinkedMachines();+ return error;+ }++ Future<void> _pollOfflineMachine(String machineId) async {+ final machine = machineStates[machineId];+ if (machine == null ||+ machine.nodeOnline != false ||+ (!machine.isLocalMachine && machine.pendingOfflineAgentId == null) ||+ _offlinePollsInFlight.contains(machineId)) {+ return;+ }+ _offlinePollsInFlight.add(machineId);+ try {+ if (machine.isLocalMachine) {+ final discovery = _discovery;+ final localComputerId = await discovery.computerId();+ if (localComputerId == null ||+ _normalizeComputerId(machine.machine.computerId) !=+ localComputerId) {+ return;+ }+ final endpoint = await discovery.discover(+ expectedComputerId: localComputerId,+ );+ if (endpoint == null || endpoint.computerId != localComputerId) return;+ machine.localEndpoint = endpoint;+ machine.localOnly = true;+ machine.transportMode = MachineTransportMode.localPlaintext;+ machine.nodeOnline = true;+ _connectMachine(machine);+ await _loadMachineData(machine, force: true);+ final pending = machine.pendingOfflineAgentId;+ if (pending != null) unawaited(_recoverPendingAgent(machine, pending));+ return;+ }+ final latest = (await _fetchMachines()).where(+ (item) => item.machineId == machineId,+ );+ if (latest.isEmpty) return;+ final reportedOnline = _nodeOnlineFromStatus(latest.first.status);+ if (reportedOnline == null) return;+ machine.machine = latest.first;+ await _applyNodeStatus(machine, reportedOnline);+ } catch (error) {+ debugPrint('offline node retry failed: $machineId: $error');+ } finally {+ _offlinePollsInFlight.remove(machineId);+ }+ }++ /// Open only the machine data sockets after discovery. Terminal panes remain+ /// lazy and are attached only when the user selects an agent row.+ void _autoConnectAndLoadMachines() {+ final visible = machines.map((machine) => machine.machineId).toSet();+ expandedMachines+ ..removeWhere((machineId) => !visible.contains(machineId))+ ..addAll(visible);+ if (machines.isEmpty) {+ selectedMachineId = null;+ return;+ }+ if (!visible.contains(selectedMachineId)) {+ // This computer, when it is one of them. The backend's order is its own+ // business and the local machine is not reliably first in it — landing on+ // someone else's box is a poor default when the user's own is right there.+ selectedMachineId = machines+ .firstWhere(+ (machine) =>+ machineStates[machine.machineId]?.isLocalMachine == true,+ orElse: () => machines.first,+ )+ .machineId;+ }+ for (final machine in machines) {+ _connectMachine(machineStates[machine.machineId]!);+ unawaited(_loadMachineData(machineStates[machine.machineId]!));+ }+ }++ /// A user-triggered reload is in flight.+ ///+ /// Read by the rail's reload button, which spins its glyph and stops taking+ /// clicks while this is true. It is deliberately NOT [machinesLoading]: that+ /// one means "there is nothing on screen yet", and a refresh over a list+ /// already up leaves it false on purpose.+ bool get machinesRefreshing => _retryInFlight != null;++ /// The run itself, so a second press joins the first instead of starting a+ /// second `GET /api/machines` beside it. The button's disabled state makes+ /// this hard to reach by pointer, but ⌘R has no such guard, and neither has+ /// the error strip's own retry.+ Future<void>? _retryInFlight;++ Future<void> retryMachines() {+ if (_disposed) return Future<void>.value();+ final inFlight = _retryInFlight;+ if (inFlight != null) return inFlight;+ late final Future<void> run;+ run = _performRetryMachines().whenComplete(() {+ if (identical(_retryInFlight, run)) {+ _retryInFlight = null;+ if (!_disposed) notifyListeners();+ }+ });+ _retryInFlight = run;+ notifyListeners();+ return run;+ }++ Future<void> _performRetryMachines() async {+ final revision = _authRevision;+ if (!_authWorkCurrent(revision)) return;+ // Re-verify the daemon first: a retry that skips straight to `refreshMachines()` can hit+ // the exact same "daemon not connected yet" timeout the button was pressed to escape.+ try {+ await ensureCliDaemonReady();+ } catch (error) {+ if (!_authWorkCurrent(revision)) return;+ _lastError = '$error';+ _lastErrorRetryable = true;+ notifyListeners();+ return;+ }+ if (!_authWorkCurrent(revision) || status == AppStatus.unauthenticated) {+ return;+ }+ if (currentUser == null) unawaited(_loadProfile());+ try {+ await refreshMachines();+ if (!_authWorkCurrent(revision)) return;+ _lastError = null;+ } catch (error) {+ if (!_authWorkCurrent(revision)) return;+ _lastError = 'Could not load machines: ${describeApiError(error)}';+ _lastErrorRetryable = true;+ notifyListeners();+ return;+ }+ await Future.wait(expandedMachines.toList().map(reloadMachineData));+ if (_authWorkCurrent(revision)) notifyListeners();+ }++ void toggleExpand(String machineId) {+ if (expandedMachines.contains(machineId)) {+ expandedMachines.remove(machineId);+ } else {+ expandedMachines.add(machineId);+ selectedMachineId = machineId;+ final machine = machineStates[machineId];+ if (machine != null) {+ _connectMachine(machine);+ unawaited(_loadMachineData(machine));+ }+ }+ notifyListeners();+ }++ /// Selects a machine without toggling its tree. Setup/status rows use this+ /// action so clicking an E2EE prompt always opens that machine's setup pane.+ Future<void> selectMachineForSetup(String machineId) async {+ final machine = machineStates[machineId];+ if (machine == null) return;+ _dismissedLinkPrompts.remove(machineId);+ selectedMachineId = machineId;+ expandedMachines.add(machineId);+ // Nothing is torn down here any more. That line existed because the content+ // area was one terminal belonging to whichever machine was selected, so+ // browsing to a second machine's setup form would otherwise have left the+ // first machine's terminal rendering underneath it. Tiles now say what they+ // are on their own and outlive the rail's selection, which makes selecting+ // a machine navigation again — and closing someone's running terminals+ // because they clicked a row would be the surprise, not the fix.+ //+ // The form itself arrives as a tile, which is the only way it can arrive at+ // all: a machine that needs linking has no agents to open.+ showMachinePane(machineId);+ _connectMachine(machine);+ notifyListeners();+ }++ void _connectMachine(MachineState machine) {+ // connFor() starts a new socket and reports `connecting` through onStatus,+ // or returns the existing socket with its current status intact. Do not+ // overwrite an already-connected socket when the user collapses and+ // re-expands the machine row; doing so leaves the UI permanently yellow+ // and disables every agent even though the transport is still ready.+ if (_pool != null &&+ (!machine.isLocalMachine || machine.usesLocalTransport)) {+ _conn(machine.machine.machineId);+ }+ }++ WsConn _conn(String machineId) {+ final testConnection = connectionForTest;+ if (testConnection != null) return testConnection(machineId);+ // The local-manual dev fixture exercises a locally-run backend+node stack directly (no real+ // `harness` CLI involved) — keep it on the old direct-cloud dial. Every other (real) machine now+ // goes through the local CLI daemon regardless of whether it's this computer's own machine or a+ // relayed one: the CLI proxies foreign machines to backend transparently (see `remoteRelay.ts` in+ // the harness CLI repo), so this app never dials backend's WS directly anymore.+ final connection = localManualFixture != null || viewer != null+ ? _pool!.connFor(machineId, transportKind: WsTransportKind.cloudE2ee)+ : _pool!.connFor(+ machineId,+ transportKind: WsTransportKind.localPlaintext,+ localWsUri: _cliEndpoint?.wsUri,+ localProtocolVersion:+ _cliEndpoint?.protocolVersion ?? localWsProtocolVersion,+ );+ _wireConnectionHooks(connection, machineId);+ return connection;+ }++ // Every machine — this computer's own, or a relayed one — now speaks the same plaintext local wire+ // protocol to the CLI (which terminates E2EE itself for relayed machines; see remoteRelay.ts in the+ // harness CLI repo). There is no per-machine branching left here at all.+ //+ // Known gap: LocalManualFixture (main_local_manual.dart, a compile-time-gated dev entry point that+ // exercises a locally-run backend+machine-node stack without SSO) used to run its OWN simulated E2EE+ // handshake against that local stack. That simulation depended on the crypto this app no longer+ // carries — the fixture now sends/receives plaintext-local-framed terminal data like every other+ // machine, which needs the target local machine-node to also expect plaintext for the fixture to+ // keep working end-to-end. Fixing that (if still desired) is a machine-node-side change, out of+ // scope here.+ void _wireConnectionHooks(WsConn connection, String machineId) {+ connection.onBinaryFrame = (frame) =>+ _handleTerminalBinary(machineId, frame);+ }++ /// Bulk terminal data for a machine, which may now be feeding several tiles.+ ///+ /// Read the live session identity instead of maintaining a second registry.+ /// Skip unrelated sessions before awaiting: every ignored async call adds a+ /// scheduling turn to the socket's incoming queue. Matching frames enter the+ /// session's ordered renderer queue synchronously, regardless of tab order.+ Future<void> _handleTerminalBinary(String machineId, Uint8List raw) async {+ final targets = panesFor(machineId)+ .map((pane) => pane.session)+ .whereType<TerminalSession>()+ .toList();+ if (targets.isEmpty) return;+ final clear = decodeTerminalLocal(raw);+ if (clear == null) {+ // Undecodable says the transport is wrong, not that one stream is — so+ // it goes to all of them.+ for (final terminal in targets) {+ terminal.transportLost('Binary terminal frame could not be decoded');+ }+ return;+ }+ for (final terminal in targets) {+ if (terminal.streamId == clear.streamId) {+ await terminal.handleBinary(clear);+ }+ }+ }++ Future<bool> _sendTerminalBinary(+ String machineId,+ TerminalBinaryFrame frame,+ ) async {+ final encoded = encodeTerminalLocal(frame);+ if (encoded == null) return false;+ return _conn(machineId).sendTerminalBinary(encoded);+ }++ Future<void> _loadMachineData(+ MachineState machine, {+ bool force = false,+ }) async {+ if (!_machineWorkCurrent(machine, _authRevision)) return;+ if (machine.agentLoadStatus == AgentLoadStatus.loaded && !force) return;+ if (machine.isLocalMachine && !machine.usesLocalTransport) {+ machine.transportMode = MachineTransportMode.localOffline;+ machine.nodeOnline = false;+ machine.agentsRefreshing = false;+ machine.agentsLoadError = 'Harness is offline — run harness login';+ machine.agentLoadStatus = machine.agents.isEmpty+ ? AgentLoadStatus.error+ : AgentLoadStatus.loaded;+ notifyListeners();+ return;+ }+ final inFlight = machine.agentsLoadInFlight;+ if (inFlight != null) return inFlight;+ late final Future<void> load;+ load = _performMachineDataLoad(machine).whenComplete(() {+ if (identical(machine.agentsLoadInFlight, load)) {+ machine.agentsLoadInFlight = null;+ }+ });+ machine.agentsLoadInFlight = load;+ return load;+ }++ Future<void> _performMachineDataLoad(MachineState machine) async {+ final revision = _authRevision;+ final hadAgents = machine.agents.isNotEmpty;+ machine.agentsRefreshing = hadAgents;+ if (!hadAgents) machine.agentLoadStatus = AgentLoadStatus.loading;+ machine.agentsLoadError = null;+ notifyListeners();+ final connection = _conn(machine.machine.machineId);+ final deadline = Stopwatch()..start();+ debugPrint('agents_list start: ${machine.machine.machineId}');+ try {+ const inventoryTimeout = Duration(seconds: 10);+ await connection.waitUntilReady(timeout: inventoryTimeout);+ if (!_machineWorkCurrent(machine, revision)) return;+ // Keep the inventory's existing total budget, including connection time.+ // Capabilities get their own budget only once the handshake is complete.+ final remaining = inventoryTimeout - deadline.elapsed;+ if (remaining <= Duration.zero) {+ throw const WsRequestTimeout('agents_list');+ }+ final capabilities = _loadTerminalCapabilities(+ machine,+ connection,+ revision,+ );+ final response = await connection.request(+ 'agents_list',+ timeout: remaining,+ );+ if (!_machineWorkCurrent(machine, revision)) return;+ final agents = (response['agents'] as List<dynamic>? ?? [])+ .map((item) => Agent.fromJson(item as Map<String, dynamic>))+ .toList();+ _replaceAgents(machine, agents);+ machine.agentLoadStatus = AgentLoadStatus.loaded;+ machine.agentsRefreshing = false;+ machine.agentsLoadError = null;+ debugPrint(+ 'agents_list success: ${machine.machine.machineId} '+ '(${machine.agents.length} agents)',+ );+ // Publish discovery immediately. The capability loader attaches waiting+ // panes when its reply arrives; either response may finish first.+ if (machine.terminalCapabilityLoadInFlight == null) {+ _attachPendingPanes(machine);+ _autoPickFirstAgent();+ }+ notifyListeners();+ await capabilities;+ return;+ } catch (error) {+ if (!_machineWorkCurrent(machine, revision)) return;+ machine.agentsRefreshing = false;+ // A request timing out while the local relay session still nominally reports "connected" means+ // the remote node itself has stopped answering — exactly what a REST-status flip to offline+ // means elsewhere, so route it through _applyNodeStatus (not just `nodeOnline = false`) so the+ // pending agent gets captured for auto-reattach, same as any other offline detection path.+ if (error is WsRequestTimeout) {+ machine.agentsLoadError = machine.isLocalMachine+ ? 'Harness is offline — run harness login'+ : 'Harness is offline — run harness start on that machine';+ if (machine.nodeOnline != false) {+ unawaited(_applyNodeStatus(machine, false));+ }+ if (!machine.isLocalMachine) {+ // The relay's cached upstream session can go stale at the E2EE-session layer without the+ // underlying transport ever closing — most commonly the relayed machine's own Harness+ // process restarting, which drops its in-memory session state but doesn't touch the socket.+ // Nothing else would ever notice, so force a fresh dial rather than let every future retry+ // keep timing out against the same dead session.+ unawaited(connection.forceReconnect());+ }+ } else {+ machine.agentsLoadError = 'Could not load harnesses: $error';+ }+ // A NO_PEER_LINK close already set needsLink (via onLocalFailure) perhaps a microtask before+ // this catch runs — don't downgrade that specific, actionable state back to a generic error.+ if (!hadAgents && machine.agentLoadStatus != AgentLoadStatus.needsLink) {+ machine.agentLoadStatus = AgentLoadStatus.error;+ }+ debugPrint('agents_list failed: ${machine.machine.machineId}: $error');+ }+ if (!_machineWorkCurrent(machine, revision)) return;+ // Order matters: a restored tile for THIS machine claims its agent before+ // the first-run convenience gets to look, so the two can never both open.+ _attachPendingPanes(machine);+ _autoPickFirstAgent();+ notifyListeners();+ }++ bool _machineWorkCurrent(MachineState machine, int revision) =>+ _authWorkCurrent(revision) &&+ identical(machineStates[machine.machine.machineId], machine);++ /// Whether the app has already opened a terminal on its own.+ ///+ /// Once, at startup, and never again: a later refresh must not reopen a+ /// terminal the user deliberately closed, and a machine that reconnects+ /// mid-session must not yank the pane away from whatever they are watching.+ bool _autoPickedAgent = false;++ /// Open the first agent on this computer, so the app arrives at work instead+ /// of at an instruction.+ ///+ /// "Select a machine, then an agent terminal" is a correct sentence and a+ /// poor first screen: in the ordinary case — one computer, agents already+ /// running on it — there is exactly one thing the user was going to click.+ ///+ /// Runs after a machine's data load rather than after the machine list,+ /// because [selectAgent] refuses on three counts that are only settled by+ /// then: the agent must exist, it must have a tmux terminal, and the+ /// machine's terminal protocol must have been negotiated. Called on every+ /// load and guarded, rather than wired to one specific load, because which+ /// machine answers first is not something this side decides.+ void _autoPickFirstAgent() {+ if (_autoPickedAgent) return;+ // V2 opens on the welcome screen; discovering an agent is not a request+ // to attach its terminal. Keep the startup gate settled for this run.+ _autoPickedAgent = true;+ }++ /// Ask a machine which engines it has.+ ///+ /// Called when the New Agent dialog opens, not at connect: the answer costs+ /// one interactive shell per engine on the far side, and it is only ever+ /// looked at in that dialog.+ ///+ /// That caller passes [force], and should: engines come and go through a+ /// terminal this app never sees, and an install the dialog itself started+ /// invalidates the stored answer as it finishes. Without it the app probes+ /// once per run and then insists, for the rest of the session, on what was+ /// true when it started. The cache is here to collapse a re-open into one+ /// sweep, not to spare the machine the question.+ ///+ /// Deduplicated on [MachineEngines.inFlight] so opening the dialog twice, or+ /// reopening it mid-probe, does not start a second sweep. Never throws — a+ /// machine that cannot answer leaves every engine unknown, and unknown is+ /// rendered as the dialog behaved before this existed.+ Future<void> probeEngines(String machineId, {bool force = false}) {+ final machine = machineStates[machineId];+ if (machine == null) return Future.value();+ final existing = machine.engines.inFlight;+ if (existing != null) return existing;+ if (machine.engines.loaded && !force) return Future.value();+ final work = _probeEngines(machine);+ machine.engines.inFlight = work;+ notifyListeners();+ return work;+ }++ Future<void> _probeEngines(MachineState machine) async {+ try {+ final result = await _conn(machine.machine.machineId).request(+ 'engines_probe',+ // The engine list travels so a machine only pays for what the dialog+ // shows. An older CLI that does not know this request answers with an+ // error, which lands in the catch below as "unknown" — never as a wrong+ // "not installed", because a CLI predating the feature would otherwise+ // report every engine missing and offer to install the ones already+ // there.+ payload: {'engines': allEngines.map((e) => e.id).toList()},+ timeout: const Duration(seconds: 30),+ );+ final raw = result['engines'];+ if (raw is! List) throw const FormatException('engines_probe: no list');+ machine.engines.replace(+ raw.map(EngineAvailability.fromJson).whereType<EngineAvailability>(),+ );+ } catch (error) {+ // A CLI that predates `engines_probe` refuses it by code; `detail` already+ // reads as a sentence when the peer sends one, so prefer it verbatim.+ machine.engines.error = error is WsRequestFailure+ ? (error.detail?.isNotEmpty == true ? error.detail : error.code)+ : 'This machine could not report its engines';+ } finally {+ machine.engines.inFlight = null;+ notifyListeners();+ }+ }++ Future<void> _loadTerminalCapabilities(+ MachineState machine,+ WsConn connection,+ int revision,+ ) {+ final pending = machine.terminalCapabilityLoadInFlight;+ if (pending != null) return pending;+ late final Future<void> load;+ load = _readTerminalCapabilities(machine, connection, revision)+ .whenComplete(() {+ if (identical(machine.terminalCapabilityLoadInFlight, load)) {+ machine.terminalCapabilityLoadInFlight = null;+ }+ });+ machine.terminalCapabilityLoadInFlight = load;+ return load;+ }++ Future<void> _readTerminalCapabilities(+ MachineState machine,+ WsConn connection,+ int revision,+ ) async {+ try {+ final result = await connection.request(+ 'terminal_capabilities',+ payload: {'protocolVersion': TerminalSession.protocolVersion},+ timeout: const Duration(seconds: 8),+ );+ if (!_machineWorkCurrent(machine, revision)) return;+ machine.terminalCapabilityLoaded = true;+ machine.terminalCapabilityAvailable =+ result['protocolVersion'] == TerminalSession.protocolVersion &&+ result['backend'] == 'tmux' &&+ result['available'] == true;+ machine.terminalCapabilityError = machine.terminalCapabilityAvailable+ ? null+ : 'tmux terminal streaming is unavailable';+ final features = result['features'];+ machine.terminalPasteRawAvailable =+ features is Map && features['pasteRaw'] == true;+ machine.terminalImagePasteAvailable =+ features is Map && features['imagePaste'] == true;+ machine.terminalPasteFileAvailable =+ features is Map && features['pasteFile'] == true;+ machine.mediaPreviewAvailable =+ features is Map && features['mediaPreview'] == true;+ } catch (_) {+ if (!_machineWorkCurrent(machine, revision)) return;+ machine.terminalCapabilityLoaded = true;+ machine.terminalCapabilityAvailable = false;+ machine.terminalCapabilityError = 'Could not negotiate terminal protocol';+ machine.terminalPasteRawAvailable = false;+ machine.terminalImagePasteAvailable = false;+ machine.terminalPasteFileAvailable = false;+ machine.mediaPreviewAvailable = false;+ }+ if (!_machineWorkCurrent(machine, revision)) return;+ if (machine.agentLoadStatus != AgentLoadStatus.loading &&+ !machine.agentsRefreshing) {+ _attachPendingPanes(machine);+ _autoPickFirstAgent();+ notifyListeners();+ }+ }++ void _replaceAgents(MachineState machine, List<Agent> agents) {+ final nextIds = agents.map((agent) => agent.id).toSet();+ for (final agentId in machine.processingAgentIds.difference(nextIds)) {+ _cancelTurnActivity(machine.machine.machineId, agentId);+ }+ machine.agents = agents;+ final pending = machine.pendingOfflineAgentId;+ if (pending != null && !nextIds.contains(pending)) {+ machine.pendingOfflineAgentId = null;+ _stopOfflineRetry(machine.machine.machineId);+ }+ if (machine.activeAgentId != null &&+ !nextIds.contains(machine.activeAgentId) &&+ panesFor(machine.machine.machineId).isEmpty) {+ machine.activeAgentId = null;+ }+ machine.processingAgentIds.removeWhere((id) => !nextIds.contains(id));+ machine.sessionAgentIds.clear();+ for (final agent in agents) {+ final sessionId = agent.sessionId;+ if (sessionId != null) machine.sessionAgentIds[sessionId] = agent.id;+ }+ for (final sessionId in machine.pendingProcessingSessions.toList()) {+ final agentId = machine.sessionAgentIds[sessionId];+ if (agentId == null) continue;+ machine.pendingProcessingSessions.remove(sessionId);+ _markAgentProcessing(machine, agentId);+ }+ }++ void _upsertAgent(MachineState machine, Agent agent) {+ final index = machine.agents.indexWhere((item) => item.id == agent.id);+ final previous = index == -1 ? null : machine.agents[index];+ if (index == -1) {+ machine.agents = [...machine.agents, agent];+ } else {+ machine.agents = [...machine.agents]..[index] = agent;+ }+ machine.sessionAgentIds.removeWhere((_, id) => id == agent.id);+ final sessionId = agent.sessionId;+ if (sessionId != null) {+ machine.sessionAgentIds[sessionId] = agent.id;+ if (machine.pendingProcessingSessions.remove(sessionId)) {+ _markAgentProcessing(machine, agent.id);+ }+ }+ machine.agentLoadStatus = AgentLoadStatus.loaded;+ machine.agentsLoadError = null;+ if (agent.launchState == 'failed' && previous?.launchState != 'failed') {+ _lastError = agent.launchDetail ?? 'Failed to start ${agent.name}';+ // The launch already ran and failed (e.g. the engine's automatic+ // install failed) — reloading the machine list will not install it.+ _lastErrorRetryable = false;+ }+ }++ void _renameAgent(MachineState machine, String agentId, String name) {+ final index = machine.agents.indexWhere((agent) => agent.id == agentId);+ if (index == -1 || name.trim().isEmpty) return;+ final cleanName = name.trim();+ machine.agents = [...machine.agents]+ ..[index] = machine.agents[index].copyWith(name: cleanName);+ for (final pane in panesFor(machine.machine.machineId)) {+ if (pane.agentId != agentId) continue;+ pane.session?.renameAgent(cleanName);+ }+ }++ Future<void> _removeAgent(MachineState machine, String agentId) async {+ machine.agents = machine.agents+ .where((agent) => agent.id != agentId)+ .toList();+ machine.sessionAgentIds.removeWhere((_, id) => id == agentId);+ _cancelTurnActivity(machine.machine.machineId, agentId);+ if (machine.activeAgentId == agentId) machine.activeAgentId = null;+ if (machine.pendingOfflineAgentId == agentId) {+ machine.pendingOfflineAgentId = null;+ _stopOfflineRetry(machine.machine.machineId);+ }+ // Every tile showing it, not just the focused one — and without+ // `terminal_close`, which would be addressed to an agent the machine has+ // already destroyed.+ final machineId = machine.machine.machineId;+ for (final pane in allPanes.toList()) {+ if (pane.machineId != machineId || pane.agentId != agentId) continue;+ await _detachSession(pane, sendClose: false);+ for (final swarm in swarms) {+ swarm.remove(pane);+ }+ }+ _persistLayout();+ _announceAppFocus();+ }++ String? _eventAgentId(+ MachineState machine,+ Map<String, dynamic> event,+ Map<String, dynamic> payload,+ ) {+ final explicit = payload['agentId'] ?? event['agentId'];+ if (explicit is String && explicit.isNotEmpty) return explicit;+ final session = payload['sessionId'] ?? event['dbSessionId'];+ if (session is! String || session.isEmpty) return null;+ return machine.sessionAgentIds[session];+ }++ String? _eventSessionId(+ Map<String, dynamic> event,+ Map<String, dynamic> payload,+ ) {+ final session = payload['sessionId'] ?? event['dbSessionId'];+ return session is String && session.isNotEmpty ? session : null;+ }++ /// Starts the clock `app_first_message` measures. [from] is `sign_in` for a+ /// fresh log-in and `launch` for an app opened with a session already there.+ ///+ /// One body, called by both routes and by the test seam below — a second+ /// place building this record is a second place to get it wrong.+ void _armFirstMessage(String from) =>+ _awaitingFirstMessage = (at: DateTime.now(), from: from);++ /// Closes that clock out, once.+ ///+ /// A one-shot latch rather than a counter: the record is read and cleared in+ /// the same breath, so every turn after the first finds nothing and there is+ /// never a "which message is this" to get wrong.+ ///+ /// ⚠️ Called from `turn_started` ONLY, never from the other two routes into+ /// [_markAgentProcessing]. A `turn_heartbeat`, and an adopted agent found+ /// already mid-turn when this app connected, are both work that was under way+ /// before anybody here typed anything — counting either would report a+ /// near-zero wait for a returning user who has not said a word.+ void _reportFirstMessage() {+ if (_awaitingFirstMessage case final login?) {+ _awaitingFirstMessage = null;+ analytics.appFirstMessage(+ from: login.from,+ secondsSinceLogin: DateTime.now().difference(login.at).inSeconds,+ );+ }+ }++ /// [_armFirstMessage], for a test: signing in needs a live CLI, and what is+ /// worth pinning is what the first turn AFTER it does.+ @visibleForTesting+ void armFirstMessageForTest(String from) => _armFirstMessage(from);++ String _turnActivityKey(String machineId, String agentId) =>+ '$machineId\u0000$agentId';++ bool _markAgentProcessing(MachineState machine, String agentId) {+ final changed = machine.processingAgentIds.add(agentId);+ final key = _turnActivityKey(machine.machine.machineId, agentId);+ _turnActivityWatchdogs.remove(key)?.cancel();+ _turnActivityWatchdogs[key] = Timer(turnActivityTimeout, () {+ _turnActivityWatchdogs.remove(key);+ // Closed even when the machine has been replaced under us: this path is+ // the only end a stalled turn ever gets, and a stats turn left open would+ // sit there until quit and then bank every hour since as work.+ harnessStats.onTurnEnded(key);+ final current = machineStates[machine.machine.machineId];+ if (!identical(current, machine)) return;+ if (machine.processingAgentIds.remove(agentId)) notifyListeners();+ });+ return changed;+ }++ /// Whether this agent is mid-turn, by the app's own reckoning.+ ///+ /// Fed by `turn_started`/`turn_heartbeat`/`turn_ended` and by the same watchdog that clears a+ /// stalled turn, so it answers what the tiles already draw rather than a second opinion.+ ///+ /// Read by the model menu, which disables itself for exactly the agents the CLI would refuse with+ /// AGENT_BUSY. It is deliberately NOT authoritative: only the CLI inspects the pane, and a turn+ /// can begin between a build and a tap. This spares the user the round trip in the common case;+ /// the refusal remains the thing that guarantees no turn is lost.+ bool agentIsProcessing(String machineId, String agentId) =>+ machineStates[machineId]?.processingAgentIds.contains(agentId) ?? false;++ // ── blocked agents ────────────────────────────────────────────────────────++ /// The question this agent stopped on, if it is waiting for one.+ ///+ /// Read by the tile, which rings itself while its agent is blocked. That ring+ /// is the whole surface: an agent asking something is a fact about the pane+ /// you are looking at, not a queue to be worked through somewhere else.+ PendingQuestion? questionFor(String machineId, String agentId) =>+ machineStates[machineId]?.blockedAgents[agentId];++ void _cancelTurnActivity(String machineId, String agentId) {+ final key = _turnActivityKey(machineId, agentId);+ _turnActivityWatchdogs.remove(key)?.cancel();+ // Every ordinary end of a turn comes through here — `turn_ended`, a+ // disconnect, a deleted agent — so this is where the clock stops. An end for+ // a turn this process never saw start contributes nothing (see+ // `HarnessStats.onTurnEnded`), which is what makes the disconnect sweep safe.+ harnessStats.onTurnEnded(key);+ final machine = machineStates[machineId];+ machine?.processingAgentIds.remove(agentId);+ // A question cannot outlive its own turn — the daemon's watcher says the+ // same thing from the other end, tearing down and announcing a close when+ // the turn ends. Clearing here as well means the row cannot survive a close+ // frame that was dropped, and this is also the path a deleted agent takes.+ machine?.blockedAgents.remove(agentId);+ }++ void _clearMachineActivity(MachineState machine) {+ for (final agentId in machine.processingAgentIds.toList()) {+ _cancelTurnActivity(machine.machine.machineId, agentId);+ }+ machine.processingAgentIds.clear();+ machine.pendingProcessingSessions.clear();+ machine.blockedAgents.clear();+ }++ void _clearAllTurnActivity() {+ for (final timer in _turnActivityWatchdogs.values) {+ timer.cancel();+ }+ _turnActivityWatchdogs.clear();+ for (final machine in machineStates.values) {+ machine.processingAgentIds.clear();+ machine.pendingProcessingSessions.clear();+ machine.blockedAgents.clear();+ }+ }++ Future<void> reloadMachineData(String machineId) async {+ final machine = machineStates[machineId];+ if (machine == null) return;+ _connectMachine(machine);+ await _loadMachineData(machine, force: true);+ }++ /// What every connected REMOTE machine's agent accounts have spent, asked in+ /// parallel and read there with that machine's own credentials (`usage_read`).+ ///+ /// This computer's own accounts are not asked here — the app reads those+ /// directly, the Keychain included. A remote machine may be signed in to a+ /// different subscription, and a rate limit belongs to an account rather than+ /// a computer, so the only honest way to show that one is to ask the machine+ /// that holds it.+ ///+ /// ⚠️ **A machine whose CLI predates `usage_read` does not refuse it — it goes+ /// silent.** The frame reaches it as an E2EE envelope it does not know to+ /// open, so the requestId inside is never read and nothing replies. That is a+ /// timeout, not an `UNSUPPORTED`, which is why this asks with a short one and+ /// treats every failure alike: a machine that cannot say has nothing to add,+ /// and it must never hold up the figures of the ones that can.+ Future<List<MachineUsage>> readRemoteUsage() async {+ final remotes = [+ for (final machine in machineStates.values)+ if (!machine.isLocalMachine &&+ machine.connectionStatus == ConnectionStatus.connected)+ machine,+ ];+ final answers = await Future.wait([+ for (final machine in remotes) _readMachineUsage(machine),+ ]);+ return [for (final answer in answers) ?answer];+ }++ /// What to call THIS computer wherever a usage figure has to say whose it is.+ ///+ /// The same `displayName` the sidebar prints and `_readMachineUsage` labels+ /// every remote machine with, so a panel listing one local and one remote+ /// account names them in one vocabulary rather than setting a hostname+ /// beside the words "this computer".+ ///+ /// Falls back to the OS hostname when the local machine has not been fetched+ /// yet — the rail can open before `refreshMachines` lands — and to null when+ /// even that is empty, which the caller renders by dropping the caption+ /// rather than printing a blank one.+ String? get thisMachineName {+ for (final state in machineStates.values) {+ if (state.isLocalMachine) return state.machine.displayName;+ }+ return localHostnameOrNull();+ }++ Future<MachineUsage?> _readMachineUsage(MachineState machine) async {+ try {+ final reply = await _conn(machine.machine.machineId)+ .request('usage_read', timeout: const Duration(seconds: 10));+ final readings = parseUsageReadResult(reply);+ if (readings.isEmpty) return null;+ return MachineUsage(+ machineName: machine.machine.displayName,+ readings: readings,+ );+ } catch (_) {+ return null;+ }+ }++ /// Media uses the existing machine-scoped, encrypted file RPC. It is never+ /// queued for a disconnected machine or resolved against this app's cwd.+ Future<Map<String, dynamic>> readRemoteMediaChunk(+ String machineId,+ String agentId,+ String target, {+ required int offset,+ String? revision,+ }) async {+ final machine = machineStates[machineId];+ if (machine == null ||+ machine.needsLink ||+ machine.nodeOnline == false ||+ machine.connectionStatus != ConnectionStatus.connected) {+ throw const RemoteMediaException(+ 'This machine is disconnected. Reconnect and try opening the preview again.',+ );+ }+ if (!machine.mediaPreviewAvailable) {+ throw const RemoteMediaException(+ 'Update the Harness CLI on this remote machine to open image and video previews.',+ );+ }+ final connection = _conn(machineId);+ if (!connection.isReady) {+ throw const RemoteMediaException(+ 'This machine is disconnected. Reconnect and try opening the preview again.',+ );+ }+ try {+ return await connection.request(+ 'agent_read_file',+ payload: {+ 'agentId': agentId,+ 'path': target,+ 'media': true,+ 'offset': offset,+ 'revision': ?revision,+ },+ timeout: const Duration(seconds: 15),+ );+ } on WsRequestFailure catch (error) {+ throw RemoteMediaException(switch (error.code) {+ 'MEDIA_NOT_FOUND' || 'NOT_FOUND' => 'This file is no longer available on the remote machine. It may have moved or been deleted.',+ 'MEDIA_TOO_LARGE' => 'Remote previews support files up to 512 MB. Use a smaller export or transfer this file separately.',+ 'MEDIA_CHANGED' => 'The file changed while downloading. Wait for it to finish generating and try again.',+ 'MEDIA_UNSUPPORTED' => 'This file is not a supported image or video.',+ 'MEDIA_INVALID_REQUEST' =>+ 'Use a full path or a path inside this harness’s working folder.',+ 'AGENT_NOT_FOUND' =>+ 'This harness is no longer available. Reconnect and try again.',+ 'NOT_TEXT' || 'FILE_TOO_LARGE' => 'Update the Harness CLI on this remote machine to open media previews.',+ _ => 'The remote machine could not read this file. Check that it is accessible and try again.',+ });+ } catch (_) {+ throw const RemoteMediaException(+ 'The media download was interrupted. Check the connection and try again.',+ );+ }+ }++ /// One-level directory listing on the remote machine, for the New Agent folder browser.+ /// Returns `{path, entries: [{name, isDir}], truncated}` or `{error}` — the caller renders both.+ Future<Map<String, dynamic>> listRemoteFolder(+ String machineId,+ String? path,+ ) async {+ final connection = _conn(machineId);+ try {+ return await connection.request(+ 'fs_list_dir',+ payload: {+ ...?path == null ? null : {'path': path},+ },+ timeout: const Duration(seconds: 10),+ );+ } catch (error) {+ return {'error': 'UNREACHABLE'};+ }+ }++ /// Every Codex profile folder the CLI on [machineId] can offer, merged with [observedPaths]+ /// (Codex homes already known from this same machine's other Codex agents). Runs entirely on that+ /// machine — this app never touches a filesystem itself, which is what makes it work for a remote+ /// machine too. Returns `{profiles: [{path, label}]}` or `{error}`.+ Future<Map<String, dynamic>> listCodexProfiles(+ String machineId, {+ Set<String> observedPaths = const {},+ }) async {+ final connection = _conn(machineId);+ try {+ return await connection.request(+ 'codex_profiles_list',+ payload: {'observedPaths': observedPaths.toList()},+ timeout: const Duration(seconds: 10),+ );+ } catch (error) {+ return {'error': 'UNREACHABLE'};+ }+ }++ /// Links [path] as a Codex profile on [machineId], persisted there so it survives future+ /// requests. Returns `{profile: {path, label}}` or `{error}`.+ Future<Map<String, dynamic>> linkCodexProfile(+ String machineId,+ String path,+ ) async {+ final connection = _conn(machineId);+ try {+ return await connection.request(+ 'codex_profile_link',+ payload: {'path': path},+ timeout: const Duration(seconds: 10),+ );+ } catch (error) {+ return {'error': 'UNREACHABLE'};+ }+ }++ /// Starts an agent, or recovers this form's earlier request after a lost reply.+ /// Returns null on success, or an inline message; [attempt] tells the form+ /// whether to offer Check status instead of inviting another creation.+ Future<String?> createAgent(+ String machineId, {+ required String engine,+ required String folder,+ bool bypassPermission = false,+ String? codexHome,+ String? swarmId,+ PaneSplitRequest? split,+ AgentCreationAttempt? attempt,+ }) {+ final creation = attempt ?? AgentCreationAttempt();+ final choices = <String, dynamic>{+ 'engine': engine,+ 'cwd': folder,+ 'bypassPermission': bypassPermission,+ 'codexHome': ?codexHome,+ };+ if (creation._choices != null &&+ (creation._machineId != machineId ||+ !mapEquals(creation._choices, choices))) {+ return Future.value(+ 'Check the original request before changing its choices.',+ );+ }+ if (creation._finished) return Future.value(creation._outcome);+ if (creation._inFlight case final inFlight?) return inFlight;+ if (creation._choices == null) {+ creation._choices = choices;+ creation._machineId = machineId;+ creation._targetId = split?.swarmId ?? swarmId ?? activeSwarmId;+ creation._split = split;+ }+ final work = _createAgentWithReceipt(creation);+ creation._inFlight = work;+ return work.whenComplete(() => creation._inFlight = null);+ }++ String? _creationPlacementError(String targetId, PaneSplitRequest? split) {+ if (split != null && !isPaneSplitCurrent(split)) {+ return 'The layout changed. Close this dialog and split the pane again.';+ }+ final target = swarms.where((s) => s.id == targetId).firstOrNull;+ if (target == null) return 'This tab was closed';+ if (target.panes.length >= maxPanes) {+ return 'This tab is full. Open a new tab to create a harness.';+ }+ return null;+ }++ String _creationFailureMessage(String code, String? detail, String machine) =>+ switch (code) {+ 'CWD_NOT_FOUND' || 'INVALID_CWD' =>+ 'The project folder is unavailable on $machine. '+ 'Choose another folder and try again.',+ 'TMUX_UNAVAILABLE' =>+ 'Harness needs tmux to start harnesses on $machine. '+ 'Install tmux there, then try again.',+ 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>+ 'Update the harness CLI on this machine to create a harness',+ _ => 'Create harness failed: ${detail ?? code}',+ };++ Future<String?> _createAgentWithReceipt(AgentCreationAttempt creation) async {+ final machineId = creation._machineId!;+ final targetId = creation._targetId!;+ final split = creation._split;+ final choices = creation._choices!;+ final machine = machineStates[machineId];+ if (machine == null) return 'Machine not found';+ final machineName = machine.machine.displayName;+ // A status check must remain possible even if the destination closed or a+ // capability probe changed while the first create was already in flight.+ if (!creation.awaitingConfirmation) {+ final placementError = _creationPlacementError(targetId, split);+ if (placementError != null) return placementError;+ if (choices['codexHome'] != null) {+ if (choices['engine'] != 'codex') {+ return 'Choose a Codex profile only for Codex';+ }+ if (machine.engines['codex']?.supportsCodexHome != true) {+ return 'Update the harness CLI on this machine to choose a Codex profile';+ }+ }+ }+ final connection = _conn(machineId);+ final operation = creation.awaitingConfirmation+ ? 'agent_create_status'+ : 'agent_create';+ final unconfirmed =+ '$machineName has not confirmed the new harness yet. '+ 'Check status before creating another.';+ Map<String, dynamic> result;+ creation._awaitingConfirmation = true;+ try {+ if (operation == 'agent_create_status') {+ result = await connection.request(+ operation,+ payload: {'creationId': creation._id},+ timeout: const Duration(seconds: 10),+ );+ if (result['creationId'] != creation._id) return unconfirmed;+ } else {+ result = await connection.request(+ operation,+ payload: {...choices, 'creationId': creation._id},+ timeout: const Duration(seconds: 20),+ );+ }+ } on WsRequestFailure catch (failure) {+ if (operation == 'agent_create_status') {+ if (failure.code == 'UNSUPPORTED' ||+ failure.code == 'UNSUPPORTED_ON_REMOTE' ||+ failure.code == 'E2EE_REQUIRED') {+ return '$machineName cannot check this creation. '+ 'Use Find a harness to look for it before creating another.';+ }+ return unconfirmed;+ }+ // Refusals that happen before a launch are safe to correct. INTERNAL,+ // spawn timeouts and connection failures cannot prove nothing started.+ const refusedBeforeLaunch = {+ 'CWD_NOT_FOUND',+ 'INVALID_CWD',+ 'INVALID_ENGINE',+ 'INVALID_GRID',+ 'INVALID_CODEX_HOME',+ 'TMUX_UNAVAILABLE',+ 'TMUX_TOO_OLD_FOR_GRID',+ 'GRID_CONFIG_FAILED',+ 'UNSUPPORTED_ON_REMOTE',+ 'UNSUPPORTED',+ };+ if (refusedBeforeLaunch.contains(failure.code)) {+ return creation._complete(+ _creationFailureMessage(failure.code, failure.detail, machineName),+ );+ }+ return unconfirmed;+ } catch (_) {+ // Includes disconnects, malformed replies and timeouts. A transport error+ // is not evidence that the machine did not execute the request.+ return unconfirmed;+ }+ if ((result.containsKey('creationId') || result['state'] != null) &&+ result['creationId'] != creation._id) {+ return unconfirmed;+ }+ switch (result['state']) {+ case 'missing':+ // An old CLI may have created the agent before being updated to a+ // receipt-aware version. Missing is not proof that nothing started.+ // Check status stays read-only, even across upgrades and reconnects.+ return '$machineName has no record of this request. '+ 'Use Find a harness to look for it before creating another.';+ case 'pending':+ return '$machineName is still starting your harness. Check again in a moment.';+ case 'unconfirmed':+ return '$machineName could not confirm whether this harness started. '+ 'Use Open Harness to look for it before creating another.';+ case 'unavailable':+ return creation._complete(+ 'This harness was created but is no longer available. '+ 'You can create a new one.',+ );+ case 'failed':+ final failure = result['failure'];+ if (failure is! Map || failure['code'] is! String) return unconfirmed;+ return creation._complete(+ _creationFailureMessage(+ failure['code'] as String,+ failure['detail'] is String ? failure['detail'] as String : null,+ machineName,+ ),+ );+ case 'created':+ case null: // A successful first response from a CLI predating receipts.+ break;+ default:+ return unconfirmed;+ }+ final raw = result['agent'];+ if (raw is! Map || raw['id'] is! String || (raw['id'] as String).isEmpty) {+ return unconfirmed;+ }+ final Agent agent;+ try {+ agent = Agent.fromJson(Map<String, dynamic>.from(raw));+ } catch (_) {+ return unconfirmed;+ }+ creation._complete(null);+ if (_disposed || machineStates[machineId] != machine) return null;+ _upsertAgent(machine, agent);+ // Apply each creation receipt once, even if its transport result is replayed.+ harnessStats.onAgentSpawned();+ notifyListeners();+ if (_creationPlacementError(targetId, split) != null) {+ _lastError =+ 'The harness was created, but its original tab or layout changed. '+ 'Use Open Harness to find it.';+ _lastErrorRetryable = false;+ notifyListeners();+ return null;+ }+ await assignAgentToPane(+ null,+ machineId,+ agent.id,+ swarmId: targetId,+ split: split,+ );+ return null;+ }++ /// Renames a machine via `PATCH /api/machines/:machineId` (control-plane REST — the machine's+ /// `name` is backend-owned, unlike an agent's, which lives on the harness CLI). Returns null on+ /// success, or an error message to show inline in the caller's dialog.+ Future<String?> renameMachine(String machineId, String name) async {+ final state = machineStates[machineId];+ if (state == null) return 'Machine not found';+ final trimmed = name.trim();+ if (trimmed.isEmpty) return 'Name cannot be empty';+ try {+ await api.renameMachine(machineId: machineId, name: trimmed);+ } catch (error) {+ return 'Rename failed: $error';+ }+ state.machine = state.machine.copyWith(name: trimmed);+ final index = machines.indexWhere((m) => m.machineId == machineId);+ if (index != -1) machines[index] = state.machine;+ notifyListeners();+ return null;+ }++ /// Permanently deletes a machine from the account (backend `DELETE /api/machines/:id`) — not to+ /// be confused with [unlinkMachine], which only drops this computer's local E2EE trust pin and+ /// leaves the machine itself intact. Returns null on success, or an error message to show inline.+ Future<String?> deleteMachine(String machineId) async {+ final state = machineStates[machineId];+ if (state == null) return 'Machine not found';+ try {+ await api.deleteMachine(machineId: machineId);+ } catch (error) {+ return 'Delete failed: $error';+ }+ // Any tile still showing this machine would otherwise sit forever in the "waiting to answer"+ // busy state, since the machine can never be found again after this.+ for (final pane in panesFor(machineId).toList()) {+ for (final swarm in swarms) {+ swarm.remove(pane);+ }+ await _detachSession(pane, sendClose: true);+ }+ _persistLayout();+ _stopAgentSyncTimer(machineId);+ machineStates.remove(machineId);+ machines.removeWhere((m) => m.machineId == machineId);+ if (selectedMachineId == machineId) selectedMachineId = null;+ notifyListeners();+ return null;+ }++ /// Renames an agent via `agent_update`. Returns null on success, or an error message to show+ /// inline in the caller's dialog.+ Future<String?> renameAgent(+ String machineId,+ String agentId,+ String name,+ ) async {+ final machine = machineStates[machineId];+ if (machine == null) return 'Machine not found';+ final trimmed = name.trim();+ if (trimmed.isEmpty) return 'Name cannot be empty';+ Map<String, dynamic> result;+ try {+ result = await _conn(+ machineId,+ ).request('agent_update', payload: {'agentId': agentId, 'name': trimmed});+ } catch (error) {+ return 'Rename failed: $error';+ }+ final error = result['error'];+ if (error is String) return 'Rename failed: $error';+ _renameAgent(machine, agentId, trimmed);+ notifyListeners();+ return null;+ }++ /// Deletes an agent via `agent_delete`. Returns null on success, or an error message to show+ /// inline in the caller's dialog.+ Future<String?> deleteAgent(String machineId, String agentId) async {+ final machine = machineStates[machineId];+ if (machine == null) return 'Machine not found';+ Map<String, dynamic> result;+ try {+ result = await _conn(machineId)+ .request('agent_delete', payload: {'agentId': agentId});+ } catch (error) {+ return 'Delete failed: $error';+ }+ final error = result['error'];+ if (error is String) return 'Delete failed: $error';+ await _removeAgent(machine, agentId);+ notifyListeners();+ return null;+ }++ /// Restarts an agent via `agent_restart` — exits its current engine process and relaunches it+ /// daemon-side, resuming its session where possible.+ ///+ /// The reply carries the same fresh `Agent` shape `agent_synced` pushes once the new process is+ /// confirmed, so this upserts from the reply directly — idempotent on `agent.id`, same as+ /// [createAgent], and safe even if the CLI's own `agent_synced` push for the restart arrives+ /// separately (fire-and-forget on the CLI side, unordered relative to this reply).+ Future<RestartAgentResult> restartAgent(+ String machineId,+ String agentId,+ ) async {+ final machine = machineStates[machineId];+ if (machine == null) {+ return const RestartAgentResult(error: 'Machine not found');+ }+ Map<String, dynamic> result;+ try {+ result = await _conn(machineId)+ .request('agent_restart', payload: {'agentId': agentId});+ } catch (error) {+ return RestartAgentResult(error: 'Restart failed: $error');+ }+ final error = result['error'];+ if (error is String) {+ final detail = result['detail'];+ return RestartAgentResult(+ error: detail is String ? detail : 'Restart failed: $error',+ );+ }+ final raw = result['agent'];+ if (raw is Map) {+ try {+ _upsertAgent(machine, Agent.fromJson(Map<String, dynamic>.from(raw)));+ notifyListeners();+ } catch (_) {+ // Malformed reply agent — harmless, the CLI's own agent_synced push still lands.+ }+ }+ // Absent (older daemon build) reads as true — assume resumed rather than warn about a fresh+ // session that may not have happened, since this field is purely additive UI polish.+ final resumed = result['resumed'];+ return RestartAgentResult(resumed: resumed is bool ? resumed : true);+ }++ /// Every tile on the machine, not just the focused one: the machine is what+ /// went away, so a tile of the same machine sitting in another corner of the+ /// grid is just as dead and must say so rather than keep showing a terminal+ /// that can no longer receive anything. Records what was open so the next+ /// `connected` can put it back (`_recoverPendingAgent`).+ void _markSessionsUnreachable(MachineState machine, String message) {+ for (final pane in panesFor(machine.machine.machineId)) {+ final session = pane.session;+ if (session == null) continue;+ machine.activeAgentId ??= session.agentId;+ // A pane someone else already took over must stay frozen until the user retries it+ // themselves (see `_paneNeedsAttach`) — recording it here would have `_recoverPendingAgent`+ // call `selectAgent` on reconnect and silently win it back the moment the connection+ // returns, fighting whichever machine holds it now.+ if (session.status != TerminalSessionStatus.takenOver) {+ machine.pendingOfflineAgentId ??= session.agentId;+ }+ // Do not send terminal_close: the adapter is already gone and the+ // next client attachment should be the only stream that owns the pane.+ session.transportLost(message);+ }+ }++ Future<void> _applyNodeStatus(MachineState machine, bool online) async {+ if (_disposed) return;+ final machineId = machine.machine.machineId;+ final wasOnline = machine.nodeOnline;+ machine.nodeOnline = online;++ if (!online) {+ _markSessionsUnreachable(+ machine,+ machine.isLocalMachine+ ? 'Harness is offline. Run harness login to reconnect.'+ : 'Harness is offline. Run harness start on that machine to reconnect.',+ );+ _startOfflineRetry(machine);+ } else {+ _stopOfflineRetry(machineId);+ if (wasOnline == false) {+ for (final pane in panesFor(machineId)) {+ pane.session?.transportLost(+ 'Harness reconnected; restoring terminal…',+ );+ }+ }+ final pending = machine.pendingOfflineAgentId;+ if (pending != null) {+ unawaited(_recoverPendingAgent(machine, pending));+ } else if (panesFor(machineId).any(_paneNeedsAttach)) {+ // A tile restored from the saved layout has no pendingOfflineAgentId —+ // nothing of its was interrupted, it simply arrived before its machine+ // did. Without this it would sit on "Attaching…" forever on a machine+ // that has since come back, because every other route to _attachSession+ // runs off a load that nothing here would trigger.+ unawaited(_loadMachineData(machine, force: true));+ }+ }+ notifyListeners();+ }++ Future<void> _recoverPendingAgent(+ MachineState machine,+ String agentId,+ ) async {+ final machineId = machine.machine.machineId;+ if (!_offlineRecoveryInFlight.add(machineId)) return;+ try {+ // E2EE and agents_list can become ready in separate frames after a+ // node restart. Poll briefly instead of racing a single request.+ for (var attempt = 0; attempt < 40; attempt++) {+ if (_disposed ||+ machine.nodeOnline != true ||+ machine.pendingOfflineAgentId != agentId) {+ return;+ }+ await _loadMachineData(machine, force: true);+ final agent = machine.agents.cast<Agent?>().firstWhere(+ (candidate) => candidate?.id == agentId,+ orElse: () => null,+ );+ if (agent != null &&+ agent.terminalAvailable &&+ machine.terminalCapabilityAvailable) {+ machine.pendingOfflineAgentId = null;+ // Only reattach the terminal if the user is still on THIS machine — recovery can finish+ // well after the user has moved on to a different machine/agent, and forcing selectAgent+ // here would yank their focus back to what they were looking at before, mid-navigation.+ // The recovered agent still shows normally in the rail; they can click it themselves.+ if (selectedMachineId == machineId) {+ await selectAgent(machineId, agentId);+ } else {+ notifyListeners();+ }+ return;+ }+ await Future<void>.delayed(const Duration(milliseconds: 250));+ }+ } finally {+ _offlineRecoveryInFlight.remove(machineId);+ }+ }++ /// 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.+ Future<void> ensureDeviceFocus(Map<String, dynamic> payload) async {+ final expiresAt = payload['expiresAt'];+ final machineId = payload['machineId'];+ final agentId = payload['agentId'];+ final focusRevision = payload['focusRevision'];+ if (expiresAt is! num ||+ expiresAt <= DateTime.now().millisecondsSinceEpoch ||+ machineId is! String ||+ agentId is! String ||+ agentId.isEmpty ||+ focusRevision is! String ||+ focusRevision.isEmpty) {+ return;+ }+ if (focusedPane?.agentId != null) {+ _announceAppFocus();+ return;+ }+ // Tag only the synchronous fallback announcement, never a later user click.+ late Future<void> selection;+ _deviceFocusRevision = focusRevision;+ try {+ selection = selectAgent(machineId, agentId);+ } finally {+ _deviceFocusRevision = null;+ }+ await selection;+ }++ /// The dial turned to an agent. Ordinary selection, the same path a click on the rail takes.+ ///+ /// It used to take a `DeskEdge` and, for an agent with no tile, replace the pane at that end — the+ /// dial's carousel could walk past the end of the desk onto an unopened agent, and the edge said+ /// which tile it had walked off. The carousel walks only open panes now, so there is no off-desk+ /// landing left to place and nothing to replace.+ Future<void> selectAgentFromDial(String machineId, String agentId) async {+ await selectAgent(machineId, agentId);+ }++ Future<void> selectAgent(String machineId, String agentId) async {+ final existing = paneOfAgent(machineId, agentId);+ if (existing != null) {+ selectedMachineId = machineId;+ machineStates[machineId]?.activeAgentId = agentId;+ focusPane(existing.id);+ final terminal = existing.session;+ if (terminal == null) {+ // The pane wanted this agent before `_attachSession` could actually attach it (the agent's+ // terminal wasn't verified yet, the machine was briefly offline, ...). Nothing else retries a+ // null session on its own — see `_attachPendingPanes` — so a click here has to.+ await _attachSession(existing);+ } else if (terminal.status != TerminalSessionStatus.opening &&+ terminal.status != TerminalSessionStatus.controlling &&+ terminal.status != TerminalSessionStatus.resyncing) {+ if (!_canAttachPane(existing)) return;+ // Retry the dead stream in place so its output and view context remain+ // available until the next keyframe. Healthy panes stay focus-only.+ await terminal.reopen();+ }+ return;+ }+ await addAgentToSwarm(machineId, agentId);+ }++ /// Show a MACHINE in the grid, for the states that belong to the machine+ /// rather than to any agent on it.+ ///+ /// It has to be a tile like any other — the alternative of letting a machine+ /// take over the whole content area would blank three working terminals+ /// belonging to two other machines. The one exception is a machine that+ /// already needs linking: that state now surfaces as a blocking popup+ /// (HomeScreen._maybeShowLinkDialog / showLinkMachineScreenDialog) rather+ /// than a tile, so opening one here too would just be a redundant "not+ /// linked" pane sitting behind it. Selecting is still worth doing — it's+ /// what makes the popup's gate notice this machine — the tile is not.+ void showMachinePane(String machineId) {+ final machine = machineStates[machineId];+ if (machine == null) return;+ _dismissedLinkPrompts.remove(machineId);+ selectedMachineId = machineId;+ if (machine.isRemote && !machine.isLocalMachine && machine.needsLink) {+ notifyListeners();+ return;+ }++ final existing = panes+ .where((pane) => pane.machineId == machineId && pane.agentId == null)+ .firstOrNull;+ if (existing != null) {+ focusPane(existing.id);+ notifyListeners();+ return;+ }++ final target = focusedPane;+ if (target != null && target.agentId == null) {+ target.machineId = machineId;+ focusPane(target.id);+ notifyListeners();+ return;+ }+ if (!canAddPane) return;+ final pane = TerminalPane(id: _nextPaneId++, machineId: machineId);+ panes.add(pane);+ focusPane(pane.id);+ notifyListeners();+ }++ /// Put an agent into a specific tile, or into a NEW tile when [paneId] is+ /// null — which is what a drop on the empty slot means.+ Future<void> assignAgentToPane(+ int? paneId,+ String machineId,+ String agentId, {+ String? swarmId,+ PaneSplitRequest? split,+ }) async {+ final target = swarms+ .where((s) => s.id == (swarmId ?? activeSwarmId))+ .firstOrNull;+ if (target == null || _disposed) return;+ if (split != null &&+ (split.swarmId != target.id ||+ paneId != null ||+ !isPaneSplitCurrent(split))) {+ return;+ }+ final targetPanes = target.panes;+ final machine = machineStates[machineId];+ if (machine == null) return;++ Agent? agent;+ for (final candidate in machine.agents) {+ if (candidate.id == agentId) {+ agent = candidate;+ break;+ }+ }+ if (agent == null) return;++ final shared = allPanes+ .where((p) => p.machineId == machineId && p.agentId == agentId)+ .firstOrNull;+ final existing = targetPanes+ .where((p) => p.machineId == machineId && p.agentId == agentId)+ .firstOrNull;+ if (paneId == null && existing != null) {+ if (target == activeSwarm) focusPane(existing.id);+ return;+ }+ final replaced = targetPanes.where((p) => p.id == paneId).firstOrNull;+ if (replaced == shared && shared != null) {+ if (target == activeSwarm) focusPane(shared.id);+ return;+ }+ if (replaced == null &&+ existing == null &&+ targetPanes.length >= maxPanes) {+ _lastError =+ 'This tab holds $maxPanes harnesses. Open another tab to add more.';+ _lastErrorRetryable = false;+ notifyListeners();+ return;+ }+ final insertion = replaced == null+ ? split == null+ ? targetPanes.length+ : split.paneIds.indexOf(split.paneId) + 1+ : targetPanes.indexOf(replaced);+ if (existing != null) target.remove(existing);+ if (replaced != null) target.remove(replaced);+ final pane =+ shared ??+ TerminalPane(id: _nextPaneId++, machineId: machineId, agentId: agentId);+ final firstAgent = targetPanes.every((pane) => pane.agentId == null);+ targetPanes.insert(insertion.clamp(0, targetPanes.length), pane);+ if (split != null) {+ target.pinnedSlots.updateAll(+ (_, slot) => slot >= insertion ? slot + 1 : slot,+ );+ final key = '${targetPanes.length}:manual';+ target.savePaneSizes(key, split.after);+ target.arranged = split.after;+ target.arrangedKey = key;+ }+ if (firstAgent && target.name == 'New Harness') {+ final name = agent.name.trim();+ if (name.isNotEmpty) {+ target.name = name.length > 80 ? name.substring(0, 80) : name;+ }+ }+ if (replaced != null && !allPanes.contains(replaced)) {+ // Release just the desktop stream. The CLI agent process keeps running.+ unawaited(_detachSession(replaced, sendClose: true));+ }++ target.focusedPaneId = pane.id;+ target.zoomedPaneId = null;+ if (target == activeSwarm) selectedMachineId = machineId;+ _dismissedLinkPrompts.remove(machineId);+ machine.activeAgentId = agentId;+ _persistLayout();+ // SAID OUTRIGHT, like every other move.+ //+ // This path — a rail click on an agent with no tile — was the one that never said it. It relied on+ // the daemon inferring the move from the `terminal_open` that follows, which is the old+ // one-terminal-per-window equivalence [see _announceAppFocus]. Two things wrong with that: the+ // roster below changes the dial's carousel, so the focus and the roster are one transaction and the+ // inference arrives after it by luck; and every early return under here (machine offline, terminal+ // capability missing, a session already attached) opens no stream at all, so nothing was ever sent+ // and the dial stayed on the old agent with the window on the new one.+ //+ // After _persistLayout, so the daemon has the new tile roster before it is told to move onto it. A+ // duplicate with the inferred one is free: the daemon drops the second against where the dial+ // already is.+ if (target == activeSwarm) _announceAppFocus();++ if (machine.nodeOnline == false) {+ machine.pendingOfflineAgentId = agentId;+ _startOfflineRetry(machine);+ notifyListeners();+ return;+ }+ if (!machine.terminalCapabilityAvailable) {+ notifyListeners();+ return;+ }+ machine.pendingOfflineAgentId = null;+ _stopOfflineRetry(machineId);+ notifyListeners();+ if (target == activeSwarm || pane.session != null) {+ await _attachSession(pane);+ }+ }++ /// Open the stream for a tile that already knows what it wants.+ ///+ /// Separate from [assignAgentToPane] because a restored tile takes this path+ /// on its own, later, when its machine finally answers — the intent was+ /// settled at launch, and nothing about the selection should move again then.+ Future<void> _attachSession(TerminalPane pane) async {+ if (_disposed || !allPanes.contains(pane) || pane.session != null) return;+ final wantedAgentId = pane.agentId;+ if (wantedAgentId == null) return;+ final machine = machineStates[pane.machineId];+ if (machine == null) return;+ if (machine.nodeOnline == false) return;+ if (!machine.terminalCapabilityAvailable) return;++ Agent? agent;+ for (final candidate in machine.agents) {+ if (candidate.id == wantedAgentId) {+ agent = candidate;+ break;+ }+ }+ if (agent == null || !agent.terminalAvailable) return;++ final terminal = TerminalSession(+ machineId: pane.machineId,+ agentId: agent.id,+ agentName: agent.name,+ engineId: agent.engine,+ send: (type, payload) =>+ _conn(pane.machineId).sendTerminalFrame(type, payload),+ sendBinary: (frame) => _sendTerminalBinary(pane.machineId, frame),+ onOpenStalled: () => _conn(pane.machineId).forceReconnect(),+ );+ pane.session = terminal;+ terminal.addListener(notifyListeners);+ notifyListeners();+ // Wait for the pane's actual measured viewport before asking the daemon to open anything.+ // Sending the 80x24 fallback here used to make the daemon spawn the remote TTY (and render its+ // first keyframe) at that wrong size, which then had to be corrected by a resize round trip —+ // visible as the terminal's content briefly rendering narrow before snapping to full width. The+ // blank "Attaching…" placeholder already covers this measurement, which lands within a frame or+ // two of the panel mounting; `waitForViewportSize`'s own 2s timeout falls back to 80x24 only if+ // the pane genuinely never gets laid out.+ await terminal.open(waitForViewportSize: true);+ }++ Future<void> _detachSession(+ TerminalPane pane, {+ required bool sendClose,+ }) async {+ final terminal = pane.session;+ pane.session = null;+ if (terminal == null) return;+ terminal.removeListener(notifyListeners);+ if (sendClose) await terminal.close();+ 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();+ }++ /// How many columns the grid last laid out.+ ///+ /// Only `auto` needs telling: it measures the window, so it is the one shape+ /// whose columns are not in its own description. Reported by the grid as it+ /// builds; null until then, and then the shape's own guess stands.+ int? get gridColumns => activeSwarm.gridColumns;+ set gridColumns(int? value) => activeSwarm.gridColumns = value;++ bool hasNavigationRail = true;++ /// Focus the tile above or below the focused one — ⌘↑ / ⌘↓.+ ///+ /// SPATIAL, unlike the left/right pair, which walks the tiles in order. Down+ /// from the top-left of a 2×2 is the tile under it, not the next one along,+ /// because that is what the arrow is pointing at. The shapes are read from+ /// [PanePreset.tilesFor] — the same rectangles the layout is built from and+ /// the picker draws — so this cannot describe a grid the app does not build.+ ///+ /// Nothing above or below (a single row, or the edge) leaves the focus where+ /// it is: an arrow that wraps to the far side of the screen reads as a jump,+ /// not as a step.+ void focusPaneVertically(int delta) {+ final to = _neighbour(dx: 0, dy: delta) ?? _wrapVertically(delta);+ if (to != null) focusPane(panes[to].id);+ }++ /// The tile at the far end of this column — ⌘j off the bottom row, ⌘k off the+ /// top.+ ///+ /// IN COLUMN, not in list order. Wrapping to `panes.first` from the bottom+ /// right of a 2x2 would jump a column as well as a row, which reads as the key+ /// having misfired rather than as having come round. This finds the tile that+ /// still overlaps ours horizontally and sits furthest in the direction pressed+ /// — the one directly above or below, as far as it goes.+ int? _wrapVertically(int delta) {+ final count = panes.length;+ if (count < 2) return null;+ final shape = activeSwarm.arranged?.tiles.length == count+ ? activeSwarm.arranged!.tiles+ : presetFor(count)?.tilesFor(count, columns: gridColumns);+ if (shape == null || shape.length != count) return null;+ final at = panes.indexWhere((pane) => pane.id == focusedPaneId);+ if (at < 0) return null;++ final from = shape[at];+ int? best;+ double bestEdge = 0;+ for (var i = 0; i < count; i++) {+ if (i == at) continue;+ final to = shape[i];+ if ((from.right < to.left + 0.001) || (to.right < from.left + 0.001)) {+ continue;+ }+ // Going DOWN wraps to the topmost; going up, to the bottom-most.+ final edge = delta > 0 ? -to.top : to.top;+ if (best == null || edge > bestEdge) {+ bestEdge = edge;+ best = i;+ }+ }+ return best;+ }++ /// ⌘h / ⌘l, and ⌘← / ⌘→ — the tile beside this one, by POSITION.+ ///+ /// Spatial, like its vertical twin, and that is a change: left and right used+ /// to walk the panes in list order while up and down read the geometry, so+ /// half the compass answered "the next one" and half answered "the one over+ /// there". A vim user pressing `l` means the window to their right, and a+ /// scheme that means it in two directions out of four is one nobody can hold.+ void focusPaneHorizontally(int delta) {+ // THE RAIL IS A SEAT IN THE RING, not a wall at one end of it.+ //+ // No new key for "go to the sidebar": the sidebar is what is to the left of+ // the leftmost tile, so the key that means left already says it — the motion+ // vim users have, where `Ctrl-w h` out of the last split does not stop, it+ // reaches the next thing.+ //+ // And the ring CLOSES. Walking off either edge seats you in the rail, and+ // walking out of the rail continues round to the far side: left out of it+ // lands on the last tile, right onto the first. A ring that stopped dead at+ // one end would make the same key mean "go left" in the middle of the grid+ // and "do nothing" at its edge, which is a key people stop trusting.+ if (railFocused) {+ if (panes.isEmpty) return;+ unfocusRail();+ focusPane(delta < 0 ? panes.last.id : panes.first.id);+ return;+ }+ final to = _neighbour(dx: delta, dy: 0);+ if (to != null) {+ focusPane(panes[to].id);+ return;+ }+ if (hasNavigationRail) focusRail();+ // An EMPTY rail is not a seat, so the ring skips it rather than stopping on+ // it. focusRail refuses when there is nothing to put a cursor on — no+ // machines yet, or a list that has not loaded — and without this the key+ // would simply do nothing at the edge, which is the exact behaviour the ring+ // exists to remove.+ if (!railFocused && panes.isNotEmpty) {+ focusPane(delta < 0 ? panes.last.id : panes.first.id);+ }+ }++ /// ⇧⌘h j k l — put this pane where its neighbour is, and that one here.+ ///+ /// A SWAP, not an insert. vim's `Ctrl-w H/J/K/L` — the capitals this mirrors —+ /// moves a window to the far edge, which needs a tree of splits to mean+ /// anything; this grid is a list of slots rendered into a shape, so the honest+ /// equivalent is to trade places with whoever is in the direction pressed.+ void movePaneDirection({required int dx, required int dy}) {+ final id = focusedPaneId;+ if (id == null) return;+ final at = panes.indexWhere((pane) => pane.id == id);+ final to = _neighbour(dx: dx, dy: dy);+ if (at < 0 || to == null) return;+ final moved = panes.removeAt(at);+ panes.insert(to, moved);+ _persistLayout();+ notifyListeners();+ }++ /// The index of the tile in the given direction, or null at the edge.+ ///+ /// Reads the laid-out RECTANGLES rather than the list, so "left" means left on+ /// screen whatever order the panes happen to be in. The two rules that make it+ /// honest: the neighbour has to actually be on that side (a tile whose edge is+ /// level with ours is not beside us), and the two have to OVERLAP on the other+ /// axis — otherwise the tile diagonally across counts as "down", which is how+ /// a 2x2 ends up with a key that moves like a knight.+ int? _neighbour({required int dx, required int dy}) {+ final count = panes.length;+ if (count < 2) return null;+ final shape = activeSwarm.arranged?.tiles.length == count+ ? activeSwarm.arranged!.tiles+ : presetFor(count)?.tilesFor(count, columns: gridColumns);+ if (shape == null || shape.length != count) return null;+ final at = panes.indexWhere((pane) => pane.id == focusedPaneId);+ if (at < 0) return null;++ final from = shape[at];+ int? best;+ double bestGap = double.infinity;+ for (var i = 0; i < count; i++) {+ if (i == at) continue;+ final to = shape[i];+ final double gap;+ final bool apart;+ if (dy != 0) {+ gap = dy > 0 ? to.top - from.top : from.top - to.top;+ apart =+ (from.right < to.left + 0.001) || (to.right < from.left + 0.001);+ } else {+ gap = dx > 0 ? to.left - from.left : from.left - to.left;+ apart =+ (from.bottom < to.top + 0.001) || (to.bottom < from.top + 0.001);+ }+ if (gap <= 0.001 || apart) continue;+ if (gap < bestGap) {+ bestGap = gap;+ best = i;+ }+ }+ return best;+ }++ /// ⌘; — 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+ /// usually breaks this: focus moving. Zoomed on tile 3 and then jumping to+ /// tile 5 shows tile 5 zoomed, which is what tmux does and what the eye+ /// expects; a boolean would have shown tile 3 while the focus was elsewhere.+ 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+ /// lifting the pinned tile back into its slot leaves that slide intact for+ /// every other tile. A swap would instead fling whichever tile inherited the+ /// slot to the far end of the grid — one close, two tiles moved, and only one+ /// of them explicable.+ ///+ /// A pin past the end of a shrunken grid is HELD, not dropped: the tiles that+ /// 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)!));+ for (final pane in pinned) {+ final want = pinnedSlotFor(pane)!;+ if (want >= panes.length) continue;+ final at = panes.indexOf(pane);+ if (at == want) continue;+ panes.removeAt(at);+ panes.insert(want, pane);+ }+ }++ Future<void> closePane(int paneId, {bool persist = true}) async {+ final pane = panes.where((p) => p.id == paneId).firstOrNull;+ if (pane == null) return;+ if (pane.agentId != null) {+ final machine = stateOf(pane.machineId);+ final agent = machine?.agents+ .where((a) => a.id == pane.agentId)+ .firstOrNull;+ _rememberClosed(+ ClosedAgent(+ pane,+ activeSwarm,+ historyId: 'closed-${_nextClosedHistoryId++}',+ name: agent?.name ?? pane.session?.agentName ?? pane.agentId!,+ machineName: machine?.machine.displayName ?? pane.machineId,+ engine: agent?.engine ?? pane.session?.engineId,+ ),+ );+ }+ // Only a close that moves the focus is worth telling the daemon about: a+ // background tile going away changes nothing the dial can see.+ final wasFocused = focusedPaneId == paneId;+ activeSwarm.remove(pane);+ _settlePins();+ if (persist) _persistLayout();+ selectedMachineId = focusedPane?.machineId;+ if (wasFocused) _announceAppFocus();+ notifyListeners();+ if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);+ }++ Future<void> _closeAllPanes({bool persist = true}) async {+ final open = allPanes.toList();+ for (final swarm in swarms) {+ swarm.panes.clear();+ swarm.focusedPaneId = null;+ swarm.zoomedPaneId = null;+ }+ _announceAppFocus();+ for (final pane in open) {+ await _detachSession(pane, sendClose: true);+ }+ if (persist) _persistLayout();+ }++ int _layoutRevision = 0;++ Future<void> flushPaneLayout() =>+ _paneLayout?.flushSwarms() ?? Future<void>.value();++ void _persistLayout() {+ _draftSwarmReturns.removeWhere((id, _) {+ final swarm = swarms.where((swarm) => swarm.id == id).firstOrNull;+ return swarm == null ||+ swarm.panes.isNotEmpty ||+ swarm.name != 'New Harness' ||+ swarm.presets.isNotEmpty;+ });+ _layoutRevision++;+ _announceOpenPanesToDial();+ final saved = swarms.where((swarm) => !isDraftSwarm(swarm.id)).toList();+ if (saved.isEmpty) return;+ final savedActive = isDraftSwarm(activeSwarmId)+ ? _draftSwarmReturns[activeSwarmId]+ : activeSwarmId;+ unawaited(+ _paneLayout?.saveSwarms(+ saved,+ saved.any((swarm) => swarm.id == savedActive)+ ? savedActive!+ : saved.last.id,+ ),+ );+ }++ /// Rebuild the grid from disk as INTENT only — the tiles appear immediately,+ /// each saying which machine it is waiting for, and attach themselves as+ /// their machines answer.+ ///+ /// The tiles cannot wait for the machines: machines answer in an order this+ /// side does not decide, a restored grid commonly spans two of them, and one+ /// being slow or offline must not hold the others blank.+ Future<void> _restorePaneLayout() async {+ final store = _paneLayout;+ if (store == null) return;+ final initialSwarm = activeSwarm;+ final revision = _layoutRevision;+ final saved = await store.loadSwarms();+ if (_disposed || revision != _layoutRevision) return;+ if (saved != null &&+ allPanes.isEmpty &&+ swarms.length == 1 &&+ activeSwarm == initialSwarm) {+ final restored = <Swarm>[];+ final pool = <String, TerminalPane>{};+ for (final raw in (saved['swarms'] as List).take(maxSwarms)) {+ if (raw is! Map || raw['id'] is! String || raw['panes'] is! List) {+ continue;+ }+ final id = raw['id'] as String;+ if (id.isEmpty || restored.any((s) => s.id == id)) continue;+ final swarm = Swarm(+ id: id,+ name:+ raw['name'] is String && (raw['name'] as String).trim().isNotEmpty+ ? (raw['name'] as String).substring(+ 0,+ (raw['name'] as String).length.clamp(0, 80),+ )+ : 'New Harness',+ );+ for (final item in (raw['panes'] as List).take(maxPanes)) {+ final entry = PaneLayoutEntry.fromJson(item);+ if (entry == null) continue;+ final key = '${entry.machineId}\u0000${entry.agentId}';+ final pane = pool.putIfAbsent(+ key,+ () =>+ TerminalPane(+ id: _nextPaneId++,+ machineId: entry.machineId,+ agentId: entry.agentId,+ )+ ..composerVisible = entry.composerVisible+ ..pinnedSlot = entry.pinnedSlot,+ );+ if (!swarm.panes.contains(pane)) {+ swarm.panes.add(pane);+ if (entry.pinnedSlot != null) {+ swarm.pinnedSlots[pane.id] = entry.pinnedSlot!;+ }+ }+ }+ int? paneAt(Object? index) =>+ index is int && index >= 0 && index < swarm.panes.length+ ? swarm.panes[index].id+ : null;+ swarm.focusedPaneId =+ paneAt(raw['focus']) ?? swarm.panes.firstOrNull?.id;+ swarm.zoomedPaneId = paneAt(raw['zoom']);+ swarm.previousPaneId = paneAt(raw['previousFocus']);+ if (raw['presets'] case final Map presets) {+ for (final e in presets.entries) {+ final count = int.tryParse(e.key.toString());+ final preset = PanePreset.byId(e.value?.toString());+ if (count != null &&+ count >= 2 &&+ count <= maxPanes &&+ preset != null &&+ preset.supportsCount(count)) {+ swarm.presets[count] = preset;+ }+ }+ }+ swarm.paneSizes.addAll(PaneArrangement.readSaved(raw['paneSizes']));+ restored.add(swarm);+ }+ if (restored.isNotEmpty) {+ // Older builds saved multiple unused start pages. Retain the selected+ // one when possible; custom names, presets and real work stay intact.+ final starters = restored.where((swarm) => swarm.isEmptyStarter);+ final starter =+ starters+ .where((swarm) => swarm.id == saved['activeId'])+ .firstOrNull ??+ starters.firstOrNull;+ final hadDuplicateStarters = starters.length > 1;+ if (hadDuplicateStarters) {+ restored.removeWhere(+ (swarm) => swarm.isEmptyStarter && swarm != starter,+ );+ }+ swarms+ ..clear()+ ..addAll(restored);+ _activeSwarmId = restored.any((s) => s.id == saved['activeId'])+ ? saved['activeId'] as String+ : restored.first.id;+ while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {+ _nextSwarmId++;+ }+ _autoPickedAgent = true;+ if (hadDuplicateStarters) _persistLayout();+ notifyListeners();+ return;+ }+ }+ // Read before the guards below: the dividers are remembered even for a+ // grid this run has not restored any agents into, so a window that opens+ // empty and is then filled by hand still comes up the shape it was left.+ final legacyPresets = await store.loadPresets();+ if (_disposed || revision != _layoutRevision) return;+ if (allPanes.isNotEmpty ||+ swarms.length != 1 ||+ activeSwarm != initialSwarm) {+ return;+ }+ final entries = await store.load();+ if (_disposed || revision != _layoutRevision) return;+ panePresets.addAll(legacyPresets);+ if (entries.isEmpty) {+ if (panePresets.isNotEmpty) notifyListeners();+ return;+ }+ for (final entry in entries) {+ panes.add(+ TerminalPane(+ id: _nextPaneId++,+ machineId: entry.machineId,+ agentId: entry.agentId,+ )+ ..composerVisible = entry.composerVisible+ ..pinnedSlot = entry.pinnedSlot,+ );+ }+ // The saved order already puts everything where it was left, so this is+ // only a repair: a layout whose file was hand-edited, or trimmed by the+ // pane ceiling on the way in, can arrive with a pinned tile off its slot.+ _settlePins();+ focusedPaneId = panes.first.id;+ // A restored grid IS the choice of what to open, so the first-run+ // convenience must not also fire and add a fifth agent nobody asked for.+ _autoPickedAgent = true;+ notifyListeners();+ }++ /// Attach any tile of this machine that is still waiting.+ ///+ /// Called after every load rather than once, because the three things+ /// [_attachSession] insists on — the agent exists, it has a tmux terminal,+ /// and the machine's terminal protocol has been negotiated — become true at+ /// different moments, and a machine that goes away and returns has to be able+ /// to re-arrive at them.+ void _attachPendingPanes(MachineState machine, {bool retryExisting = true}) {+ final machineId = machine.machine.machineId;+ for (final pane in allPanes.toList()) {+ if (!panes.contains(pane) && pane.session == null) continue;+ if (pane.machineId != machineId) continue;+ // Navigation may mount a new view; it must never retry a retained stream+ // or discard its output while the machine is unavailable.+ if (!retryExisting && pane.session != null) continue;+ if (!_paneNeedsAttach(pane)) continue;+ // Covers a tile that never attached AND one holding a stream the machine+ // lost. Only the first used to be covered, and the second is why a+ // reconnect left every tile but one frozen on "restoring terminal…":+ // recovery ran off pendingOfflineAgentId, which is a single slot, so it+ // could only ever promise restoration to one of them.+ unawaited(_reattachPane(pane));+ }+ }++ /// Whether this tile is showing something that is not a working terminal.+ ///+ /// `takenOver` is deliberately absent. A stream someone else claimed is only+ /// reopened when a person asks for it — see [selectAgent], which is reached+ /// from the tile's own retry button. Doing it automatically would have two+ /// windows trading one terminal back and forth for as long as both stayed+ /// open.+ bool _paneNeedsAttach(TerminalPane pane) {+ if (pane.agentId == null) return false;+ final session = pane.session;+ if (session == null) return true;+ return switch (session.status) {+ TerminalSessionStatus.error || TerminalSessionStatus.closed => true,+ _ => false,+ };+ }++ /// Reopen a dead stream in its existing session, keeping its rendered output.+ /// An already-lost stream needs no close addressed to its previous owner.+ Future<void> _reattachPane(TerminalPane pane) async {+ if (!_canAttachPane(pane)) return;+ final session = pane.session;+ if (session == null) {+ await _attachSession(pane);+ } else {+ await session.reopen();+ }+ }++ bool _canAttachPane(TerminalPane pane) {+ if (_disposed || !allPanes.contains(pane)) return false;+ final machine = machineStates[pane.machineId];+ return machine != null &&+ machine.nodeOnline != false &&+ machine.terminalCapabilityAvailable &&+ !(machine.isRemote && !machine.isLocalMachine && machine.needsLink) &&+ (!machine.isLocalMachine || machine.usesLocalTransport) &&+ machine.agents.any((a) => a.id == pane.agentId && a.terminalAvailable);+ }++ /// Resolve a dial agent to the machine that owns it.+ ///+ /// New CLIs state the machine explicitly. Older CLIs only sent an agent id;+ /// that is safe to retain only when the current snapshots contain exactly+ /// one matching machine. The websocket carrying the event is always the+ /// local daemon and is therefore not evidence that the agent is local.+ String? _dialFocusMachine(Map<String, dynamic> payload, String agentId) {+ final explicitMachineId = payload['machineId'];+ if (explicitMachineId is String && explicitMachineId.isNotEmpty) {+ final state = machineStates[explicitMachineId];+ if (state == null ||+ !state.agents.any((candidate) => candidate.id == agentId)) {+ return null;+ }+ return explicitMachineId;+ }++ String? match;+ for (final entry in machineStates.entries) {+ if (!entry.value.agents.any((candidate) => candidate.id == agentId)) {+ continue;+ }+ if (match != null) return null; // Ambiguous legacy event: do not guess.+ match = entry.key;+ }+ return match;+ }++ Future<void> _handleEvent(+ String machineId,+ Map<String, dynamic> event,+ ) async {+ final machine = machineStates[machineId];+ if (machine == null) return;+ final type = event['type'] as String? ?? '';+ final payload = (event['payload'] as Map<String, dynamic>?) ?? {};+ // Only terminal protocol frames visit the session pool. Heartbeats, dial+ // scroll and discovery events must not await every retained terminal.+ // Each session still sees terminal frames: ready replies match their own+ // request/agent, while transport errors must reach the whole machine.+ if (type.startsWith('terminal_')) {+ for (final pane in panesFor(machineId).toList()) {+ await pane.session?.handleFrame(type, payload);+ }+ return;+ }+ switch (type) {+ // ── the dial, over the cable, forwarded by the local daemon ──────────────────────────────────+ // Local-only frames (backend.sendLocal in the harness CLI): they describe a hand at THIS desk, so+ // they never reach the cloud web audience, who may be sitting at another computer entirely.+ case 'dial_status':+ // The dial came, went, or started taking an update. Its own notifier —+ // see [dial] — so nothing else in the window rebuilds for it.+ dial.apply(DialStatus.fromJson(payload));+ return;+ case 'dial_scroll':+ // Straight through, including the reports carrying no travel — the ends of a stroke are the point+ // of the message. The window does no arithmetic here; the terminal that owns the scrollback does.+ final phase = switch (payload['phase']) {+ 'down' => 0,+ 'up' => 2,+ _ => 1,+ };+ activeTerminal?.scroll(+ phase,+ (payload['dy'] as num?)?.round() ?? 0,+ (payload['velocity'] as num?)?.round() ?? 0,+ );+ return;+ case 'device_focus':+ unawaited(ensureDeviceFocus(payload));+ break;+ case 'dial_focus':+ // Turning the dial to an agent brings that agent's terminal up here — the ordinary selection+ // path, the same one a click on the rail takes, failing the same way for a missing terminal,+ // an offline machine or an unknown id.+ //+ // It used to carry an `edge` for an agent with no tile, naming which end of the desk the+ // carousel had walked off so a tile could be replaced there. The carousel walks only open+ // panes now, so every focus it sends is about a pane that already exists.+ final agentId = payload['agentId'];+ if (agentId is String && agentId.isNotEmpty) {+ final targetMachineId = _dialFocusMachine(payload, agentId);+ if (targetMachineId != null) {+ unawaited(selectAgentFromDial(targetMachineId, agentId));+ }+ }+ 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+ // line follow from that — nothing is answered to the dial directly.+ 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 'node_status':+ final online = payload['online'] == true;+ await _applyNodeStatus(machine, online);+ break;+ case 'machine_select_error':+ _lastError =+ 'Machine selection failed: ${payload['error'] ?? 'unknown error'}';+ _lastErrorRetryable = true;+ machine.connectionStatus = ConnectionStatus.disconnected;+ break;+ case 'agent_synced':+ final raw = payload['agent'];+ if (raw is Map) {+ try {+ final agent = Agent.fromJson(Map<String, dynamic>.from(raw));+ if (agent.terminalAvailable) {+ _upsertAgent(machine, agent);+ // A pane created before this agent's terminal was verified is still sitting on+ // "Attaching…" with no session — nothing else re-checks it once agentLoadStatus is+ // already `loaded`, so this push is the only signal that it can attach now.+ _attachPendingPanes(machine);+ } else {+ await _removeAgent(machine, agent.id);+ }+ } catch (_) {+ unawaited(_loadMachineData(machine, force: true));+ }+ } else {+ unawaited(_loadMachineData(machine, force: true));+ }+ break;+ case 'agent_created':+ final raw = payload['agent'];+ if (raw is Map && raw['terminal'] is Map) {+ try {+ final agent = Agent.fromJson(Map<String, dynamic>.from(raw));+ _upsertAgent(machine, agent);+ // Same reattach as `agent_synced` above — a pane can be waiting on this exact agent+ // (e.g. one this window's own New Agent dialog just opened) with no session yet.+ _attachPendingPanes(machine);+ } catch (_) {+ unawaited(_loadMachineData(machine, force: true));+ }+ } else {+ unawaited(_loadMachineData(machine, force: true));+ }+ break;+ case 'agent_renamed':+ final agentId = _eventAgentId(machine, event, payload);+ final name = payload['name'];+ if (agentId != null && name is String) {+ _renameAgent(machine, agentId, name);+ } else {+ unawaited(_loadMachineData(machine, force: true));+ }+ break;+ case 'agent_deleted':+ final agentId = _eventAgentId(machine, event, payload);+ if (agentId != null) {+ await _removeAgent(machine, agentId);+ } else {+ unawaited(_loadMachineData(machine, force: true));+ }+ break;+ // An agent stopped and is waiting on the person. Ignored by this window+ // until now, even though the daemon had already shaped the question for+ // the dial — `sendCommander` is device-only, so it never came down this+ // wire at all.+ case 'commander_question':+ final agentId = _eventAgentId(machine, event, payload);+ if (agentId != null) {+ final asked = PendingQuestion.fromPayload(+ machineId: machineId,+ agentId: agentId,+ payload: payload,+ now: DateTime.now(),+ );+ if (asked != null) {+ // The daemon re-announces an open question after a reconnect, and+ // on attaching to a turn that was already mid-dialog. Keep the+ // original clock in that case: this is the same wait continuing,+ // and restarting it would make a long block look new.+ final known = machine.blockedAgents[agentId];+ machine.blockedAgents[agentId] =+ known != null && known.sameAs(asked)+ ? asked.withSince(known.since)+ : asked;+ }+ }+ break;+ // It stopped being on screen — answered here, in the pane by hand, on+ // another window, or on the dial. Whoever got there first, everyone else+ // is told to stop drawing it.+ case 'commander_question_close':+ final agentId = _eventAgentId(machine, event, payload);+ final requestId = payload['requestId'];+ if (agentId != null) {+ final open = machine.blockedAgents[agentId];+ // Only if it is the one being closed: a stale close must not wipe the+ // question that replaced it when a dialog advanced to its next page.+ if (open != null &&+ (requestId is! String ||+ requestId.isEmpty ||+ open.requestId == requestId)) {+ machine.blockedAgents.remove(agentId);+ }+ }+ break;+ case 'turn_started':+ case 'turn_heartbeat':+ // A turn that STARTS is somebody sending something; a heartbeat is a+ // turn already under way, which for an agent this app merely reconnected+ // to is work nobody here just asked for.+ if (type == 'turn_started') _reportFirstMessage();+ var changed = false;+ final agentId = _eventAgentId(machine, event, payload);+ if (agentId != null) {+ changed = _markAgentProcessing(machine, agentId);+ // Only a START opens a stats turn, for the reason above: a heartbeat+ // is a turn already under way, and counting one would report an agent+ // this app merely reconnected to as work somebody just asked for.+ if (type == 'turn_started') {+ harnessStats.onTurnStarted(+ _turnActivityKey(machine.machine.machineId, agentId),+ );+ }+ } else {+ final sessionId = _eventSessionId(event, payload);+ if (sessionId != null) {+ changed = machine.pendingProcessingSessions.add(sessionId);+ }+ }+ // Renew the watchdog on every heartbeat, but redraw only when the+ // agent first becomes busy. Expiry and turn end publish separately.+ if (!changed) return;+ break;+ case 'turn_ended':+ final agentId = _eventAgentId(machine, event, payload);+ if (agentId != null) {+ _cancelTurnActivity(machine.machine.machineId, agentId);+ } else {+ final sessionId = _eventSessionId(event, payload);+ if (sessionId != null) {+ machine.pendingProcessingSessions.remove(sessionId);+ }+ }+ break;+ }+ notifyListeners();+ }++ /// Feed one machine event straight into the dispatcher.+ ///+ /// The frames worth testing here have no terminal to route through and no+ /// socket to arrive on — what they exercise is the bookkeeping either side of+ /// that, which is exactly what a live socket makes hard to reach.+ @visibleForTesting+ Future<void> restorePaneLayoutForTest() => _restorePaneLayout();++ @visibleForTesting+ Future<void> handleMachineEventForTest(+ String machineId,+ Map<String, dynamic> event,+ ) => _handleEvent(machineId, event);++ @visibleForTesting+ Future<void> handleTerminalBinaryForTest(String machineId, Uint8List frame) =>+ _handleTerminalBinary(machineId, frame);++ /// Put an already-built session on the grid.+ ///+ /// The seam tests used to get from assigning `activeTerminal` directly, which+ /// a grid cannot offer: a session on screen is a session in a TILE, and the+ /// tile is what every lifecycle path — a machine going offline, an agent+ /// being deleted, a frame arriving — actually looks for.+ @visibleForTesting+ TerminalPane adoptSessionForTest(TerminalSession session) {+ final pane = TerminalPane(+ id: _nextPaneId++,+ machineId: session.machineId,+ agentId: session.agentId,+ )..session = session;+ panes.add(pane);+ focusedPaneId = pane.id;+ session.addListener(notifyListeners);+ return pane;+ }++ @visibleForTesting+ Future<void> handleEventForTest(+ String machineId,+ Map<String, dynamic> event,+ ) => _handleEvent(machineId, event);++ /// What the local CLI closing this machine's socket with [code] does to the+ /// model — the `WsPool.onLocalFailure` path, without a socket.+ @visibleForTesting+ void localFailureForTest(String machineId, int code, String reason) =>+ _onLocalFailure(machineId, code, reason);++ @override+ void dispose() {+ _localGitProjects.dispose();+ _disposed = true;+ if (signingIn) cliLogin.cancel();+ _closedHistory.clear();+ _daemonSupervisionTimer?.cancel();+ _updateCheckTimer?.cancel();+ _environmentRecheckTimer?.cancel();+ _stopAllOfflineRetries();+ _stopAllLinkRetries();+ _stopAllAgentSyncTimers();+ _clearAllTurnActivity();+ for (final pane in allPanes) {+ pane.session?.removeListener(notifyListeners);+ pane.session?.dispose();+ }+ for (final swarm in swarms) {+ swarm.panes.clear();+ }+ unawaited(_spokenTasks.close());+ super.dispose();+ }+}++final appStateProvider = Provider<AppNotifier>((ref) {+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: ConfigStore(),+ paneLayoutStore: PaneLayoutStore(),+ );+ app.bootstrap();+ return app;+});diff --git a/mobile/lib/state/dial_status.dart b/mobile/lib/state/dial_status.dartnew file mode 100644index 000000000..d9ddca689--- /dev/null+++ b/mobile/lib/state/dial_status.dart@@ -0,0 +1,76 @@+import 'package:flutter/foundation.dart';++import '../core/local_key_value_store.dart';++/// The dial on this desk, as the daemon last reported it over the local socket.+///+/// Three facts and nothing else: whether it is plugged in, which firmware it greeted with, and whether+/// an update is going over the cable right now. The daemon sends `dial_status` on every change and+/// once more the moment this window connects, so a window opened after the dial was plugged in is not+/// left believing there is none.+class DialStatus {+ const DialStatus({required this.attached, this.fw, this.updating});++ static const none = DialStatus(attached: false);++ final bool attached;++ /// The version it greeted with. Null until the first greeting — a dial can be on the wire before it+ /// has said which image it runs.+ final String? fw;++ /// The version on its way over the cable, or null. The one state that deserves its own word in the+ /// window, because it is the minute in which people unplug the thing.+ final String? updating;++ /// Read with `is`, never `as`: this crosses a socket, so its shape belongs to the other end.+ static DialStatus fromJson(Map<String, dynamic> json) => DialStatus(+ attached: json['attached'] == true,+ fw: json['fw'] is String && (json['fw'] as String).isNotEmpty+ ? json['fw'] as String+ : null,+ updating:+ json['updating'] is String && (json['updating'] as String).isNotEmpty+ ? json['updating'] as String+ : null,+ );+}++/// What the rail's device row needs: the live status, plus one remembered bit — has a dial EVER been+/// seen on this computer?+///+/// That bit is what separates "no device" from "unplugged". A person who has never owned one is+/// shown the way to get one; a person whose dial is in a drawer is told it is unplugged, and is not+/// sold a second one every time they look at the rail. It persists, because the drawer outlives the+/// app's process.+class DialState extends ChangeNotifier {+ DialState([this._storage]);++ static const _seenKey = 'dial_seen';++ final LocalKeyValueStore? _storage;++ 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) {+ seen = true;+ // Never awaited: a write that fails costs one wrong word in the rail on the next launch, which+ // is a far smaller wrong than an exception thrown out of a socket frame.+ _storage?.write(_seenKey, '1').catchError((_) {});+ }+ notifyListeners();+ }+}diff --git a/mobile/lib/state/pane_arrangement.dart b/mobile/lib/state/pane_arrangement.dartnew file mode 100644index 000000000..ab9ca8c4f--- /dev/null+++ b/mobile/lib/state/pane_arrangement.dart@@ -0,0 +1,342 @@+import 'dart:math' as math;+import 'dart:ui';++enum PaneResizeAxis { x, y }++/// Normalized rectangles preserve the preset's topology while its dividers+/// move. They describe slots, not sessions, so moving agents keeps their sizes.+class PaneArrangement {+ PaneArrangement(Iterable<Rect> tiles) : tiles = List.unmodifiable(tiles);+ final List<Rect> tiles;+ static const _epsilon = 0.000001;++ late final List<PaneDivider> dividers = _findDividers();++ PaneArrangement? split(+ int index,+ PaneResizeAxis axis, {+ required Size minimum,+ }) {+ if (index < 0 || index >= tiles.length || tiles.length >= 64) return null;+ final tile = tiles[index];+ final x = axis == PaneResizeAxis.x;+ if (x ? tile.width / 2 < minimum.width : tile.height / 2 < minimum.height) {+ return null;+ }+ final first = x+ ? Rect.fromLTRB(tile.left, tile.top, tile.center.dx, tile.bottom)+ : Rect.fromLTRB(tile.left, tile.top, tile.right, tile.center.dy);+ final second = x+ ? Rect.fromLTRB(tile.center.dx, tile.top, tile.right, tile.bottom)+ : Rect.fromLTRB(tile.left, tile.center.dy, tile.right, tile.bottom);+ return PaneArrangement([+ ...tiles.take(index),+ first,+ second,+ ...tiles.skip(index + 1),+ ]);+ }++ /// Expand a complete neighboring edge into a removed slot. This preserves+ /// the other cuts, including nested splits. An unsupported shape falls back+ /// to the count's preset instead of leaving a hole or overlapping terminals.+ PaneArrangement? remove(int index) {+ if (index < 0 || index >= tiles.length || tiles.length < 2) return null;+ final removed = tiles[index];+ for (final axis in PaneResizeAxis.values) {+ final x = axis == PaneResizeAxis.x;+ final start = x ? removed.top : removed.left;+ final end = x ? removed.bottom : removed.right;+ for (final before in [true, false]) {+ final at = x+ ? (before ? removed.left : removed.right)+ : (before ? removed.top : removed.bottom);+ final neighbors = [+ for (var i = 0; i < tiles.length; i++)+ if (i != index &&+ _touches(tiles[i], axis, at, start, end, before: before))+ i,+ ];+ neighbors.sort(+ (a, b) => (x ? tiles[a].top : tiles[a].left).compareTo(+ x ? tiles[b].top : tiles[b].left,+ ),+ );+ var cursor = start;+ var covers = neighbors.isNotEmpty;+ for (final i in neighbors) {+ final tile = tiles[i];+ final from = x ? tile.top : tile.left;+ final to = x ? tile.bottom : tile.right;+ if ((from - cursor).abs() > _epsilon || to > end + _epsilon) {+ covers = false;+ break;+ }+ cursor = to;+ }+ if (!covers || (cursor - end).abs() > _epsilon) continue;+ final moving = neighbors.toSet();+ return PaneArrangement([+ for (var i = 0; i < tiles.length; i++)+ if (i != index)+ if (!moving.contains(i))+ tiles[i]+ else+ Rect.fromLTRB(+ x && !before ? removed.left : tiles[i].left,+ !x && !before ? removed.top : tiles[i].top,+ x && before ? removed.right : tiles[i].right,+ !x && before ? removed.bottom : tiles[i].bottom,+ ),+ ]);+ }+ }+ return null;+ }++ List<PaneDivider> _findDividers() {+ final segments =+ <({PaneResizeAxis axis, double at, double start, double end})>[];+ for (final a in tiles) {+ for (final b in tiles) {+ final top = math.max(a.top, b.top);+ final bottom = math.min(a.bottom, b.bottom);+ if ((a.right - b.left).abs() < _epsilon && bottom - top > _epsilon) {+ segments.add((+ axis: PaneResizeAxis.x,+ at: a.right,+ start: top,+ end: bottom,+ ));+ }+ final left = math.max(a.left, b.left);+ final right = math.min(a.right, b.right);+ if ((a.bottom - b.top).abs() < _epsilon && right - left > _epsilon) {+ segments.add((+ axis: PaneResizeAxis.y,+ at: a.bottom,+ start: left,+ end: right,+ ));+ }+ }+ }+ segments.sort((a, b) {+ final axis = a.axis.index.compareTo(b.axis.index);+ if (axis != 0) return axis;+ final at = a.at.compareTo(b.at);+ return at != 0 ? at : a.start.compareTo(b.start);+ });+ final merged =+ <({PaneResizeAxis axis, double at, double start, double end})>[];+ for (final segment in segments) {+ if (merged.isNotEmpty) {+ final previous = merged.last;+ if (segment.axis == previous.axis &&+ (segment.at - previous.at).abs() < _epsilon &&+ segment.start <= previous.end + _epsilon) {+ merged[merged.length - 1] = (+ axis: previous.axis,+ at: previous.at,+ start: previous.start,+ end: math.max(previous.end, segment.end),+ );+ continue;+ }+ }+ merged.add(segment);+ }+ return List.unmodifiable([+ for (final segment in merged)+ PaneDivider(+ axis: segment.axis,+ position: segment.at,+ start: segment.start,+ end: segment.end,+ before: [+ for (var i = 0; i < tiles.length; i++)+ if (_touches(+ tiles[i],+ segment.axis,+ segment.at,+ segment.start,+ segment.end,+ before: true,+ ))+ i,+ ],+ after: [+ for (var i = 0; i < tiles.length; i++)+ if (_touches(+ tiles[i],+ segment.axis,+ segment.at,+ segment.start,+ segment.end,+ before: false,+ ))+ i,+ ],+ ),+ ]);+ }++ static bool _touches(+ Rect tile,+ PaneResizeAxis axis,+ double at,+ double start,+ double end, {+ required bool before,+ }) {+ final edge = axis == PaneResizeAxis.x+ ? before+ ? tile.right+ : tile.left+ : before+ ? tile.bottom+ : tile.top;+ final from = axis == PaneResizeAxis.x ? tile.top : tile.left;+ final to = axis == PaneResizeAxis.x ? tile.bottom : tile.right;+ return (edge - at).abs() < _epsilon &&+ math.min(end, to) - math.max(start, from) > _epsilon;+ }++ PaneArrangement resize(+ PaneDivider divider,+ double position, {+ required Size minimum,+ }) {+ if (!position.isFinite || divider.before.isEmpty || divider.after.isEmpty) {+ return this;+ }+ final horizontal = divider.axis == PaneResizeAxis.x;+ final floor = horizontal ? minimum.width : minimum.height;+ if (!floor.isFinite || floor < 0) return this;+ // A deliberately dense preset may already be below the normal floor.+ // Resizing can improve that tile, but cannot make it smaller than it was.+ final lower = divider.before+ .map((i) {+ final tile = tiles[i];+ return horizontal+ ? tile.left + math.min(floor, tile.width)+ : tile.top + math.min(floor, tile.height);+ })+ .reduce(math.max);+ final upper = divider.after+ .map((i) {+ final tile = tiles[i];+ return horizontal+ ? tile.right - math.min(floor, tile.width)+ : tile.bottom - math.min(floor, tile.height);+ })+ .reduce(math.min);+ if (lower > upper + _epsilon) return this;+ final next = position.clamp(lower, math.max(lower, upper)).toDouble();+ if ((next - divider.position).abs() < _epsilon) return this;+ final before = divider.before.toSet(), after = divider.after.toSet();+ return PaneArrangement([+ for (var i = 0; i < tiles.length; i++)+ Rect.fromLTRB(+ horizontal && after.contains(i) ? next : tiles[i].left,+ !horizontal && after.contains(i) ? next : tiles[i].top,+ horizontal && before.contains(i) ? next : tiles[i].right,+ !horizontal && before.contains(i) ? next : tiles[i].bottom,+ ),+ ]);+ }++ double balancedPosition(PaneDivider divider) {+ final x = divider.axis == PaneResizeAxis.x;+ final start = divider.before+ .map((i) => x ? tiles[i].left : tiles[i].top)+ .reduce(math.max);+ final end = divider.after+ .map((i) => x ? tiles[i].right : tiles[i].bottom)+ .reduce(math.min);+ return (start + end) / 2;+ }++ List<List<double>> toJson() => [+ for (final tile in tiles) [tile.left, tile.top, tile.right, tile.bottom],+ ];++ static PaneArrangement? fromJson(Object? value) {+ if (value is! List || value.length < 2 || value.length > 64) return null;+ final tiles = <Rect>[];+ for (final item in value) {+ if (item is! List ||+ item.length != 4 ||+ item.any((v) => v is! num || !v.isFinite || v < 0 || v > 1)) {+ return null;+ }+ final numbers = item.cast<num>().map((v) => v.toDouble()).toList();+ final rect = Rect.fromLTRB(+ numbers[0],+ numbers[1],+ numbers[2],+ numbers[3],+ );+ if (rect.width < _epsilon ||+ rect.height < _epsilon ||+ tiles.any((tile) {+ final overlap = tile.intersect(rect);+ return overlap.width > _epsilon && overlap.height > _epsilon;+ })) {+ return null;+ }+ tiles.add(rect);+ }+ return PaneArrangement(tiles);+ }++ static Map<String, PaneArrangement> readSaved(Object? value) {+ if (value is! Map) return {};+ final result = <String, PaneArrangement>{};+ for (final entry in value.entries.take(64)) {+ final key = entry.key;+ if (key is! String || key.length > 80) continue;+ final count = int.tryParse(key.split(':').first);+ final arrangement = fromJson(entry.value);+ if (arrangement != null && count == arrangement.tiles.length) {+ result[key] = arrangement;+ }+ }+ return result;+ }+}++/// Captured before a creation dialog/network request. Completion must still+/// match these slots; it can never split whichever agent is focused later.+class PaneSplitRequest {+ PaneSplitRequest({+ required this.swarmId,+ required this.paneId,+ required this.axis,+ required Iterable<int> paneIds,+ required this.before,+ required this.after,+ }) : paneIds = List.unmodifiable(paneIds);+ final String swarmId;+ final int paneId;+ final PaneResizeAxis axis;+ final List<int> paneIds;+ final PaneArrangement before, after;+}++class PaneDivider {+ PaneDivider({+ required this.axis,+ required this.position,+ required this.start,+ required this.end,+ required List<int> before,+ required List<int> after,+ }) : before = List.unmodifiable(before),+ after = List.unmodifiable(after);+ final PaneResizeAxis axis;+ final double position, start, end;+ final List<int> before, after;+ String get id => '${axis.name}:${before.join(',')}:${after.join(',')}';+ bool touches(int tile) => before.contains(tile) || after.contains(tile);+}diff --git a/mobile/lib/state/pane_layout_store.dart b/mobile/lib/state/pane_layout_store.dartnew file mode 100644index 000000000..d4ae5bcc7--- /dev/null+++ b/mobile/lib/state/pane_layout_store.dart@@ -0,0 +1,187 @@+import 'dart:async';+import 'dart:convert';++import '../core/harness_file_store.dart';+import '../core/local_key_value_store.dart';+import 'pane_preset.dart';+import 'terminal_pane.dart';+import 'swarm.dart';++/// Remembers which agents were on screen, so reopening the app returns to the+/// desk it was left on rather than to whatever happens to load first.+///+/// Only the intent is stored — machine and agent ids. Sizes, sessions and+/// stream ids are all facts about a particular run and would be lies by the+/// next one.+class PaneLayoutStore {+ PaneLayoutStore({LocalKeyValueStore? storage})+ : _storage = storage ?? HarnessFileStore.shared;++ static const _key = 'terminal_pane_layout';++ /// Chosen shapes, by tile count. A SECOND key rather than a field on the+ /// layout entries: the two answer different questions — which agents were+ /// open, and what shape the grid was in — and the entry schema above already+ /// refuses anything it does not recognise, so widening it would make an old+ /// build drop a new build's whole layout rather than just the part it cannot+ /// use.+ ///+ /// A third key, `terminal_pane_splits`, is written by older builds and no+ /// longer read: dividers were draggable and their positions were remembered.+ /// Nothing deletes it — a downgrade would want it back, and a few hundred+ /// bytes of dead JSON costs less than a file this build has to migrate.+ static const _presetsKey = 'terminal_pane_presets';++ /// The ceiling on tiles, enforced on the way IN as well as out: a file written+ /// by a future build that allows more must not make this one try to open+ /// terminals it has nowhere to put.+ ///+ /// Nine, because ⌘1–⌘9 already addresses that many and a tenth would have no+ /// key. It is a CEILING, not a target — how many actually fit is decided by+ /// the window, since every terminal has a floor of 40 columns and 12 rows+ /// that both this app and the daemon enforce. On a 1280px window with the+ /// rail open that is about three columns; on a 2560px display, six.+ static const maxPanes = 9;++ final LocalKeyValueStore _storage;+ LocalKeyValueStore get storage => _storage;+ String? _pendingSwarmSnapshot;+ Completer<void>? _swarmSave;++ Future<void> flushSwarms() => _swarmSave?.future ?? Future<void>.value();++ /// Failure is silent and lands on an empty layout, which is exactly the+ /// first-run state. A corrupt state file is a reason to open the app the way+ /// a new user sees it, not a reason to refuse to start.+ Future<List<PaneLayoutEntry>> load() async {+ try {+ final raw = await _storage.read(_key);+ if (raw == null || raw.isEmpty) return const [];+ final decoded = jsonDecode(raw);+ if (decoded is! List) return const [];+ final entries = <PaneLayoutEntry>[];+ for (final item in decoded) {+ final entry = PaneLayoutEntry.fromJson(item);+ // One agent cannot be in two tiles: the daemon keeps a single+ // controller per agent, so a duplicate would take its own twin over the+ // moment both opened. Dropping it here means a hand-edited or+ // downgraded file cannot produce that fight.+ if (entry == null ||+ entries.any(+ (existing) =>+ existing.machineId == entry.machineId &&+ existing.agentId == entry.agentId,+ )) {+ continue;+ }+ entries.add(entry);+ if (entries.length == maxPanes) break;+ }+ return entries;+ } catch (_) {+ return const [];+ }+ }++ /// A failed write costs the layout at the next launch, which is a far smaller+ /// wrong than an exception thrown out of a pane close.++ /// Chosen shapes, by tile count. An id this build does not know is dropped —+ /// a shape it cannot draw is worse than the default it can.+ Future<Map<int, PanePreset>> loadPresets() async {+ try {+ final raw = await _storage.read(_presetsKey);+ if (raw == null || raw.isEmpty) return const {};+ final decoded = jsonDecode(raw);+ if (decoded is! Map) return const {};+ final out = <int, PanePreset>{};+ for (final entry in decoded.entries) {+ final count = int.tryParse(entry.key.toString());+ if (count == null || count < 2 || count > maxPanes) continue;+ final preset = PanePreset.byId(entry.value?.toString());+ if (preset == null) continue;+ if (!preset.supportsCount(count)) continue;+ out[count] = preset;+ }+ return out;+ } catch (_) {+ return const {};+ }+ }++ Future<void> savePresets(Map<int, PanePreset> presets) async {+ try {+ await _storage.write(+ _presetsKey,+ jsonEncode({+ for (final entry in presets.entries) '${entry.key}': entry.value.id,+ }),+ );+ } catch (_) {+ // Kept in memory for this run; see above.+ }+ }++ Future<Map<String, dynamic>?> loadSwarms() async {+ try {+ final value = await _storage.read('swarm_layout_v1');+ if (value == null) return null;+ final decoded = jsonDecode(value);+ if (decoded is! Map<String, dynamic> ||+ decoded['version'] != 1 ||+ decoded['swarms'] is! List) {+ return null;+ }+ return decoded;+ } catch (_) {+ return null;+ }+ }++ Future<void> saveSwarms(List<Swarm> swarms, String activeId) {+ // Capture each request before yielding, but keep only the latest snapshot+ // while a write is pending. Holding a navigation key must not queue a full+ // state-file rewrite for every intermediate focus or tab selection.+ try {+ _pendingSwarmSnapshot = jsonEncode({+ 'version': 1,+ 'activeId': activeId,+ 'swarms': swarms.map((s) => s.toJson()).toList(),+ });+ } catch (_) {+ return Future<void>.value();+ }+ final active = _swarmSave;+ if (active != null) return active.future;+ final completion = Completer<void>();+ _swarmSave = completion;+ unawaited(_drainSwarmSnapshots(completion));+ return completion.future;+ }++ Future<void> _drainSwarmSnapshots(Completer<void> completion) async {+ while (_pendingSwarmSnapshot != null) {+ final snapshot = _pendingSwarmSnapshot!;+ _pendingSwarmSnapshot = null;+ try {+ await _storage.write('swarm_layout_v1', snapshot);+ } catch (_) {+ // Keep the current desk usable when storage is unavailable. A newer+ // queued snapshot still gets its own attempt.+ }+ }+ // Clear synchronously before completing: a save requested by a completion+ // listener must start a fresh drain rather than join an already-ended one.+ _swarmSave = null;+ completion.complete();+ }++ Future<void> save(List<PaneLayoutEntry> entries) async {+ try {+ final capped = entries.take(maxPanes).map((e) => e.toJson()).toList();+ await _storage.write(_key, jsonEncode(capped));+ } catch (_) {+ // Kept in memory for this run; see above.+ }+ }+}diff --git a/mobile/lib/state/pane_preset.dart b/mobile/lib/state/pane_preset.dartnew file mode 100644index 000000000..668a4c0cf--- /dev/null+++ b/mobile/lib/state/pane_preset.dart@@ -0,0 +1,389 @@+import 'dart:ui' show Rect;++/// The named shapes a grid of tiles can take.+///+/// The picker offers concrete, distinct arrangements. Automatic and older+/// lattice presets still restore saved work, but are not duplicate cards in+/// the picker. New balanced grids fill every row and use all the canvas.+enum PanePreset {+ /// Two tiles: split whichever side is longer. A terminal's usable size is its+ /// column count first, so halving the short axis is what protects it.+ splitLong,++ /// Two tiles, side by side whatever the window's shape.+ columns,++ /// Two tiles, one above the other.+ rows,++ /// Three tiles: two over one, the bottom one spanning. The shipped shape.+ twoOverOne,++ /// Three tiles: one over two, the top one spanning.+ oneOverTwo,++ /// Three tiles: one tall on the left, two stacked on the right.+ mainLeft,++ /// As many columns as the window can carry at the 40-column floor. The+ /// measured answer, and the one a grid gets when nobody has chosen.+ auto,++ /// A stated column count, for any number of tiles. The rows fall out of it:+ /// seven tiles in three columns is three rows, the last one short.+ ///+ /// Narrow counts are allowed to be narrow — three terminals across a 1600px+ /// window with the rail open is close to the floor — because the floor itself+ /// already refuses anything narrower than a terminal can use, and clamps.+ cols2,+ cols3,+ cols4,+ cols5,++ /// Five tiles: one tall down the MIDDLE, two stacked either side of it.+ ///+ /// The only five-tile shape that is not a lattice, and the reason to have it:+ /// a lattice of five leaves the odd tile alone on a short row, while this+ /// gives the work in hand a full-height column and keeps four others in+ /// sight beside it.+ middleMain,++ /// Four tiles in a square.+ quad,++ /// Four tiles: one tall on the left, three stacked on the right.+ mainAndStack,++ /// Three tiles: two on the left and one full-height on the right.+ mainRight,++ /// Five tiles: two above three, with both rows filling the width.+ twoOverThree,++ /// Row counts follow the requested maximum columns; panes are distributed+ /// evenly between rows so there are no unused cells or sparse trailing rows.+ balanced2,+ balanced3,+ balanced4,+ balanced5,++ /// A full-height main pane beside a balanced grid of supporting panes.+ mainAndGrid,++ /// A full-width main pane above a balanced grid of supporting panes.+ mainOverGrid;++ /// What the picker prints.+ String get label => switch (this) {+ PanePreset.splitLong => 'Split',+ PanePreset.columns => 'Columns',+ PanePreset.rows => 'Rows',+ PanePreset.twoOverOne => 'Main bottom',+ PanePreset.oneOverTwo => 'Main top',+ PanePreset.mainLeft => 'Main left',+ PanePreset.quad => 'Grid',+ PanePreset.mainAndStack => 'Main left',+ PanePreset.auto => 'Auto',+ PanePreset.cols2 => '2 columns',+ PanePreset.cols3 => '3 columns',+ PanePreset.cols4 => '4 columns',+ PanePreset.cols5 => '5 columns',+ PanePreset.middleMain => 'Middle + sides',+ PanePreset.mainRight => 'Main right',+ PanePreset.twoOverThree => 'Two over three',+ PanePreset.balanced2 => '2 columns',+ PanePreset.balanced3 => '3 columns',+ PanePreset.balanced4 => '4 columns',+ PanePreset.balanced5 => '5 columns',+ PanePreset.mainAndGrid => 'Main left',+ PanePreset.mainOverGrid => 'Main top',+ };++ /// The column count this shape states, or null for [auto] and for the shapes+ /// that are not a lattice at all.+ int? get statedColumns => switch (this) {+ PanePreset.cols2 => 2,+ PanePreset.cols3 => 3,+ PanePreset.cols4 => 4,+ PanePreset.cols5 => 5,+ _ => null,+ };++ /// These shapes use their unit rectangles directly in both renderers.+ bool get usesTileGeometry => switch (this) {+ PanePreset.mainRight ||+ PanePreset.twoOverThree ||+ PanePreset.balanced2 ||+ PanePreset.balanced3 ||+ PanePreset.balanced4 ||+ PanePreset.balanced5 ||+ PanePreset.mainAndGrid ||+ PanePreset.mainOverGrid => true,+ _ => false,+ };++ /// The tiles this shape makes, as fractions of the grid.+ ///+ /// This is the shape's DESCRIPTION, and it lives here rather than in the+ /// picker that draws it so there is only one of it: the palette paints these+ /// rectangles and a test measures the real layout against them, so a diagram+ /// cannot drift into advertising a shape the grid does not build.+ ///+ /// Legacy automatic layouts accept their measured column count. They are+ /// not offered in the picker because they resolve to another shape there.+ List<Rect> tilesFor(int count, {int? columns}) => switch (this) {+ PanePreset.columns || PanePreset.splitLong => const [+ Rect.fromLTRB(0, 0, .5, 1),+ Rect.fromLTRB(.5, 0, 1, 1),+ ],+ PanePreset.rows => _lattice(count, 1),+ PanePreset.twoOverOne => const [+ Rect.fromLTRB(0, 0, .5, .5),+ Rect.fromLTRB(.5, 0, 1, .5),+ Rect.fromLTRB(0, .5, 1, 1),+ ],+ PanePreset.oneOverTwo => const [+ Rect.fromLTRB(0, 0, 1, .5),+ Rect.fromLTRB(0, .5, .5, 1),+ Rect.fromLTRB(.5, .5, 1, 1),+ ],+ PanePreset.mainLeft => const [+ Rect.fromLTRB(0, 0, .5, 1),+ Rect.fromLTRB(.5, 0, 1, .5),+ Rect.fromLTRB(.5, .5, 1, 1),+ ],+ PanePreset.mainRight => const [+ Rect.fromLTRB(0, 0, .5, .5),+ Rect.fromLTRB(.5, 0, 1, 1),+ Rect.fromLTRB(0, .5, .5, 1),+ ],+ PanePreset.quad => const [+ Rect.fromLTRB(0, 0, .5, .5),+ Rect.fromLTRB(.5, 0, 1, .5),+ Rect.fromLTRB(0, .5, .5, 1),+ Rect.fromLTRB(.5, .5, 1, 1),+ ],+ PanePreset.mainAndStack => const [+ Rect.fromLTRB(0, 0, .5, 1),+ Rect.fromLTRB(.5, 0, 1, 1 / 3),+ Rect.fromLTRB(.5, 1 / 3, 1, 2 / 3),+ Rect.fromLTRB(.5, 2 / 3, 1, 1),+ ],+ // Tile order reads across the top and then across the bottom: 1 and 4 on the+ // left, 2 down the middle, 3 and 5 on the right — which is the order a+ // person numbers them, not the order a column would fill.+ PanePreset.middleMain => const [+ Rect.fromLTRB(0, 0, 1 / 3, 1 / 2),+ Rect.fromLTRB(1 / 3, 0, 2 / 3, 1),+ Rect.fromLTRB(2 / 3, 0, 1, 1 / 2),+ Rect.fromLTRB(0, 1 / 2, 1 / 3, 1),+ Rect.fromLTRB(2 / 3, 1 / 2, 1, 1),+ ],+ PanePreset.twoOverThree => _balanced(count, 3, largerRowsLast: true),+ PanePreset.balanced2 => _balanced(count, 2),+ PanePreset.balanced3 => _balanced(count, 3),+ PanePreset.balanced4 => _balanced(count, 4),+ PanePreset.balanced5 => _balanced(count, 5),+ PanePreset.mainAndGrid => [+ const Rect.fromLTRB(0, 0, .5, 1),+ for (final tile in _balanced(count - 1, 2))+ Rect.fromLTRB(+ .5 + tile.left / 2,+ tile.top,+ .5 + tile.right / 2,+ tile.bottom,+ ),+ ],+ PanePreset.mainOverGrid => [+ const Rect.fromLTRB(0, 0, 1, .5),+ for (final tile in _balanced(+ count - 1,+ count == 4 ? 3 : ((count - 1) / 2).ceil().clamp(2, 5),+ ))+ Rect.fromLTRB(+ tile.left,+ .5 + tile.top / 2,+ tile.right,+ .5 + tile.bottom / 2,+ ),+ ],+ PanePreset.auto => _lattice(+ count,+ columns ?? _autoColumnsForDrawing(count),+ ),+ _ => _lattice(count, statedColumns!.clamp(1, count)),+ };++ static List<Rect> _balanced(+ int count,+ int columns, {+ bool largerRowsLast = false,+ }) {+ final rows = (count / columns.clamp(1, count)).ceil();+ final perRow = count ~/ rows;+ final extra = count % rows;+ int columnsIn(int row) =>+ perRow + ((largerRowsLast ? row >= rows - extra : row < extra) ? 1 : 0);+ return [+ for (var row = 0; row < rows; row++)+ for (var col = 0; col < columnsIn(row); col++)+ Rect.fromLTRB(+ col / columnsIn(row),+ row / rows,+ (col + 1) / columnsIn(row),+ (row + 1) / rows,+ ),+ ];+ }++ /// The lattice, laid out the way `_Lattice` lays it: row-major, the last row+ /// short when the count does not divide.+ ///+ /// Written twice would be the bug this whole file exists to prevent, so the+ /// widget's own arithmetic is mirrored here and a test measures one against+ /// the other.+ static List<Rect> _lattice(int count, int columns) {+ final cols = columns.clamp(1, count);+ final rows = (count / cols).ceil();+ return [+ for (var i = 0; i < count; i++)+ Rect.fromLTRB(+ (i % cols) / cols,+ (i ~/ cols) / rows,+ (i % cols + 1) / cols,+ (i ~/ cols + 1) / rows,+ ),+ ];+ }++ /// Only for the DIAGRAM: what a wide window typically carries. The grid's own+ /// answer is measured at build time and can differ — the point of the picture+ /// is to say "the app decides", and it says that best by showing a plausible+ /// grid rather than a special icon nobody can read.+ static int _autoColumnsForDrawing(int count) => count <= 6 ? 3 : 4;++ /// Stable across releases: this is what lands in the state file, so it must+ /// not be the enum's index — reordering the enum would silently repoint+ /// everyone's saved layout at a different shape.+ String get id => name;++ static PanePreset? byId(String? id) {+ for (final preset in PanePreset.values) {+ if (preset.id == id) return preset;+ }+ return _legacyIds[id];+ }++ /// At most six useful shapes. Balanced grids that resolve to the same+ /// rectangles at a particular count are offered only once.+ static List<PanePreset> forCount(int count) {+ if (count < 2) return const [];+ return _choices.putIfAbsent(count, () {+ final seen = <String>{};+ return List.unmodifiable([+ for (final preset in _candidates(count))+ if (seen.add(_shapeKey(preset.tilesFor(count)))) preset,+ ]);+ });+ }++ static final _choices = <int, List<PanePreset>>{};++ static List<PanePreset> _candidates(int count) => switch (count) {+ < 2 => const [],+ 2 => const [PanePreset.columns, PanePreset.rows],+ 3 => const [+ PanePreset.twoOverOne,+ PanePreset.oneOverTwo,+ PanePreset.mainLeft,+ PanePreset.mainRight,+ PanePreset.cols3,+ PanePreset.rows,+ ],+ 4 => const [+ PanePreset.quad,+ PanePreset.mainAndStack,+ PanePreset.mainOverGrid,+ PanePreset.cols4,+ PanePreset.rows,+ ],+ 5 => const [+ PanePreset.balanced3,+ PanePreset.twoOverThree,+ PanePreset.middleMain,+ PanePreset.mainAndGrid,+ PanePreset.mainOverGrid,+ PanePreset.cols5,+ ],+ _ => [+ PanePreset.balanced2,+ PanePreset.balanced3,+ PanePreset.balanced4,+ PanePreset.balanced5,+ if (count <= 9) ...[PanePreset.mainAndGrid, PanePreset.mainOverGrid],+ ],+ };++ /// Saved automatic/regular grids remain valid even though the picker now+ /// offers explicit, filled arrangements. Do not silently discard their IDs.+ bool supportsCount(int count) => switch (this) {+ PanePreset.splitLong || PanePreset.columns => count == 2,+ PanePreset.rows => count >= 2 && count <= 4,+ PanePreset.twoOverOne ||+ PanePreset.oneOverTwo ||+ PanePreset.mainLeft ||+ PanePreset.mainRight => count == 3,+ PanePreset.quad || PanePreset.mainAndStack => count == 4,+ PanePreset.middleMain || PanePreset.twoOverThree => count == 5,+ PanePreset.cols2 || PanePreset.auto => count >= 5,+ PanePreset.cols3 => count >= 3,+ PanePreset.cols4 => count >= 4,+ PanePreset.cols5 ||+ PanePreset.balanced2 ||+ PanePreset.balanced3 ||+ PanePreset.balanced4 ||+ PanePreset.balanced5 ||+ PanePreset.mainAndGrid => count >= 5,+ PanePreset.mainOverGrid => count >= 4,+ };++ /// Match the visible geometry rather than the old preset's name or tile+ /// order. This highlights Columns/Rows for saved automatic two-pane splits.+ static PanePreset? matchingChoice(int count, List<Rect> tiles) {+ final key = _shapeKey(tiles);+ for (final choice in forCount(count)) {+ if (_shapeKey(choice.tilesFor(count)) == key) return choice;+ }+ return null;+ }++ static String _shapeKey(List<Rect> tiles) {+ final parts = [+ for (final tile in tiles)+ [+ tile.left,+ tile.top,+ tile.right,+ tile.bottom,+ ].map((edge) => (edge * 1e8).round()).join(','),+ ]..sort();+ return parts.join(';');+ }++ /// What a grid of this size looks like when nobody has chosen.+ static PanePreset? defaultFor(int count) {+ return switch (count) {+ < 2 => null,+ 2 => PanePreset.splitLong,+ 3 => PanePreset.twoOverOne,+ 4 => PanePreset.quad,+ _ => PanePreset.auto,+ };+ }++ /// Ids written by the build that named these two by hand, before the column+ /// count became a thing any grid size could state. Read only — nothing writes+ /// them any more — so a layout saved yesterday still opens the shape it was+ /// left in rather than silently falling back to the default.+ static const _legacyIds = {'threeColumns': cols3, 'fourColumns': cols4};+}diff --git a/mobile/lib/state/pending_question.dart b/mobile/lib/state/pending_question.dartnew file mode 100644index 000000000..9daa627d0--- /dev/null+++ b/mobile/lib/state/pending_question.dart@@ -0,0 +1,109 @@+/// One agent stopped mid-turn to ask the person something.+///+/// The daemon finds these by reading the pane while a turn is open — the+/// transcript is useless for it, because the engine does not flush the+/// `AskUserQuestion` line until the question has already been ANSWERED. So a+/// question exists here for exactly as long as its dialog is on screen, and the+/// daemon says so twice: `commander_question` when it appears,+/// `commander_question_close` when it stops being on screen for any reason —+/// including someone answering it on a different client.+///+/// That second frame is the whole reason this is state and not a widget flag.+/// A question can be answered from the pane, from another window, or from the+/// dial cabled to this computer, and every one of those arrives back here down+/// the same path — so the ring cannot outlive a dialog somebody else closed.+///+/// The tile's amber ring and Needs input picker read this same live state.+class PendingQuestion {+ PendingQuestion({+ required this.machineId,+ required this.agentId,+ required this.requestId,+ required this.answerKey,+ required this.prompt,+ required this.options,+ required this.multi,+ required this.since,+ });++ final String machineId;+ final String agentId;++ /// Opaque id from the daemon — a hash of the session and the question's own+ /// text, so re-announcing the same open question is idempotent.+ final String requestId;++ /// What the `answers` map must be keyed by when replying. The daemon sets it+ /// to the question text itself for a pane-derived question; keeping it+ /// separate from [prompt] means a future engine can key by an id instead+ /// without every call site guessing.+ final String answerKey;++ final String prompt;+ final List<String> options;++ /// Whether the terminal dialog takes more than one option. Navigation does+ /// not answer it; the original terminal still owns that interaction.+ final bool multi;++ /// When this window first heard about it. Not when the agent actually+ /// blocked: a question that was already on screen when the app started is+ /// re-announced on attach, so the age shown is "how long we have known",+ /// which is the honest claim.+ final DateTime since;++ /// Same question, same agent — used to keep [since] across the re-announce+ /// that follows a reconnect, so reattaching does not reset every clock.+ bool sameAs(PendingQuestion other) =>+ other.requestId == requestId && other.agentId == agentId;++ PendingQuestion withSince(DateTime value) => PendingQuestion(+ machineId: machineId,+ agentId: agentId,+ requestId: requestId,+ answerKey: answerKey,+ prompt: prompt,+ options: options,+ multi: multi,+ since: value,+ );++ /// Build from a `commander_question` payload, or null if it carries nothing+ /// answerable. The daemon sends `questions` as a list but a pane-derived+ /// dialog is always exactly one — take the first and ignore the rest rather+ /// than inventing a queue no engine currently produces.+ static PendingQuestion? fromPayload({+ required String machineId,+ required String agentId,+ required Map<String, dynamic> payload,+ required DateTime now,+ }) {+ final requestId = payload['requestId'];+ if (requestId is! String || requestId.isEmpty) return null;+ final questions = payload['questions'];+ if (questions is! List || questions.isEmpty) return null;+ final first = questions.first;+ if (first is! Map) return null;++ final prompt = (first['q'] ?? first['key'] ?? '').toString().trim();+ if (prompt.isEmpty) return null;+ final rawOptions = first['options'];+ final options = rawOptions is List+ ? rawOptions+ .map((option) => option.toString().trim())+ .where((option) => option.isNotEmpty)+ .toList(growable: false)+ : const <String>[];++ return PendingQuestion(+ machineId: machineId,+ agentId: agentId,+ requestId: requestId,+ answerKey: (first['key'] ?? prompt).toString(),+ prompt: prompt,+ options: options,+ multi: first['multi'] == true,+ since: now,+ );+ }+}diff --git a/mobile/lib/state/swarm.dart b/mobile/lib/state/swarm.dartnew file mode 100644index 000000000..13d536162--- /dev/null+++ b/mobile/lib/state/swarm.dart@@ -0,0 +1,186 @@+import 'dart:ui' show Size;++import 'pane_preset.dart';+import 'pane_arrangement.dart';+import 'terminal_pane.dart';++/// A named arrangement of agents. Membership never owns the agent process.+/// Shared agents reuse the same pane/session across swarms, so the daemon has+/// exactly one controller and switching tabs cannot take over our own stream.+class Swarm {+ Swarm({required this.id, String name = 'New Harness'})+ : name = const {'New swarm', 'New tab', 'New Agent'}.contains(name)+ ? 'New Harness'+ : name;++ final String id;+ String name;+ final List<TerminalPane> panes = [];+ final Map<int, PanePreset> presets = {};+ final Map<String, PaneArrangement> paneSizes = {};+ PaneArrangement? arranged;+ String? arrangedKey;+ Size? arrangedMinimum;+ int? focusedPaneId;+ int? zoomedPaneId;+ int? previousPaneId;+ int? gridColumns;+ final Map<int, int> pinnedSlots = {};++ bool get isEmptyStarter =>+ name == 'New Harness' && panes.isEmpty && presets.isEmpty;++ PaneArrangement? get manualLayout => paneSizes['${panes.length}:manual'];++ void savePaneSizes(String key, PaneArrangement arrangement) {+ paneSizes[key] = arrangement;+ while (paneSizes.length > 64) {+ paneSizes.remove(paneSizes.keys.first);+ }+ }++ void remove(TerminalPane pane) {+ final index = panes.indexOf(pane);+ if (index < 0) return;+ final manual = manualLayout;+ panes.removeAt(index);+ if (manual != null && panes.length > 1) {+ final next = manual.remove(index);+ if (next == null) {+ paneSizes.remove('${panes.length}:manual');+ } else {+ savePaneSizes('${panes.length}:manual', next);+ }+ }+ if (manual != null) {+ pinnedSlots.updateAll((_, slot) => slot > index ? slot - 1 : slot);+ }+ arranged = null;+ arrangedKey = null;+ pinnedSlots.remove(pane.id);+ if (focusedPaneId == pane.id) {+ focusedPaneId = panes.isEmpty+ ? null+ : panes[index.clamp(0, panes.length - 1)].id;+ }+ if (zoomedPaneId == pane.id) zoomedPaneId = null;+ if (previousPaneId == pane.id) previousPaneId = null;+ }++ Map<String, Object?> toJson() {+ final agents = panes+ .where((p) => p.agentId != null)+ .toList(growable: false);+ return {+ 'id': id,+ 'name': name,+ 'focus': agents.indexWhere((p) => p.id == focusedPaneId),+ 'previousFocus': agents.indexWhere((p) => p.id == previousPaneId),+ 'zoom': agents.indexWhere((p) => p.id == zoomedPaneId),+ 'presets': {for (final e in presets.entries) '${e.key}': e.value.id},+ if (paneSizes.isNotEmpty)+ 'paneSizes': {+ for (final e in paneSizes.entries) e.key: e.value.toJson(),+ },+ 'panes': [+ for (final p in agents)+ PaneLayoutEntry(+ machineId: p.machineId,+ agentId: p.agentId!,+ composerVisible: p.composerVisible,+ pinnedSlot: pinnedSlots[p.id],+ ).toJson(),+ ],+ };+ }+}++/// Session-free history: closing a view never owns the agent's lifetime.+sealed class ClosedWork {+ const ClosedWork({required this.historyId});+ final String historyId;+}++class ClosedAgent extends ClosedWork {+ ClosedAgent(+ TerminalPane pane,+ Swarm swarm, {+ required super.historyId,+ required this.name,+ required this.machineName,+ required this.engine,+ }) : swarmId = swarm.id,+ swarmName = swarm.name,+ index = swarm.panes.indexOf(pane),+ machineId = pane.machineId,+ agentId = pane.agentId!,+ composerVisible = pane.composerVisible,+ pinnedSlot = swarm.pinnedSlots[pane.id],+ manualLayout = swarm.manualLayout,+ remainingAgents = List.unmodifiable([+ for (final other in swarm.panes)+ if (other != pane) (other.machineId, other.agentId),+ ]),+ zoomed = swarm.zoomedPaneId == pane.id;++ final String swarmId, swarmName, machineId, machineName, agentId, name;+ final String? engine;+ final int index;+ final bool composerVisible, zoomed;+ final int? pinnedSlot;+ final PaneArrangement? manualLayout;+ final List<(String, String?)> remainingAgents;+}++/// Terminal buffers and controllers are released normally; a reopened view+/// reuses any live peer.+class ClosedSwarm extends ClosedWork {+ ClosedSwarm(+ Swarm swarm, {+ required super.historyId,+ required this.index,+ Swarm? replacement,+ this.engine,+ }) : id = swarm.id,+ name = swarm.name,+ gridColumns = swarm.gridColumns,+ focus = swarm.panes.indexWhere((p) => p.id == swarm.focusedPaneId),+ previousFocus = swarm.panes.indexWhere(+ (p) => p.id == swarm.previousPaneId,+ ),+ zoom = swarm.panes.indexWhere((p) => p.id == swarm.zoomedPaneId),+ presets = Map.unmodifiable(swarm.presets),+ paneSizes = Map.unmodifiable(swarm.paneSizes),+ panes = List.unmodifiable([+ for (final pane in swarm.panes)+ (+ machineId: pane.machineId,+ agentId: pane.agentId,+ composerVisible: pane.composerVisible,+ pinnedSlot: swarm.pinnedSlots[pane.id],+ ),+ ]),+ replacementId = replacement?.id;++ final String id;+ final String name;+ final String? engine;+ final int index;+ final int? gridColumns;+ final int focus;+ final int previousFocus;+ final int zoom;+ final Map<int, PanePreset> presets;+ final Map<String, PaneArrangement> paneSizes;+ final List<+ ({String machineId, String? agentId, bool composerVisible, int? pinnedSlot})+ >+ panes;+ final String? replacementId;++ bool replacesUntouchedWelcome(Swarm swarm) =>+ swarm.id == replacementId &&+ swarm.name == 'New Harness' &&+ swarm.panes.isEmpty &&+ swarm.presets.isEmpty;+}diff --git a/mobile/lib/state/terminal_pane.dart b/mobile/lib/state/terminal_pane.dartnew file mode 100644index 000000000..ceab4b648--- /dev/null+++ b/mobile/lib/state/terminal_pane.dart@@ -0,0 +1,123 @@+import 'package:flutter/widgets.dart';++import '../terminal/terminal_session.dart';++/// One tile in the terminal grid.+///+/// The INTENT (which agent this tile is for) and the live [session] are kept+/// apart on purpose. A restored layout names agents on machines that have not+/// answered yet, and machines answer in an order this side does not decide —+/// so a tile has to be able to exist, and say what it is waiting for, before+/// there is anything to attach. The same split is what lets a tile survive its+/// machine going offline and coming back without the grid reshuffling around+/// it.+class TerminalPane {+ TerminalPane({required this.id, required this.machineId, this.agentId});++ /// Stable for the tile's whole life, including across a machine going away+ /// and returning. Widget keys hang off this: keying on the agent id instead+ /// would tear down and rebuild the WebView — and with it the scrollback the+ /// user was reading — every time a tile were reassigned.+ final int id;++ String machineId;++ /// Null means the tile is about the MACHINE, not an agent on it.+ ///+ /// A machine that needs linking cannot list its agents — that is what needing+ /// a link means — so there is no agent to put in a tile, and without this the+ /// link screen would have no way onto the screen at all. The same shape+ /// carries "this machine has no agents yet".+ String? agentId;++ TerminalSession? session;++ /// Last visible geometry, retained while this controller is parked off screen.+ Size? lastViewSize;++ /// The grid cell's widget key — a GlobalKey, and measured to be necessary.+ ///+ /// The layout puts cells in DIFFERENT parents depending on how many there+ /// are: with four, two live in the top Row and two in the bottom one. A+ /// ValueKey only preserves an element within one parent, so any move across+ /// that boundary rebuilds the cell — remounting TerminalPanel, taking a fresh+ /// layout pass, and paying a resize round trip to tmux.+ ///+ /// Probed on the real arrangement before this existed: swapping two cells+ /// across the Rows remounted 2 of them, and simply GROWING from two panes to+ /// three remounted all 3 — so the flash was already there, on every add,+ /// before reordering was a feature. With a GlobalKey the same swap remounts 0.+ ///+ /// Lives on the pane so its lifetime is the tile's, exactly like [id].+ final GlobalKey cellKey = GlobalKey();++ /// The slot this tile insists on keeping, or null for a tile that is happy to+ /// slide.+ ///+ /// What it protects against is the hole a close leaves: shut the second of+ /// four tiles and everything after it slides up one, so the agent someone was+ /// reading in the bottom-left is suddenly top-right — the grid rearranged+ /// itself under a hand that only asked to close something else. A pinned tile+ /// stays where it is and the others fill in around it.+ ///+ /// It binds automatic movement only. Dragging a tile is an explicit answer to+ /// the same question, so a drag always wins and takes the pin with it —+ /// otherwise the tile would spring back and the drag would look broken.+ int? pinnedSlot;++ bool get isPinned => pinnedSlot != null;++ /// Whether this tile shows the composer textbox under its terminal.+ ///+ /// Only ever consulted for a remote machine — that is the one where typing straight into the+ /// pane pays a network round trip per keystroke. Off by default, and remembered, so the choice+ /// survives a restart the way the rest of the layout does.+ bool composerVisible = false;+}++/// A tile as it survives a restart: intent only, never the session.+class PaneLayoutEntry {+ const PaneLayoutEntry({+ required this.machineId,+ required this.agentId,+ this.composerVisible = false,+ this.pinnedSlot,+ });++ final String machineId;+ final String agentId;+ final bool composerVisible;+ final int? pinnedSlot;++ Map<String, dynamic> toJson() => {+ 'machineId': machineId,+ 'agentId': agentId,+ 'composerVisible': composerVisible,+ // Absent for the tiles nobody pinned, which is nearly all of them.+ 'pinnedSlot': ?pinnedSlot,+ };++ static PaneLayoutEntry? fromJson(Object? raw) {+ if (raw is! Map) return null;+ final machineId = raw['machineId'];+ final agentId = raw['agentId'];+ if (machineId is! String || machineId.isEmpty) return null;+ if (agentId is! String || agentId.isEmpty) return null;+ final composer = raw['composerVisible'];+ return PaneLayoutEntry(+ machineId: machineId,+ agentId: agentId,+ // Absent means a layout written before the composer existed. Those default to OFF, matching a+ // tile the user has never had an opinion about — never to ON, which would read as a setting+ // they chose.+ composerVisible: composer is bool ? composer : false,+ // A negative or absurd slot is read as "not pinned" rather than clamped:+ // a pin is a place someone chose, and inventing a different one for them+ // is worse than forgetting it.+ pinnedSlot: switch (raw['pinnedSlot']) {+ final int slot when slot >= 0 => slot,+ _ => null,+ },+ );+ }+}diff --git a/mobile/lib/stats/harness_stats.dart b/mobile/lib/stats/harness_stats.dartnew file mode 100644index 000000000..8b5169ab0--- /dev/null+++ b/mobile/lib/stats/harness_stats.dart@@ -0,0 +1,226 @@+/// How much work this app has done: agents started, turns taken, time spent.+///+/// Ported from Orca's `src/main/stats/` — same three cards, same "tracking+/// since" line, same balanced start/stop accounting for the clock.+///+/// **What it counts and what it does not.** These are the app's OWN events, not+/// a vendor's and not a file on disk: the ledger beside it (`usage/ledger/`)+/// reads what the agent CLIs wrote and counts tokens, and this counts what+/// Harness itself watched happen. So it needs no permission and has no enable+/// switch — an app may count what it did.+///+/// ⚠️ **Two deliberate differences from Orca.**+///+/// 1. **PRs are not a Harness concept**, so the third card is TURNS. Orca opens+/// pull requests from its worktrees and counts them; this app launches agents+/// on machines and never touches a forge. A card wired to a number that can+/// only ever be zero is worse than a card showing something true, and turns+/// fall out of the same event stream the clock already needs.+/// 2. **No event log is kept.** Orca persists up to 10,000 individual events+/// beside its aggregates, for per-repo breakdowns it does not yet draw. That+/// costs a ~900KB rewrite every few seconds on a busy session, so what is+/// persisted here is the aggregates alone. [firstEventAt] is the reason Orca+/// needed the log to be lossy-safe, and it is stored directly here for the+/// same reason: it is set once and never moves, so trimming can never drag+/// "tracking since" forward.+library;++import 'dart:async';+import 'dart:convert';++import 'package:flutter/foundation.dart';++import '../core/snapshot_store.dart';+import '../core/test_run.dart';++/// How long to wait before writing after something happens.+///+/// Five seconds, as Orca uses: these events are infrequent and nothing on screen+/// waits for the write. A turn that starts and ends inside the window costs one+/// write rather than two.+const kStatsWriteDebounce = Duration(seconds: 5);++/// The format. Bumped when the persisted shape changes, which discards an older+/// snapshot rather than reading one that means something slightly different.+const _kStatsVersion = 1;++/// The three figures and the date under them.+@immutable+class StatsSummary {+ const StatsSummary({+ this.agentsSpawned = 0,+ this.turns = 0,+ this.timeWorked = Duration.zero,+ this.firstEventAt,+ });++ /// Agents this app has created. Counted at creation, not at first message —+ /// an agent that was launched and never spoken to was still launched.+ final int agentsSpawned;++ /// Turns started. One per time somebody set an agent working.+ final int turns;++ /// Time agents spent working, summed across every finished turn.+ final Duration timeWorked;++ /// When the first event landed, or null before any has.+ ///+ /// Set once and never moved, so the "Tracking since" line means what it says+ /// however much is later forgotten.+ final DateTime? firstEventAt;++ /// Nothing has happened yet — what the empty state keys on.+ bool get isEmpty => agentsSpawned == 0 && turns == 0;+}++class HarnessStats extends ChangeNotifier {+ HarnessStats({SnapshotStore? store})+ : _store = store ?? FileSnapshotStore('harness-stats');++ final SnapshotStore _store;++ int _agentsSpawned = 0;+ int _turns = 0;+ int _workedMs = 0;+ DateTime? _firstEventAt;++ /// Turns under way, keyed by whatever the caller uses to name one, mapped to+ /// when it started.+ ///+ /// In memory only. A turn still running when the app quits is closed out at+ /// [flush]; a turn still running when the app is KILLED is lost, which is the+ /// right trade — the alternative is persisting a start time that a crash would+ /// later turn into a multi-day "turn".+ final Map<String, DateTime> _live = {};++ Timer? _writeTimer;+ bool _disposed = false;++ StatsSummary get summary => StatsSummary(+ agentsSpawned: _agentsSpawned,+ turns: _turns,+ timeWorked: Duration(milliseconds: _workedMs),+ firstEventAt: _firstEventAt,+ );++ /// Read the counters back off disk. Never throws.+ Future<void> load() async {+ final contents = await _store.read();+ if (contents == null) return;+ try {+ final decoded = jsonDecode(contents);+ if (decoded is! Map<String, Object?>) return;+ if (decoded['version'] != _kStatsVersion) return;+ _agentsSpawned = _int(decoded['agentsSpawned']);+ _turns = _int(decoded['turns']);+ _workedMs = _int(decoded['workedMs']);+ final first = decoded['firstEventAt'];+ _firstEventAt = first is String ? DateTime.tryParse(first) : null;+ } on Object {+ // A snapshot we cannot read is one we do not have. Counting restarts+ // rather than refusing to open the screen.+ return;+ }+ _notify();+ }++ /// An agent was created.+ void onAgentSpawned({DateTime? at}) {+ _agentsSpawned++;+ _stamp(at);+ _schedule();+ _notify();+ }++ /// An agent started working. [key] must identify one turn — the same value has+ /// to come back to [onTurnEnded].+ ///+ /// A second start on a live key is ignored rather than restarting the clock:+ /// `turn_heartbeat` and a reconnect can both re-announce a turn already under+ /// way, and taking the later timestamp would quietly discard the time before+ /// it.+ void onTurnStarted(String key, {DateTime? at}) {+ if (_live.containsKey(key)) return;+ final now = at ?? DateTime.now();+ _live[key] = now;+ _turns++;+ _stamp(now);+ _schedule();+ _notify();+ }++ /// An agent stopped working.+ ///+ /// An unmatched end is dropped, exactly as Orca drops an unbalanced stop: the+ /// app reconnects to agents that were already running, so a `turn_ended` for a+ /// turn this process never saw start has no duration to contribute and+ /// inventing one would be worse than counting nothing.+ void onTurnEnded(String key, {DateTime? at}) {+ final startedAt = _live.remove(key);+ if (startedAt == null) return;+ final elapsed = (at ?? DateTime.now()).difference(startedAt);+ if (elapsed > Duration.zero) _workedMs += elapsed.inMilliseconds;+ _schedule();+ _notify();+ }++ /// Close out every live turn and write now.+ ///+ /// Idempotent, and safe to call on the quit path: the turns still running are+ /// ended at this moment, so their time is counted rather than lost.+ Future<void> flush() async {+ final now = DateTime.now();+ for (final key in _live.keys.toList()) {+ onTurnEnded(key, at: now);+ }+ _writeTimer?.cancel();+ _writeTimer = null;+ await _write();+ }++ void _stamp(DateTime? at) => _firstEventAt ??= at ?? DateTime.now();++ void _schedule() {+ // Never on a timer under test: a pending `Timer` is a `pumpAndSettle` that+ // never settles, and the write would reach a real `~/.harness` besides.+ if (kUnderTest || _disposed || _writeTimer != null) return;+ _writeTimer = Timer(kStatsWriteDebounce, () {+ _writeTimer = null;+ unawaited(_write());+ });+ }++ Future<void> _write() => _store.write(+ jsonEncode({+ 'version': _kStatsVersion,+ 'agentsSpawned': _agentsSpawned,+ 'turns': _turns,+ 'workedMs': _workedMs,+ 'firstEventAt': _firstEventAt?.toIso8601String(),+ }),+ );++ void _notify() {+ if (!_disposed) notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ _writeTimer?.cancel();+ _writeTimer = null;+ super.dispose();+ }++ static int _int(Object? value) =>+ value is num && value.isFinite && value > 0 ? value.toInt() : 0;+}++/// The app's own counters.+///+/// A singleton like `analytics` and `terminalFontStore`, for the same reason: the+/// call sites are `AppNotifier`'s event dispatcher and one settings pane, and+/// threading an instance from one to the other would mean handing a `Ref` to a+/// widget that has no other use for one.+final harnessStats = HarnessStats();diff --git a/mobile/lib/terminal/remote_media_download.dart b/mobile/lib/terminal/remote_media_download.dartnew file mode 100644index 000000000..9d054c68d--- /dev/null+++ b/mobile/lib/terminal/remote_media_download.dart@@ -0,0 +1,296 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:math';+import 'dart:typed_data';++import '../core/harness_file_store.dart';+import 'terminal_links.dart';++// Mirrors cli/src/lib/mediaPreview.ts. Four bounded requests per batch keep a+// high-latency relay useful without buffering a whole video on either machine.+const remoteMediaChunkBytes = 128 * 1024;+const remoteMediaMaxBytes = 512 * 1024 * 1024;+const _cacheMaxBytes = 1024 * 1024 * 1024;+const _cacheMaxAge = Duration(hours: 24);++typedef ReadRemoteMediaChunk = Future<Map<String, dynamic>> Function({+ required int offset,+ String? revision,+});++class RemoteMediaException implements Exception {+ final String message;+ const RemoteMediaException(this.message);+ @override+ String toString() => message;+}++class RemoteMediaCancelled implements Exception {+ const RemoteMediaCancelled();+}++class MediaDownloadCancellation {+ final _listeners = <void Function()>{};+ bool _cancelled = false;+ bool get isCancelled => _cancelled;+ void cancel() {+ if (isCancelled) return;+ _cancelled = true;+ for (final listener in _listeners.toList()) {+ listener();+ }+ _listeners.clear();+ }++ void check() {+ if (isCancelled) throw const RemoteMediaCancelled();+ }++ Future<T> wait<T>(Future<T> operation) {+ final result = Completer<T>();+ void cancelled() {+ if (!result.isCompleted) {+ result.completeError(const RemoteMediaCancelled());+ }+ }++ // Remove listeners after every batch; retaining completed futures on one+ // cancellation future would accidentally retain the entire video in RAM.+ operation.then(+ (value) {+ _listeners.remove(cancelled);+ if (!result.isCompleted) result.complete(value);+ },+ onError: (Object error, StackTrace stack) {+ _listeners.remove(cancelled);+ if (!result.isCompleted) result.completeError(error, stack);+ },+ );+ if (isCancelled) {+ cancelled();+ } else {+ _listeners.add(cancelled);+ }+ return result.future;+ }+}++class RemoteMediaProgress {+ final String filename;+ final int receivedBytes;+ final int? totalBytes;+ const RemoteMediaProgress(this.filename, this.receivedBytes, this.totalBytes);+ double? get fraction =>+ totalBytes == null ? null : receivedBytes / totalBytes!;+}++class _Chunk {+ final String filename;+ final int totalBytes;+ final String revision;+ final Uint8List bytes;+ const _Chunk(this.filename, this.totalBytes, this.revision, this.bytes);++ factory _Chunk.parse(Map<String, dynamic> raw, int offset, [_Chunk? first]) {+ final filename = raw['filename'];+ final total = raw['totalBytes'];+ final revision = raw['revision'];+ final encoded = raw['contentBase64'];+ if (raw['media'] != true ||+ raw['offset'] != offset ||+ filename is! String ||+ filename.isEmpty ||+ filename.length > 255 ||+ RegExp(r'[\\/\x00-\x1f\x7f]').hasMatch(filename) ||+ !isMediaPath(filename) ||+ total is! int ||+ total <= 0 ||+ total > remoteMediaMaxBytes ||+ offset >= total ||+ revision is! String ||+ !RegExp(r'^[a-f0-9]{64}$').hasMatch(revision) ||+ encoded is! String) {+ throw const RemoteMediaException(+ 'This machine returned an invalid media preview. Update its Harness CLI and try again.',+ );+ }+ if (first != null &&+ (first.totalBytes != total ||+ first.revision != revision ||+ first.filename != filename)) {+ throw const RemoteMediaException(+ 'The file changed while downloading. Wait for it to finish generating and try again.',+ );+ }+ final length = min(remoteMediaChunkBytes, total - offset);+ if (encoded.length != ((length + 2) ~/ 3) * 4) {+ throw const RemoteMediaException(+ 'The media download was incomplete. Try again.',+ );+ }+ Uint8List bytes;+ try {+ bytes = base64Decode(encoded);+ } on FormatException {+ throw const RemoteMediaException(+ 'The media download was incomplete. Try again.',+ );+ }+ if (bytes.length != length) {+ throw const RemoteMediaException(+ 'The media download was incomplete. Try again.',+ );+ }+ return _Chunk(filename, total, revision, bytes);+ }+}++/// Each preview gets a private, unique directory, so identical paths on two+/// machines (or two concurrent requests) can never overwrite each other. Only a+/// completely downloaded file is renamed to its real extension and opened.+class RemoteMediaDownloader {+ final Directory? directory;+ RemoteMediaDownloader({this.directory});+ static final _activeDirectories = <String>{};++ Future<String> download({+ required ReadRemoteMediaChunk readChunk,+ required MediaDownloadCancellation cancellation,+ required void Function(RemoteMediaProgress) onProgress,+ }) async {+ Directory? staging;+ RandomAccessFile? output;+ var complete = false;+ try {+ cancellation.check();+ final first = _Chunk.parse(+ await cancellation.wait(readChunk(offset: 0)),+ 0,+ );+ cancellation.check();+ final cache =+ directory ??+ Directory(+ '${HarnessFileStore.defaultDirectoryPath()}/media-previews',+ );+ if (await FileSystemEntity.type(cache.path, followLinks: false) ==+ FileSystemEntityType.link) {+ throw const RemoteMediaException(+ 'The preview cache is not accessible.',+ );+ }+ await cache.create(recursive: true);+ await _prune(cache, reserveBytes: first.totalBytes);+ cancellation.check();+ staging = await cache.createTemp('preview-');+ _activeDirectories.add(staging.path);+ output = await File('${staging.path}/download.part')+ .open(mode: FileMode.write);+ var received = 0;+ Future<void> write(_Chunk chunk) async {+ cancellation.check();+ await output!.writeFrom(chunk.bytes);+ cancellation.check();+ received += chunk.bytes.length;+ onProgress(+ RemoteMediaProgress(first.filename, received, first.totalBytes),+ );+ }++ await write(first);+ for (var offset = remoteMediaChunkBytes; offset < first.totalBytes;) {+ cancellation.check();+ final offsets = <int>[];+ for (+ var i = 0;+ i < 4 && offset < first.totalBytes;+ i++, offset += remoteMediaChunkBytes+ ) {+ offsets.add(offset);+ }+ final replies = await cancellation.wait(+ Future.wait([+ for (final start in offsets)+ Future.sync(+ () => readChunk(offset: start, revision: first.revision),+ ),+ ], eagerError: true),+ );+ for (var i = 0; i < replies.length; i++) {+ await write(_Chunk.parse(replies[i], offsets[i], first));+ }+ }+ cancellation.check();+ await output.close();+ output = null;+ cancellation.check();+ var filename = first.filename.replaceAll(RegExp(r'[:*?"<>|]'), '_');+ if (utf8.encode(filename).length > 200) {+ filename = 'preview${filename.substring(filename.lastIndexOf('.'))}';+ }+ final file = await File('${staging.path}/download.part')+ .rename('${staging.path}/$filename');+ cancellation.check();+ complete = true;+ return file.path;+ } on FileSystemException {+ throw const RemoteMediaException(+ 'Could not save this preview. Check available disk space and try again.',+ );+ } finally {+ try {+ await output?.close();+ } on FileSystemException {+ /* still remove partial data */+ }+ if (staging != null) {+ _activeDirectories.remove(staging.path);+ if (!complete) {+ try {+ await staging.delete(recursive: true);+ } on FileSystemException {+ /* best effort */+ }+ }+ }+ }+ }++ /// Never follow links, touch active transfers, or let cache upkeep prevent a read.+ Future<void> _prune(Directory cache, {required int reserveBytes}) async {+ try {+ final entries = <({Directory directory, DateTime modified, int bytes})>[];+ await for (final entry in cache.list(followLinks: false)) {+ if (entry is! Directory ||+ !entry.uri.pathSegments+ .where((s) => s.isNotEmpty)+ .last+ .startsWith('preview-') ||+ _activeDirectories.contains(entry.path)) {+ continue;+ }+ var bytes = 0;+ await for (final file in entry.list(followLinks: false)) {+ if (file is File) bytes += (await file.stat()).size;+ }+ entries.add((+ directory: entry,+ modified: (await entry.stat()).modified,+ bytes: bytes,+ ));+ }+ entries.sort((a, b) => a.modified.compareTo(b.modified));+ var bytes = entries.fold(reserveBytes, (sum, entry) => sum + entry.bytes);+ final oldest = DateTime.now().subtract(_cacheMaxAge);+ for (final entry in entries) {+ if (entry.modified.isBefore(oldest) || bytes > _cacheMaxBytes) {+ await entry.directory.delete(recursive: true);+ bytes -= entry.bytes;+ }+ }+ } on FileSystemException {+ /* Cache pruning is best effort. */+ }+ }+}diff --git a/mobile/lib/terminal/terminal_binary.dart b/mobile/lib/terminal/terminal_binary.dartnew file mode 100644index 000000000..e9b21c37b--- /dev/null+++ b/mobile/lib/terminal/terminal_binary.dart@@ -0,0 +1,255 @@+import 'dart:typed_data';++const terminalLocalVersion = 1;+const terminalLocalHeaderBytes = 12;+const terminalLocalMaxPayloadBytes = 512 * 1024;+// A paste is delivered whole, in one frame — unlike every other kind, which is either a small+// bounded control message (keyframe/sync) or already chunked upstream to stay well under the+// keystroke ceiling (input, ≤8 KiB per frame). Mirrors TERMINAL_LOCAL_PASTE_MAX_PAYLOAD_BYTES in+// the harness CLI's terminalBinary.ts — keep the two in step.+const terminalLocalPasteMaxPayloadBytes = 6 * 1024 * 1024;+// An image paste (a clipboard screenshot, "Copy Image", ...) is delivered whole, same as a text+// paste — but the bytes are already-compressed PNG data, not text, so the ceiling is sized for a+// reasonable screenshot rather than a large source-code paste. Mirrors+// TERMINAL_LOCAL_IMAGE_PASTE_MAX_PAYLOAD_BYTES in the harness CLI's terminalBinary.ts — keep the+// two in step.+const terminalLocalImagePasteMaxPayloadBytes = 8 * 1024 * 1024;+// A dropped (non-image) file, delivered whole so its path can be pasted on the far side — see+// TerminalSession.pasteFile. Ordinary files run larger than a screenshot, hence its own, more+// generous ceiling; this is a modest atomic-frame limit, not a general file-transfer feature — a+// bigger file is rejected client-side rather than chunked. Mirrors+// TERMINAL_LOCAL_PASTE_FILE_MAX_PAYLOAD_BYTES in the harness CLI's terminalBinary.ts — keep the+// two in step.+const terminalLocalPasteFileMaxPayloadBytes = 20 * 1024 * 1024;++enum TerminalBinaryKind {+ input(1),+ output(2),+ keyframe(3),+ sync(4),++ /// A clipboard paste made directly into the terminal, delivered as one atomic unit instead of+ /// going through the chunked keystroke pipeline — see [TerminalSession.pasteText]. Upload+ /// (client→CLI) only; nothing ever sends this back down.+ paste(5),++ /// A clipboard IMAGE paste (raw PNG bytes) — same "atomic, out-of-band" shape as [paste], but+ /// carrying binary image data instead of UTF-8 text, so it cannot share that kind (the CLI's+ /// paste handler requires valid UTF-8). See [TerminalSession.pasteImage]. Upload (client→CLI)+ /// only; nothing ever sends this back down.+ imagePaste(6),++ /// A dropped (non-image) FILE — carries the original filename plus its bytes, so the daemon can+ /// write it to disk on its own machine and paste that path as text (never the OS clipboard, and+ /// never a Ctrl+V replay — unlike [imagePaste], the goal here is only "the pane gets a valid+ /// path"). See [TerminalSession.pasteFile]. Upload (client→CLI) only; nothing ever sends this+ /// back down.+ pasteFile(7);++ final int code;+ const TerminalBinaryKind(this.code);++ static TerminalBinaryKind? fromCode(int code) {+ for (final kind in values) {+ if (kind.code == code) return kind;+ }+ return null;+ }+}++/// The ceiling on one frame of [kind]: the loopback payload here, and equally+/// the relay's HTRM ciphertext — the CLI's `TERMINAL_BINARY_*_MAX_CIPHERTEXT_BYTES`+/// are the same numbers, which is why `e2ee/terminal_cipher.dart` reads them from+/// here rather than restating them.+int maxTerminalPayloadBytesFor(TerminalBinaryKind kind) {+ switch (kind) {+ case TerminalBinaryKind.paste:+ return terminalLocalPasteMaxPayloadBytes;+ case TerminalBinaryKind.imagePaste:+ return terminalLocalImagePasteMaxPayloadBytes;+ case TerminalBinaryKind.pasteFile:+ return terminalLocalPasteFileMaxPayloadBytes;+ default:+ return terminalLocalMaxPayloadBytes;+ }+}++class TerminalBinaryFrame {+ final TerminalBinaryKind kind;+ final String streamId;+ final int seq;+ final Uint8List bytes;+ final bool compressed;+ final int? cols;+ final int? rows;++ const TerminalBinaryFrame({+ required this.kind,+ required this.streamId,+ required this.seq,+ required this.bytes,+ required this.compressed,+ this.cols,+ this.rows,+ });+}++final _localMagic = Uint8List.fromList(const [0x48, 0x54, 0x52, 0x4c]);+const _flagZlib = 1;++Uint8List? _uuidBytes(String id) {+ final hex = id.replaceAll('-', '');+ if (!RegExp(r'^[0-9a-fA-F]{32}$').hasMatch(hex)) return null;+ return Uint8List.fromList([+ for (var index = 0; index < 16; index++)+ int.parse(hex.substring(index * 2, index * 2 + 2), radix: 16),+ ]);+}++String _uuidString(Uint8List bytes) {+ final hex = bytes+ .map((byte) => byte.toRadixString(16).padLeft(2, '0'))+ .join();+ return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';+}++Uint8List? encodeTerminalPlain(TerminalBinaryFrame frame) {+ final id = _uuidBytes(frame.streamId);+ if (id == null || frame.seq < 0) return null;+ if ((frame.kind == TerminalBinaryKind.input ||+ frame.kind == TerminalBinaryKind.sync ||+ frame.kind == TerminalBinaryKind.paste ||+ frame.kind == TerminalBinaryKind.imagePaste ||+ frame.kind == TerminalBinaryKind.pasteFile) &&+ frame.compressed) {+ return null;+ }+ if (frame.kind == TerminalBinaryKind.sync && frame.bytes.isNotEmpty) {+ return null;+ }+ final metaBytes = frame.kind == TerminalBinaryKind.keyframe ? 28 : 24;+ final output = Uint8List(metaBytes + frame.bytes.length)..setRange(0, 16, id);+ final view = ByteData.sublistView(output)+ ..setUint64(16, frame.seq, Endian.big);+ if (frame.kind == TerminalBinaryKind.keyframe) {+ final cols = frame.cols;+ final rows = frame.rows;+ if (cols == null ||+ rows == null ||+ cols < 1 ||+ cols > 0xffff ||+ rows < 1 ||+ rows > 0xffff) {+ return null;+ }+ view.setUint16(24, cols, Endian.big);+ view.setUint16(26, rows, Endian.big);+ }+ output.setRange(metaBytes, output.length, frame.bytes);+ return output;+}++TerminalBinaryFrame? decodeTerminalPlain(+ TerminalBinaryKind kind,+ int flags,+ Uint8List plaintext,+) {+ if ((flags & ~_flagZlib) != 0 ||+ ((kind == TerminalBinaryKind.input ||+ kind == TerminalBinaryKind.sync ||+ kind == TerminalBinaryKind.paste ||+ kind == TerminalBinaryKind.imagePaste ||+ kind == TerminalBinaryKind.pasteFile) &&+ flags != 0)) {+ return null;+ }+ final metaBytes = kind == TerminalBinaryKind.keyframe ? 28 : 24;+ if (plaintext.length < metaBytes ||+ (kind == TerminalBinaryKind.sync && plaintext.length != metaBytes)) {+ return null;+ }+ final view = ByteData.sublistView(plaintext);+ return TerminalBinaryFrame(+ kind: kind,+ streamId: _uuidString(Uint8List.sublistView(plaintext, 0, 16)),+ seq: view.getUint64(16, Endian.big),+ bytes: Uint8List.fromList(plaintext.sublist(metaBytes)),+ compressed: (flags & _flagZlib) != 0,+ cols: kind == TerminalBinaryKind.keyframe+ ? view.getUint16(24, Endian.big)+ : null,+ rows: kind == TerminalBinaryKind.keyframe+ ? view.getUint16(26, Endian.big)+ : null,+ );+}++/// Plain terminal framing for the loopback CLI transport. The CLI now terminates E2EE itself for+/// every machine (own or relayed) — see the harness CLI's lib/remoteRelay.ts — so this is the only+/// wire format the app ever needs; there is no separate encrypted variant anymore.+Uint8List? encodeTerminalLocal(TerminalBinaryFrame frame) {+ final payload = encodeTerminalPlain(frame);+ if (payload == null ||+ payload.length > maxTerminalPayloadBytesFor(frame.kind)) {+ return null;+ }+ final header = Uint8List(terminalLocalHeaderBytes)+ ..setRange(0, 4, _localMagic);+ header[4] = terminalLocalVersion;+ header[5] = frame.kind.code;+ header[6] = frame.compressed ? _flagZlib : 0;+ ByteData.sublistView(header).setUint32(8, payload.length, Endian.big);+ return Uint8List.fromList([...header, ...payload]);+}++/// Kind and stream of a loopback (HTRL) frame from its headers alone — enough to+/// route it without inflating or copying the payload. Null when the frame does+/// not carry a plain body [decodeTerminalLocal] would accept either.+({TerminalBinaryKind kind, String streamId})? peekTerminalLocal(+ Uint8List bytes,+) {+ if (bytes.length < terminalLocalHeaderBytes + 16) return null;+ for (var index = 0; index < _localMagic.length; index++) {+ if (bytes[index] != _localMagic[index]) return null;+ }+ final kind = TerminalBinaryKind.fromCode(bytes[5]);+ if (bytes[4] != terminalLocalVersion || kind == null) return null;+ return (+ kind: kind,+ streamId: _uuidString(+ Uint8List.sublistView(+ bytes,+ terminalLocalHeaderBytes,+ terminalLocalHeaderBytes + 16,+ ),+ ),+ );+}++TerminalBinaryFrame? decodeTerminalLocal(List<int> raw) {+ final bytes = Uint8List.fromList(raw);+ if (bytes.length < terminalLocalHeaderBytes) return null;+ for (var index = 0; index < _localMagic.length; index++) {+ if (bytes[index] != _localMagic[index]) return null;+ }+ final kind = TerminalBinaryKind.fromCode(bytes[5]);+ if (bytes[4] != terminalLocalVersion || kind == null || bytes[7] != 0) {+ return null;+ }+ final length = ByteData.sublistView(bytes).getUint32(8, Endian.big);+ if (length > maxTerminalPayloadBytesFor(kind) ||+ bytes.length != terminalLocalHeaderBytes + length) {+ return null;+ }+ return decodeTerminalPlain(+ kind,+ bytes[6],+ Uint8List.fromList(bytes.sublist(terminalLocalHeaderBytes)),+ );+}++/// Per-chunk size for a chunked image/file upload — comfortably under the 512 KiB per-binary-message+/// ceiling shared by the backend relay and the P2P data channel (with AEAD/framing overhead room to+/// spare). Every chunk but the last is exactly this size; `seq` is the chunk index. Mirrors the+/// harness CLI's `UPLOAD_CHUNK_BYTES` in terminalStreamManager.ts — keep the two in step.+const terminalUploadChunkBytes = 256 * 1024;diff --git a/mobile/lib/terminal/terminal_font_store.dart b/mobile/lib/terminal/terminal_font_store.dartnew file mode 100644index 000000000..db623cce3--- /dev/null+++ b/mobile/lib/terminal/terminal_font_store.dart@@ -0,0 +1,204 @@+import '../core/apple_fonts.dart';++import 'package:flutter/foundation.dart';+import 'package:xterm/xterm.dart';++import '../core/harness_file_store.dart';+import '../core/local_key_value_store.dart';+import 'terminal_typography.dart';++/// A monospace font the terminal is allowed to render in.+///+/// Deliberately a closed, curated set rather than free text or a native font+/// picker: the vendored renderer measures cell width by laying out ten `'m'`+/// glyphs and dividing by 10 (`TerminalPainter._measureCharSize`), a hard+/// monospace assumption. A proportional font would misalign every column a+/// remote TUI draws regardless of how correctly resize is handled. Nothing here+/// needs Flutter to enumerate installed fonts (it can't) or risk a silent+/// substitution — every face named is one the OS it is offered on ships.+///+/// Which is why the list is per-platform ([available]). The first four are+/// stock macOS and resolve to nothing on Linux: fontconfig answers `Menlo` and+/// `.AppleSystemUIFontMonospaced` with the proportional Noto Sans, so all four+/// rendered the same broken grid there. The rest are the Ubuntu/Debian faces —+/// `Ubuntu Sans Mono` is the 25.04-and-later family and `Ubuntu Mono` the older+/// one, so both are listed rather than guessing the release.+///+/// Every value exists on every platform. A `state.json` written on a Mac and+/// carried to a Linux box still loads, and the Settings dropdown keeps showing+/// whatever is actually selected (see `_FamilyDropdown`).+enum TerminalFontChoice {+ sfMono('SF Mono', macTerminalFontFamily, macTerminalFontFallback),+ menlo('Menlo', 'Menlo', ['Monaco', 'Courier New', 'monospace']),+ monaco('Monaco', 'Monaco', ['Menlo', 'Courier New', 'monospace']),+ courierNew('Courier New', 'Courier New', ['Menlo', 'Monaco', 'monospace']),++ dejaVuSansMono(+ 'DejaVu Sans Mono',+ linuxTerminalFontFamily,+ linuxTerminalFontFallback,+ ),+ ubuntuSansMono('Ubuntu Sans Mono', 'Ubuntu Sans Mono', [+ 'Ubuntu Mono',+ 'DejaVu Sans Mono',+ 'Noto Sans Mono',+ 'monospace',+ ]),+ ubuntuMono('Ubuntu Mono', 'Ubuntu Mono', [+ 'Ubuntu Sans Mono',+ 'DejaVu Sans Mono',+ 'monospace',+ ]),+ liberationMono('Liberation Mono', 'Liberation Mono', [+ 'DejaVu Sans Mono',+ 'Noto Sans Mono',+ 'monospace',+ ]),+ notoSansMono('Noto Sans Mono', 'Noto Sans Mono', [+ 'DejaVu Sans Mono',+ 'Liberation Mono',+ 'monospace',+ ]);++ const TerminalFontChoice(+ this.label,+ this.fontFamily,+ this.fontFamilyFallback,+ );++ final String label;+ final String fontFamily;+ final List<String> fontFamilyFallback;++ static const _macChoices = [sfMono, menlo, monaco, courierNew];+ static const _linuxChoices = [+ dejaVuSansMono,+ ubuntuSansMono,+ ubuntuMono,+ liberationMono,+ notoSansMono,+ ];++ /// The faces worth offering on the host this build is running on.+ ///+ /// Windows falls in with Linux deliberately rather than with macOS: its+ /// runner is unexercised (see CLAUDE.md), and of the two lists the Linux one+ /// at least ends every fallback at the generic `monospace`, which Windows+ /// does resolve.+ static List<TerminalFontChoice> get available =>+ hasAppleFonts ? _macChoices : _linuxChoices;++ /// What a fresh install opens with, and what `reset()` returns to.+ static TerminalFontChoice get defaultForPlatform =>+ hasAppleFonts ? sfMono : dejaVuSansMono;+}++/// The user's chosen terminal typography (family + size), remembered across+/// launches.+///+/// A [ValueNotifier] singleton backed by [HarnessFileStore], loaded once in+/// `main()` before `runApp`.+///+/// The notifier's value IS the memoized [TerminalStyle], not a raw font/size+/// pair: [TerminalStyle] has no `==`/`hashCode` override, and the vendored+/// renderer's own setters (`RenderTerminal.textStyle`, `TerminalPainter+/// .textStyle`) short-circuit on `==`/identity before doing any work. A fresh+/// `TerminalStyle(...)` built on every widget rebuild would look like "the+/// font changed" every time and spuriously re-layout (and re-resize) the+/// terminal on every unrelated rebuild. [_styleFor] guarantees the same+/// (family, size) always returns the identical object, so both the renderer's+/// guard and [ValueNotifier]'s own "don't notify on a no-op set" work for+/// free.+class TerminalFontStore extends ValueNotifier<TerminalStyle> {+ TerminalFontStore({LocalKeyValueStore? storage})+ : _storage = storage ?? HarnessFileStore.shared,+ super(_styleFor(TerminalFontChoice.defaultForPlatform, terminalFontSize));++ static const _familyKey = 'terminal_font_family';+ static const _sizeKey = 'terminal_font_size';++ /// The bounds the size is held inside — public because the Settings stepper+ /// has to *show* them: a + that stays lit at 22pt is a control that answers a+ /// click by doing nothing.+ static const minSize = 9.0;+ static const maxSize = 22.0;+ static const _step = 1.0;++ final LocalKeyValueStore _storage;++ static final _cache = <(TerminalFontChoice, double), TerminalStyle>{};+ static TerminalStyle _styleFor(TerminalFontChoice choice, double size) =>+ _cache.putIfAbsent(+ (choice, size),+ () => TerminalStyle(+ fontSize: size,+ fontFamily: choice.fontFamily,+ fontFamilyFallback: choice.fontFamilyFallback,+ ),+ );++ TerminalFontChoice get family => TerminalFontChoice.values.firstWhere(+ (choice) => choice.fontFamily == value.fontFamily,+ orElse: () => TerminalFontChoice.defaultForPlatform,+ );++ double get size => value.fontSize;++ /// Read the saved choice, if there is one. Failure (or a stale/unknown+ /// family name from an older build) is silent and lands on the default —+ /// an unreadable state file is not a reason to refuse to start.+ Future<void> load() async {+ try {+ final saved = await _storage.readMany([_familyKey, _sizeKey]);+ final savedFamily = saved[_familyKey];+ final savedSize = saved[_sizeKey];+ final choice = TerminalFontChoice.values+ .where((c) => c.name == savedFamily)+ .firstOrNull;+ final size = savedSize == null ? null : double.tryParse(savedSize);+ value = _styleFor(+ choice ?? TerminalFontChoice.defaultForPlatform,+ _clamp(size ?? terminalFontSize),+ );+ } catch (_) {+ value = _styleFor(+ TerminalFontChoice.defaultForPlatform,+ terminalFontSize,+ );+ }+ }++ Future<void> setFamily(TerminalFontChoice choice) => _set(choice, size);++ Future<void> increaseSize() => _set(family, size + _step);+ Future<void> decreaseSize() => _set(family, size - _step);+ Future<void> setSize(double size) => _set(family, size);++ Future<void> reset() =>+ _set(TerminalFontChoice.defaultForPlatform, terminalFontSize);++ /// Whether the current pick *is* the default — what [reset] would leave the+ /// store at, so a Reset control can say it has nothing to do.+ bool get isDefault =>+ family == TerminalFontChoice.defaultForPlatform &&+ size == terminalFontSize;++ double _clamp(double size) => size.clamp(minSize, maxSize);++ Future<void> _set(TerminalFontChoice choice, double size) async {+ final next = _styleFor(choice, _clamp(size));+ if (next == value) return;+ value = next;+ try {+ await _storage.write(_familyKey, choice.name);+ await _storage.write(_sizeKey, next.fontSize.toString());+ } catch (_) {+ // Kept in memory for this run; see load()'s doc.+ }+ }+}++/// The one instance the app reads. Lives here rather than beside `main()`: the+/// widgets that read and write this (the terminal panel, the composer, the Settings+/// dialog, the account menu) must not have to reach into `main.dart` for it.+final terminalFontStore = TerminalFontStore();diff --git a/mobile/lib/terminal/terminal_input.dart b/mobile/lib/terminal/terminal_input.dartnew file mode 100644index 000000000..088fa9c99--- /dev/null+++ b/mobile/lib/terminal/terminal_input.dart@@ -0,0 +1,41 @@+import 'package:xterm/xterm.dart';++/// Makes ⌥⏎ a newline inside the engine's prompt instead of a submit.+///+/// Claude Code, Codex and every other Ink/readline prompt read Meta+Enter — `ESC` followed by the+/// ordinary Return bytes — as "add a line, do not send this turn yet". A real terminal produces+/// that only when it is configured to treat ⌥ as Meta (iTerm's "Esc+", Terminal.app's "Use Option+/// as Meta Key"); xterm.dart has no such setting, and its [AltInputHandler] deliberately does+/// nothing on macOS so ⌥ stays the compose key for `å`/`ø`/`¬`. So ⌥⏎ fell through to the keytab,+/// which matches on `Return` alone and answers `\r` — the submit. The key the shortcuts sheet+/// promises (`kTerminalOwnedKeys`) sent the turn instead of breaking the line.+///+/// ⌥ is Meta for THIS ONE KEY, not for the keyboard: Enter carries no character to compose, so+/// prefixing it costs nothing that ⌥-as-compose needs, and the rest of the alphabet is untouched.+///+/// The base bytes are asked of [_inner] rather than written out here, because Return is not always+/// `\r`: under LNM (`lineFeedMode`) the keytab answers `\r\n`, and a caller may pass a keytab of+/// its own. Alt and Shift are cleared for that question — Alt so the keytab does not see the very+/// modifier being translated, Shift so ⌥⇧⏎ yields a prefixed Return rather than a prefixed `\EOM`,+/// which no prompt would recognise.+class MetaEnterInputHandler implements TerminalInputHandler {+ const MetaEnterInputHandler(this._inner);++ final TerminalInputHandler _inner;++ @override+ String? call(TerminalKeyboardEvent event) {+ final isEnter =+ event.key == TerminalKey.enter || event.key == TerminalKey.numpadEnter;+ // Ctrl+Alt+Enter is left alone: that chord belongs to whatever is running, not to this.+ if (!isEnter || !event.alt || event.ctrl) return _inner(event);+ final base = _inner(event.copyWith(alt: false, shift: false));+ if (base == null) return null;+ return '\x1b$base';+ }+}++/// The handler every pane's [Terminal] is built with — xterm's default behaviour, plus ⌥⏎.+const TerminalInputHandler harnessInputHandler = MetaEnterInputHandler(+ defaultInputHandler,+);diff --git a/mobile/lib/terminal/terminal_link_opener.dart b/mobile/lib/terminal/terminal_link_opener.dartnew file mode 100644index 000000000..21d04a3ff--- /dev/null+++ b/mobile/lib/terminal/terminal_link_opener.dart@@ -0,0 +1,120 @@+import 'dart:io';++import 'package:url_launcher/url_launcher.dart';++import 'terminal_links.dart';+import 'remote_media_download.dart';++/// Uses the existing OS launcher, never a shell command built from agent text.+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) =>+ launchUrl(uri, mode: LaunchMode.externalApplication);+ static Future<bool> _exists(String path) => File(path).exists();++ /// 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 {+ if (RegExp(r'[\x00-\x1f\x7f]').hasMatch(target)) {+ return 'This link is not supported.';+ }+ try {+ final parsed = Uri.tryParse(target);+ if (parsed == null) return 'This link is not supported.';+ Uri uri;+ if (parsed.scheme == 'https' || parsed.scheme == 'http') {+ 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 (isCancelled?.call() == true) return null;+ if (!await _launch(uri)) {+ return 'Could not open this preview. Check that a default app is installed.';+ }+ return null;+ } on RemoteMediaCancelled {+ return null;+ } on RemoteMediaException catch (error) {+ return error.message;+ } catch (_) {+ return 'Could not open this preview. Check that the file is accessible and a default app is installed.';+ }+ }+}diff --git a/mobile/lib/terminal/terminal_links.dart b/mobile/lib/terminal/terminal_links.dartnew file mode 100644index 000000000..be6594d34--- /dev/null+++ b/mobile/lib/terminal/terminal_links.dart@@ -0,0 +1,394 @@+import 'package:xterm/xterm.dart';++const _mediaExtensions =+ r'png|jpe?g|gif|webp|avif|heic|heif|bmp|tiff?|svg|ico|'+ r'mp4|m4v|mov|webm|mkv|avi|mpe?g|ogv|3gp';+final _mediaSuffix = RegExp('\\.(?:$_mediaExtensions)\$', caseSensitive: false);+final _markdownLink = RegExp(+ r'!?\[[^\]\r\n]*\]\((<[^>\r\n]+>|(?:[^()\r\n]|\([^()\r\n]*\))+)\)',+);+final _quotedTarget = RegExp(+ r'''`([^`\r\n]+)`|"([^"\r\n]+)"|'([^'\r\n]+)'|<([^<>\r\n]+)>''',+);+final _webTarget = RegExp(r'''https?://[^\s<>`"']+''', caseSensitive: false);+final _absoluteMedia = RegExp(+ r'''(?:^|[\s(\[<='"`])((?:file://|~/|/(?!/)|[a-z]:[\\/]|\.{1,2}/)[^<>\r\n`"|]*?\.(?:''' ++ _mediaExtensions ++ r'''))(?=$|[\s)\]}>.,;:!?])''',+ caseSensitive: false,+);+final _relativeMedia = RegExp(+ r'''[^\s<>`"'()\[\]]+\.(?:''' ++ _mediaExtensions ++ r''')(?=$|[\s)\]}>.,;:!?])''',+ caseSensitive: false,+);++bool isMediaPath(String path) => _mediaSuffix.hasMatch(path);++bool _isTarget(String target) {+ final uri = Uri.tryParse(target);+ if (uri == null) return false;+ if (uri.scheme == 'http' || uri.scheme == 'https') {+ return uri.host.isNotEmpty;+ }+ if (uri.scheme == 'file') return isMediaPath(uri.path);+ // A drive letter is a file path, not a custom URI scheme.+ if (uri.hasScheme &&+ !RegExp(r'^[a-z]:[\\/]', caseSensitive: false).hasMatch(target)) {+ return false;+ }+ return isMediaPath(target);+}++String _trimWebPunctuation(String target) {+ var result = target.replaceFirst(RegExp(r'[.,;:!?]+$'), '');+ for (final pair in [('(', ')'), ('[', ']')]) {+ while (result.endsWith(pair.$2) &&+ pair.$2.allMatches(result).length > pair.$1.allMatches(result).length) {+ result = result.substring(0, result.length - 1);+ }+ }+ return result;+}++/// Finds only the target under the pointer. No file IO or scan of scrollback.+/// Markdown labels and quoted paths retain spaces; bare URLs retain queries.+String? terminalLinkInText(String text, int offset) {+ if (offset < 0 || offset >= text.length) return null;+ for (final match in _markdownLink.allMatches(text)) {+ if (offset < match.start || offset >= match.end) continue;+ var target = match[1]!;+ if (target.startsWith('<') && target.endsWith('>')) {+ target = target.substring(1, target.length - 1);+ }+ return _isTarget(target) ? target : null;+ }+ for (final match in _quotedTarget.allMatches(text)) {+ if (offset < match.start || offset >= match.end) continue;+ final target = [+ match[1],+ match[2],+ match[3],+ match[4],+ ].whereType<String>().single;+ if (_isTarget(target)) return target;+ }+ for (final match in _webTarget.allMatches(text)) {+ if (offset < match.start || offset >= match.end) continue;+ final target = _trimWebPunctuation(match[0]!);+ return offset < match.start + target.length && _isTarget(target)+ ? target+ : null;+ }+ for (final pattern in [_absoluteMedia, _relativeMedia]) {+ for (final match in pattern.allMatches(text)) {+ final target = match.groupCount == 0 ? match[0]! : match[1]!;+ final start = match.end - target.length;+ if (offset >= start && offset < match.end && _isTarget(target)) {+ return target;+ }+ }+ }+ return null;+}++/// One logical line: a run of soft-wrapped rows, as the text they spell.+class _LogicalLine {+ final int firstRow;+ final int lastRow;+ final String text;++ /// The [_styleKey] of the cell each UTF-16 unit of [text] came from.+ final List<int> styles;++ /// UTF-16 offset of the target cell in [text], when the cell is on this line.+ final int? offset;++ const _LogicalLine(+ this.firstRow,+ this.lastRow,+ this.text,+ this.styles,+ this.offset,+ );++ int get leadingBlanks => text.length - text.trimLeft().length;++ /// Offset of the last character that is not a blank, or -1 on a blank line.+ int get lastVisible => text.trimRight().length - 1;+}++/// What makes a run of cells read as one thing: its colour and whether it is+/// underlined. Claude Code paints an address bright blue and carries that+/// paint onto the row it cut the address across, while the words around it+/// are plain — the one witness to the cut that survives the newline.+int _styleKey(BufferLine line, int x) =>+ (line.getForeground(x) << 1) |+ (line.getAttributes(x) & CellAttr.underline != 0 ? 1 : 0);++bool _underlined(int styleKey) => styleKey & 1 != 0;++/// Reconstructs the logical line through row [y] across terminal soft wraps,+/// mapping cell columns to UTF-16 offsets (wide CJK and emoji are not one code+/// unit). The bound also keeps malformed/unbroken output cheap during mouse+/// hover. [cell] is the pointer, whose offset is reported when it lands here.+_LogicalLine? _logicalLine(Terminal terminal, int y, CellOffset cell) {+ final lines = terminal.buffer.lines;+ var start = y;+ var end = y;+ while (start > 0 && lines[start].isWrapped) {+ if (y - start >= 16) return null;+ start--;+ }+ while (end + 1 < lines.length && lines[end + 1].isWrapped) {+ if (end - start >= 16) return null;+ end++;+ }+ final text = StringBuffer();+ final styles = <int>[];+ int? offset;+ for (var row = start; row <= end; row++) {+ final line = lines[row];+ var previousOffset = text.length;+ for (var x = 0; x < line.length; x++) {+ final continuation = x > 0 && line.getWidth(x - 1) == 2;+ if (cell.y == row && cell.x == x) {+ offset = continuation ? previousOffset : text.length;+ }+ if (continuation) continue;+ previousOffset = text.length;+ final codePoint = line.getCodePoint(x);+ text.writeCharCode(codePoint == 0 ? 0x20 : codePoint);+ if (text.length > 8192) return null;+ final style = _styleKey(line, x);+ while (styles.length < text.length) {+ styles.add(style);+ }+ }+ }+ return _LogicalLine(start, end, text.toString(), styles, offset);+}++/// Columns up to the last cell that is neither empty nor a space — the width+/// a row was wrapped at. Spaces after it say nothing: Claude Code pads some+/// rows (its prompt box, a list item) to the full width with them, tmux+/// repaints with them, and the cut row of a URL carries them as often as not+/// — a capture of the real thing showed both `…commandcode.ai/` at the last+/// column and `…0xkongamoto/ ` one space short of it, each followed by the+/// rest of the address on the next row.+int _visibleWidth(BufferLine line) {+ for (var x = line.length - 1; x >= 0; x--) {+ final codePoint = line.getCodePoint(x);+ if (codePoint != 0 && codePoint != 0x20) return x + line.getWidth(x);+ }+ return 0;+}++/// The widest row of the paragraph (contiguous non-blank rows) around [row].+int _paragraphWidth(Terminal terminal, int row) {+ final lines = terminal.buffer.lines;+ var widest = _visibleWidth(lines[row]);+ for (final step in [-1, 1]) {+ for (var y = row + step, seen = 0; y >= 0 && y < lines.length; y += step) {+ final width = _visibleWidth(lines[y]);+ if (width == 0 || seen++ >= _hardWrapRows * 2) break;+ if (width > widest) widest = width;+ }+ }+ return widest;+}++final _trailingWebTarget = RegExp(+ r'''https?://[^\s<>`"']+$''',+ caseSensitive: false,+);+// The rest of an address begins with a character an address can contain —+// and a lone dash or a `1.` is a list marker, not that.+final _continuationToken = RegExp(+ r'''^(?:[A-Za-z0-9]|[/._~%?#=&+-](?=[^\s<>`"']))[^\s<>`"']*''',+);+final _listMarker = RegExp(r'^\d+[.)]$');+final _webScheme = RegExp(r'^https?://', caseSensitive: false);++/// How many hard-wrapped rows one URL may span before giving up on it.+const _hardWrapRows = 8;++/// A cut row is as wide as the widest row of its paragraph — a hard cut fills+/// the box exactly, a word wrap leaves it short (measured per paragraph+/// because a full-width `────` divider is its own paragraph). The fallback+/// witness, for output that does not paint its addresses.+bool _cutAtBoxWidth(Terminal terminal, _LogicalLine line) {+ final width = _visibleWidth(terminal.buffer.lines[line.lastRow]);+ return width > 0 && width >= _paragraphWidth(terminal, line.lastRow);+}++/// Whether the paint on the last character of [a] runs on into the first+/// token of [b] — the cut address carrying its colour across the newline.+bool _paintContinues(_LogicalLine a, _LogicalLine b) =>+ a.lastVisible >= 0 &&+ b.leadingBlanks < b.text.length &&+ a.styles[a.lastVisible] == b.styles[b.leadingBlanks];++/// Length of the row's first token, after the indent.+int _tokenLength(_LogicalLine line) =>+ _continuationToken.firstMatch(line.text.trimLeft())?[0]!.length ?? 0;++/// A row that is one token from its indent to its end — what a row in the+/// middle of a cut address looks like, and what a tail row may look like.+bool _singleToken(_LogicalLine line) {+ final text = line.text.trim();+ return text.isNotEmpty && !text.contains(RegExp(r'\s'));+}++/// The next row's first token is URL characters that do not start a URL of+/// their own. Ink indents a list item's continuation deeper than its bullet,+/// so the indent is not compared.+bool _continuesUrl(_LogicalLine line) {+ final token = _continuationToken.firstMatch(line.text.trimLeft())?[0];+ return token != null &&+ !_webScheme.hasMatch(token) &&+ !_listMarker.hasMatch(token);+}++/// Where [text] (rows spliced so far) breaks off inside a web URL: the offset+/// the address starts at, or null. An address that closes a bracket it never+/// opened — `(https://a.example/)` at the end of a row — is finished, not cut.+int? _urlCutAt(String text) {+ final trimmed = text.trimRight();+ final match = _trailingWebTarget.firstMatch(trimmed);+ if (match == null || !_isTarget(match[0]!)) return null;+ final raw = match[0]!.replaceFirst(RegExp(r'[.,;:!?]+$'), '');+ for (final pair in [('(', ')'), ('[', ']')]) {+ if (raw.endsWith(pair.$2) &&+ pair.$2.allMatches(raw).length > pair.$1.allMatches(raw).length) {+ return null;+ }+ }+ return match.start;+}++/// The cut rows spliced back together without the box indent that follows+/// each break, or the blank cells that precede it, with the pointer's offset+/// in the result when [own] is given. Null when the pointer sat on blanks the+/// splice removed — not on the URL — or the run is absurdly long.+(String, int?)? _splice(List<_LogicalLine> joined, _LogicalLine? own) {+ final text = StringBuffer();+ int? offset;+ for (final line in joined) {+ final stripped = identical(line, joined.first) ? 0 : line.leadingBlanks;+ final segment = identical(line, joined.last)+ ? line.text.substring(stripped)+ : line.text.substring(stripped).trimRight();+ if (own != null && identical(line, own)) {+ final at = own.offset! - stripped;+ if (at < 0 || at >= segment.length) return null;+ offset = text.length + at;+ }+ text.write(segment);+ if (text.length > 8192) return null;+ }+ return (text.toString(), offset);+}++/// Whether every break in [joined] is a cut, judged by the witness the head+/// row offers. An address painted differently from the words before it is+/// followed by its paint: each next row must open in the same paint, and a+/// row that opens in plain text is the next sentence, however wide the row+/// above was. An address in the same paint as its sentence has only the box+/// width to go on.+bool _cutThroughout(Terminal terminal, List<_LogicalLine> joined) {+ final head = joined.first;+ final urlStart = _urlCutAt(head.text);+ if (urlStart == null) return false;+ final urlStyle = head.styles[head.lastVisible];+ var before = urlStart - 1;+ while (before >= 0 && head.text[before] == ' ') {+ before--;+ }+ final painted = before >= 0+ ? head.styles[before] != urlStyle+ : _underlined(urlStyle) || urlStyle != head.styles[0];+ for (var i = 0; i + 1 < joined.length; i++) {+ final cut = painted+ ? _paintContinues(joined[i], joined[i + 1])+ : _cutAtBoxWidth(terminal, joined[i]);+ if (!cut) return false;+ }+ return true;+}++/// Finds the target under [cell]. A web URL that the program on the other end+/// hard-wrapped across rows is read whole, from whichever row the pointer is+/// on; everything else is confined to the logical line, as separate output+/// lines are separate things (a path is never assembled from two of them).+///+/// A TUI cuts a long address at its box width and carries the rest onto the+/// next row with its own newline — what Claude Code (Ink, `wrap-ansi` with+/// `hard: true`) does. A terminal soft wrap is already joined by+/// [_logicalLine]; this is the break it cannot see, and it is inferred: from+/// the paint on the address when there is any, else from the row's width.+String? terminalLinkAt(Terminal terminal, CellOffset cell) {+ final lines = terminal.buffer.lines;+ if (cell.y < 0 ||+ cell.y >= lines.length ||+ cell.x < 0 ||+ cell.x >= lines[cell.y].length) {+ return null;+ }+ final own = _logicalLine(terminal, cell.y, cell);+ if (own == null || own.offset == null) return null;+ final single = terminalLinkInText(own.text, own.offset!);++ // Which way the rest of the address lies is read off the pointer: on the+ // row's opening token it may be a carried tail, so look above; on an+ // address the row breaks off in, look below. A row that is one token from+ // indent to end may be the middle of one, and is followed both ways.+ bool mayJoin(_LogicalLine a, _LogicalLine b) =>+ _continuesUrl(b) &&+ (_paintContinues(a, b) || _cutAtBoxWidth(terminal, a));++ final joined = [own];+ final at = own.offset!;+ final cutAt = _urlCutAt(own.text);+ final onOpeningToken =+ at >= own.leadingBlanks && at < own.leadingBlanks + _tokenLength(own);+ if (onOpeningToken && _continuesUrl(own)) {+ while (joined.first.firstRow > 0 && joined.length < _hardWrapRows) {+ final previous = _logicalLine(terminal, joined.first.firstRow - 1, cell);+ if (previous == null || !mayJoin(previous, joined.first)) break;+ // Above a carried row sits either the row the address starts on or+ // another row of nothing but address; anything else ends the search.+ final head = _urlCutAt(previous.text) != null;+ if (!head && !_singleToken(previous)) break;+ joined.insert(0, previous);+ if (head) break;+ }+ }+ if ((cutAt != null && at >= cutAt) || _singleToken(own)) {+ while (joined.last.lastRow + 1 < lines.length) {+ final next = _logicalLine(terminal, joined.last.lastRow + 1, cell);+ if (next == null ||+ !mayJoin(joined.last, next) ||+ _urlCutAt(_splice(joined, null)?.$1 ?? '') == null) {+ break;+ }+ // Past the bound the address is unknowable, and a fragment of it would+ // open the wrong page — no link is the honest answer.+ if (joined.length >= _hardWrapRows) return null;+ joined.add(next);+ // The row the address ends on has words after it; nothing follows.+ if (!_singleToken(next)) break;+ }+ }+ if (joined.length == 1 || !_cutThroughout(terminal, joined)) return single;++ final spliced = _splice(joined, own);+ if (spliced == null) return single;+ final (text, offset) = spliced;+ if (offset == null) return single;+ final target = terminalLinkInText(text, offset);+ if (target == null) return single;+ final scheme = Uri.tryParse(target)?.scheme;+ return scheme == 'http' || scheme == 'https' ? target : single;+}diff --git a/mobile/lib/terminal/terminal_search.dart b/mobile/lib/terminal/terminal_search.dartnew file mode 100644index 000000000..d12cd006d--- /dev/null+++ b/mobile/lib/terminal/terminal_search.dart@@ -0,0 +1,448 @@+import 'dart:async';+import 'dart:collection';+import 'dart:typed_data';++import 'package:flutter/foundation.dart';+import 'package:xterm/xterm.dart';++/// An on-demand index of the current terminal buffer. It never reads a file,+/// queries a daemon, or sends input. Unchanged rows keep their decoded text;+/// long scans yield to the event loop, and only the selected hit owns an anchor.+class TerminalSearch extends ChangeNotifier {+ TerminalSearch(this.terminal, {CellOffset? origin}) {+ _origin = origin;+ }++ final Terminal terminal;+ String _query = '';+ bool _caseSensitive = false;+ bool _enabled = true;+ bool _disposed = false;+ bool _listening = false;+ bool _running = false;+ bool _dirty = false;+ int _generation = 0;+ int _indexedGeneration = -1;+ int _pendingStep = 0;+ Timer? _timer;+ Timer? _yieldTimer;+ Completer<void>? _yieldResume;+ Completer<void>? _settled;+ Buffer? _buffer;+ CellOffset? _origin;+ CellAnchor? _selectionAnchor;+ Map<BufferLine, _SearchLine> _lines = HashMap.identity();+ Map<BufferLine, _SearchGroup> _cache = HashMap.identity();+ List<_SearchGroup> _groups = [];+ int _count = 0;+ int _selected = -1;+ _SearchGroup? _selectedGroup;+ int _selectedInGroup = 0;++ String get query => _query;+ bool get caseSensitive => _caseSensitive;+ bool get searching => _running || _dirty || _timer != null;+ bool get hasSnapshot =>+ _indexedGeneration == _generation && identical(_buffer, terminal.buffer);+ int get count => _count;+ int get selected => _selected;+ Future<void> get settled => _settled?.future ?? Future.value();++ BufferRangeLine? get match =>+ identical(_buffer, terminal.buffer) && _selectedGroup?.valid == true+ ? _selectedGroup!.rangeAt(_selectedInGroup)+ : null;++ void setQuery(String value, {bool? caseSensitive}) {+ final sensitive = caseSensitive ?? _caseSensitive;+ if (_query == value && _caseSensitive == sensitive) return;+ _query = value;+ _caseSensitive = sensitive;+ _generation++;+ _pendingStep = 0;+ _clearResults();+ _listen(_enabled && _query.isNotEmpty);+ if (_query.isEmpty) {+ _releaseIndex();+ } else {+ _request();+ }+ notifyListeners();+ }++ /// Hidden/covered find bars retain only their query and selected location.+ /// Returning rebuilds from current output instead of indexing hidden traffic.+ void setEnabled(bool value) {+ if (_enabled == value || _disposed) return;+ _enabled = value;+ _generation++;+ _listen(value && _query.isNotEmpty);+ if (value) {+ _request();+ } else {+ _releaseIndex();+ }+ }++ void _listen(bool value) {+ if (_listening == value) return;+ _listening = value;+ if (value) {+ terminal.addListener(_onOutput);+ terminal.addResizeListener(_onResize);+ } else {+ terminal.removeListener(_onOutput);+ terminal.removeResizeListener(_onResize);+ }+ }++ void _onOutput() {+ _request();+ // Output can replace the active buffer or overwrite a highlighted row.+ // Let the view remove an invalid highlight before its next paint.+ notifyListeners();+ }++ // Resize runs during renderer layout. Defer UI notifications to the scan's+ // event-loop turn so reflow never calls setState during layout.+ void _onResize() => _request();++ void _request() {+ if (_disposed || !_enabled || _query.isEmpty) return;+ _dirty = true;+ _settled ??= Completer<void>();+ if (!_running) _timer ??= Timer(Duration.zero, () => unawaited(_scan()));+ }++ Future<void> _scan() async {+ _timer = null;+ if (_disposed || !_enabled || _query.isEmpty) return;+ _running = true;+ _dirty = false;+ final generation = _generation;+ final buffer = terminal.buffer;+ final query = _query;+ final sensitive = _caseSensitive;+ final pattern = RegExp(+ RegExp.escape(query),+ caseSensitive: sensitive,+ unicode: true,+ );+ final source = [+ for (var i = 0; i < buffer.lines.length; i++) buffer.lines[i],+ ];+ final lines = HashMap<BufferLine, _SearchLine>.identity();+ final cache = HashMap<BufferLine, _SearchGroup>.identity();+ final groups = <_SearchGroup>[];+ var logical = <_SearchLine>[];+ final slice = Stopwatch()..start();+ try {+ for (var i = 0; i < source.length; i++) {+ final line = source[i];+ final cached = _lines[line];+ final snapshot = cached != null && cached.valid+ ? cached+ : _SearchLine(line);+ lines[line] = snapshot;+ logical.add(snapshot);+ if (i + 1 == source.length || !source[i + 1].isWrapped) {+ final first = logical.first.line;+ final previous = _cache[first];+ final _SearchGroup group;+ if (previous != null && previous.reuses(logical, query, sensitive)) {+ group = previous;+ } else {+ final text = logical.length == 1+ ? logical.single.text+ : logical.map((line) => line.text).join();+ final checkpoints = <int>[];+ var hits = 0;+ for (final hit in pattern.allMatches(text)) {+ if (hits % _SearchGroup.stride == 0) checkpoints.add(hit.start);+ hits++;+ if (hits % 128 == 0 && slice.elapsedMicroseconds >= 1500) {+ await _yieldScan();+ if (_disposed || generation != _generation || !_enabled) return;+ slice.reset();+ }+ }+ group = _SearchGroup(+ logical,+ query,+ sensitive,+ pattern,+ text,+ Uint32List.fromList(checkpoints),+ hits,+ );+ }+ cache[first] = group;+ if (group.count > 0 && group.valid) groups.add(group);+ logical = [];+ }+ if (slice.elapsedMicroseconds >= 1500) {+ await _yieldScan();+ if (_disposed || generation != _generation || !_enabled) return;+ slice.reset();+ }+ }+ if (_disposed || generation != _generation || !_enabled) return;+ _lines = lines;+ _cache = cache;+ _buffer = buffer;+ _indexedGeneration = generation;+ _groups = groups.where((group) => group.valid).toList(growable: false);+ _count = _groups.fold(0, (count, group) => count + group.count);+ final origin = _selectionAnchor?.attached == true+ ? _selectionAnchor!.offset+ : _origin;+ var index = 0;+ var found = false;+ if (origin != null) {+ for (final group in _groups) {+ if (group.lines.last.line.index < origin.y) {+ index += group.count;+ continue;+ }+ final hit = group.indexAtOrAfter(origin);+ index += hit;+ if (hit < group.count) {+ found = true;+ break;+ }+ }+ }+ _select(_count == 0 ? -1 : ((found ? index : 0) + _pendingStep) % _count);+ _pendingStep = 0;+ } finally {+ _running = false;+ if (!_disposed) {+ if (_dirty && _enabled && _query.isNotEmpty) {+ _request();+ } else {+ _settled?.complete();+ _settled = null;+ }+ notifyListeners();+ }+ }+ }++ void step(int delta) {+ if (_query.isEmpty || !_enabled) return;+ if (searching && !hasSnapshot) {+ _pendingStep += delta;+ return;+ }+ if (_count == 0) return;+ final target = (_selected + delta) % _count;+ var index = target;+ for (final group in _groups) {+ if (index < group.count) {+ if (!group.valid) {+ _pendingStep += delta;+ _request();+ return;+ }+ break;+ }+ index -= group.count;+ }+ _select(target);+ notifyListeners();+ }++ void _select(int index) {+ _selected = index;+ _selectedGroup = null;+ if (index < 0) return;+ for (final group in _groups) {+ if (index >= group.count) {+ index -= group.count;+ continue;+ }+ _selectedGroup = group;+ _selectedInGroup = index;+ final range = match;+ if (range != null) {+ _selectionAnchor?.dispose();+ _selectionAnchor = terminal.buffer.createAnchorFromOffset(range.begin);+ _origin = range.begin;+ }+ break;+ }+ }++ void _clearResults() {+ _groups = [];+ _count = 0;+ _selected = -1;+ _selectedGroup = null;+ }++ Future<void> _yieldScan() {+ final resume = Completer<void>();+ _yieldResume = resume;+ _yieldTimer = Timer(Duration.zero, () {+ _yieldTimer = null;+ _yieldResume = null;+ resume.complete();+ });+ return resume.future;+ }++ void _releaseIndex() {+ _yieldTimer?.cancel();+ _yieldTimer = null;+ final resume = _yieldResume;+ _yieldResume = null;+ resume?.complete();+ _timer?.cancel();+ _timer = null;+ _dirty = false;+ _lines.clear();+ _cache.clear();+ _clearResults();+ if (!_running) {+ _settled?.complete();+ _settled = null;+ }+ }++ @override+ void dispose() {+ _disposed = true;+ _generation++;+ _listen(false);+ _releaseIndex();+ _selectionAnchor?.dispose();+ _selectionAnchor = null;+ _settled?.complete();+ _settled = null;+ super.dispose();+ }+}++class _SearchLine {+ _SearchLine(this.line)+ : version = line.textVersion,+ wrapped = line.isWrapped,+ text = line.getText();+ final BufferLine line;+ final int version;+ final bool wrapped;+ final String text;+ bool get valid =>+ line.attached && line.textVersion == version && line.isWrapped == wrapped;++ int cellAt(int offset) {+ if (offset <= 0) return 0;+ var chars = 0;+ var end = 0;+ for (var x = 0; x < line.length; x++) {+ final code = line.getCodePoint(x);+ if (code == 0 && x > 0 && line.getWidth(x - 1) == 2) continue;+ chars += code > 0xffff ? 2 : 1;+ end = x + (line.getWidth(x) > 1 ? line.getWidth(x) : 1);+ if (chars >= offset) break;+ }+ return end;+ }+}++class _SearchGroup {+ _SearchGroup(+ this.lines,+ this.query,+ this.sensitive,+ this.pattern,+ this.text,+ this.checkpoints,+ this.count,+ ) {+ var offset = 0;+ starts = [+ for (final line in lines) (offset += line.text.length) - line.text.length,+ ];+ }+ // One integer per 64 matches, rather than a range/anchor for every character+ // in a very repetitive log. Selecting a hit examines at most 64 candidates.+ static const stride = 64;+ final List<_SearchLine> lines;+ final String query;+ final bool sensitive;+ final RegExp pattern;+ final String text;+ final Uint32List checkpoints;+ final int count;+ late final List<int> starts;+ bool get valid {+ for (var i = 0; i < lines.length; i++) {+ if (!lines[i].valid ||+ (i > 0 && lines[i].line.index != lines[i - 1].line.index + 1)) {+ return false;+ }+ }+ return true;+ }++ bool reuses(List<_SearchLine> other, String value, bool caseSensitive) =>+ query == value && sensitive == caseSensitive && listEquals(lines, other);++ int indexAtOrAfter(CellOffset origin) {+ var row = 0;+ while (row < lines.length && lines[row].line.index < origin.y) {+ row++;+ }+ if (row == lines.length) return count;+ final textOffset =+ starts[row] ++ (lines[row].line.index == origin.y+ ? lines[row].line.getText(0, origin.x).length+ : 0);+ var low = 0;+ var high = checkpoints.length - 1;+ while (low < high) {+ final middle = (low + high + 1) ~/ 2;+ if (checkpoints[middle] <= textOffset) {+ low = middle;+ } else {+ high = middle - 1;+ }+ }+ var index = low * stride;+ for (final hit in pattern.allMatches(text, checkpoints[low])) {+ if (hit.start >= textOffset) return index;+ index++;+ }+ return count;+ }++ BufferRangeLine rangeAt(int index) {+ final hit = pattern+ .allMatches(text, checkpoints[index ~/ stride])+ .skip(index % stride)+ .first;+ return BufferRangeLine(+ _cellAt(hit.start, end: false),+ _cellAt(hit.end, end: true),+ );+ }++ CellOffset _cellAt(int offset, {required bool end}) {+ var low = 0;+ var high = lines.length - 1;+ while (low < high) {+ final middle = (low + high + 1) ~/ 2;+ if (starts[middle] < offset || (!end && starts[middle] == offset)) {+ low = middle;+ } else {+ high = middle - 1;+ }+ }+ return CellOffset(+ lines[low].cellAt(offset - starts[low]),+ lines[low].line.index,+ );+ }+}diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dartnew file mode 100644index 000000000..12b7c5618--- /dev/null+++ b/mobile/lib/terminal/terminal_session.dart@@ -0,0 +1,1443 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:math';++import 'package:flutter/foundation.dart';+import 'package:xterm/xterm.dart';++import '../core/crash_log.dart';+import 'terminal_binary.dart';+import 'terminal_input.dart';+import 'terminal_viewport.dart';++typedef TerminalFrameSender = Future<bool> Function(+ String type,+ Map<String, dynamic> payload,+);+typedef TerminalBinarySender = Future<bool> Function(TerminalBinaryFrame frame);++enum TerminalSessionStatus {+ closed,+ opening,+ controlling,+ resyncing,+ takenOver,+ error,+}++/// Transient progress for an in-flight [TerminalSession.pasteImage]/[TerminalSession.pasteFile]+/// chunked upload. `bytesWritten` reflects the daemon's own per-chunk ACKs, not bytes merely handed+/// to the local socket.+class UploadProgress {+ const UploadProgress({+ required this.label,+ required this.bytesWritten,+ required this.totalBytes,+ });++ /// The image/file name shown in the overlay — a filename for a file upload, a generic word for+ /// an image (which carries no name of its own).+ final String label;+ final int bytesWritten;+ final int totalBytes;++ double get percent =>+ totalBytes <= 0 ? 0 : (bytesWritten / totalBytes).clamp(0, 1);++ UploadProgress copyWith({int? bytesWritten, int? totalBytes}) =>+ UploadProgress(+ label: label,+ bytesWritten: bytesWritten ?? this.bytesWritten,+ totalBytes: totalBytes ?? this.totalBytes,+ );+}++/// Internal bookkeeping for one in-flight upload — see [TerminalSession._uploadBytes]. Two+/// Completers rather than one, since "the daemon accepted the announcement" and "the transfer is+/// over (however it ended)" are resolved at different points and by different frames.+class _ActiveUpload {+ final Completer<bool> beginAccepted = Completer<bool>();+ final Completer<bool> finished = Completer<bool>();+}++/// One controller stream for one remote Harness agent.+///+/// Sequence corruption is recovered with bounded resync retries and one clean+/// reopen. Transport loss still freezes input until the user opens a session.+class TerminalSession extends ChangeNotifier {+ static const protocolVersion = 3;+ static const minCols = 40;+ static const maxCols = 300;+ static const minRows = 12;+ static const maxRows = 120;++ final String machineId;+ final String agentId;+ String agentName;+ final String? engineId;+ final TerminalFrameSender send;+ final TerminalBinarySender sendBinary;+ final Duration resyncTimeout;++ /// Forces a fresh transport dial (see `WsConn.forceReconnect`) — called once when the very first+ /// `terminal_open` never gets a `terminal_ready` back within [resyncTimeout]. Covers the relay+ /// going stale silently (the relayed machine's own Harness process restarted, dropping its E2EE+ /// session without the transport ever closing) so a reconnect looks like a couple of extra seconds+ /// of "attaching" instead of a hang the user has to notice and manually retry.+ final Future<void> Function()? onOpenStalled;++ TerminalSession({+ required this.machineId,+ required this.agentId,+ required this.agentName,+ required this.engineId,+ required this.send,+ required this.sendBinary,+ this.onOpenStalled,+ this.resyncTimeout = const Duration(seconds: 4),+ }) {+ terminal = _newTerminal();+ }++ late Terminal terminal;+ TerminalSessionStatus status = TerminalSessionStatus.closed;+ String? streamId;++ /// How this pane's terminal bytes are currently reaching it — one of:+ ///+ /// 'p2p' direct WebRTC, ICE nominated a direct candidate pair.+ /// 'turn' WebRTC too, but ICE could only manage a relay pair, so Cloudflare TURN carries it.+ /// 'relay' no data channel at all; the bytes ride the backend WebSocket.+ ///+ /// Only ever set for a `harness link connect`-linked remote machine (the CLI never sends this frame+ /// for a local machine's own terminal, which has no such distinction), and reset alongside [streamId]+ /// so a stale mode can never survive into the next stream.+ String? linkMode;+ String? errorCode;+ String? errorMessage;+ int cols = 80;+ int rows = 24;++ /// Set while an image/file upload is in flight ([pasteImage]/[pasteFile]); `null` otherwise. The+ /// terminal panel's overlay shows a progress pill exactly when this is non-null.+ UploadProgress? uploadProgress;+ _ActiveUpload? _activeUpload;++ String? _openRequestId;+ int? _expectedSeq;+ int _lastRenderedSeq = -1;+ int _framesSinceAck = 0;+ int _renderedSinceAckBytes = 0;+ int _inputSeq = 0;++ /// The last `expectedSeq` a TERMINAL_INPUT_INVALID realigned the counter to.+ /// The daemon refuses every in-flight frame it cannot accept, each naming+ /// the SAME expected seq; only the first of those may rewind the counter,+ /// or frames accepted since would be re-sent under numbers already used.+ int? _lastRealignedTo;+ int _resizeSeq = 0;+ bool _resyncRequested = false;+ int _resyncAttempts = 0;+ int _autoReopenAttempts = 0;+ bool _openStallRecovered = false;+ bool _disposed = false;+ int _generation = 0;+ bool _remoteCursorVisible = true;+ bool _cursorBlinkPhaseVisible = true;+ List<int> _utf8Tail = const [];+ final List<int> _inputBytes = [];+ Timer? _heartbeat;+ Timer? _ackTimer;+ Timer? _inputTimer;+ Timer? _resizeTimer;+ DateTime? _lastInputFlushAt;+ DateTime? _lastResizeFlushAt;+ Timer? _resyncTimer;+ Timer? _scrollTimer;+ bool? _pendingScrollUp;+ int _pendingScrollLines = 0;+ int? _pendingCols;+ int? _pendingRows;+ TerminalViewport? _viewport;+ ({int cols, int rows})? _measuredViewport;+ final Completer<({int cols, int rows})> _viewportSize = Completer();+ Future<void> _renderTail = Future<void>.value();+ Future<void> _inputSendTail = Future<void>.value();++ bool get acceptsInput =>+ status == TerminalSessionStatus.controlling && streamId != null;++ /// Grok's CLI declares terminal mouse-tracking (so tmux defers wheel bytes to it, same as any+ /// alt-buffer program) but doesn't correctly handle wheel reports itself — confirmed live: it+ /// echoes the raw SGR escape bytes into its own prompt as literal characters instead of+ /// scrolling. Its alt-buffer scroll gestures route through the daemon's tmux copy-mode+ /// (`sendScrollCommand`/`terminal_scroll`) instead of the raw `mouseInput` path every other+ /// engine already uses correctly.+ bool get scrollViaTmuxCopyMode => engineId == 'grok';++ void renameAgent(String name) {+ final cleanName = name.trim();+ if (cleanName.isEmpty || cleanName == agentName) return;+ agentName = cleanName;+ notifyListeners();+ }++ Future<void> open({+ int initialCols = 80,+ int initialRows = 24,+ bool waitForViewportSize = false,+ }) => _open(+ initialCols: initialCols,+ initialRows: initialRows,+ waitForViewportSize: waitForViewportSize,+ resetRecovery: true,+ preserveTerminal: false,+ );++ /// Reconnect the same agent without discarding its last usable screen.+ /// Input resumes only after the replacement stream's first keyframe.+ Future<void> reopen() async {+ if (_disposed ||+ status == TerminalSessionStatus.opening ||+ status == TerminalSessionStatus.controlling ||+ status == TerminalSessionStatus.resyncing) {+ return;+ }+ await _open(+ initialCols: _measuredViewport?.cols ?? cols,+ initialRows: _measuredViewport?.rows ?? rows,+ waitForViewportSize: false,+ resetRecovery: true,+ preserveTerminal: true,+ );+ }++ bool _isCurrent(int generation) => !_disposed && generation == _generation;++ Future<void> _open({+ required int initialCols,+ required int initialRows,+ required bool waitForViewportSize,+ required bool resetRecovery,+ required bool preserveTerminal,+ }) async {+ if (_disposed) return;+ final generation = ++_generation;+ _cancelTimers();+ _abortActiveUpload();+ _inputBytes.clear();+ _pendingScrollUp = null;+ _pendingScrollLines = 0;+ _lastInputFlushAt = null;+ _lastResizeFlushAt = null;+ _renderTail = Future<void>.value();+ _inputSendTail = Future<void>.value();+ streamId = null;+ linkMode = null;+ errorCode = null;+ errorMessage = null;+ _expectedSeq = null;+ _lastRenderedSeq = -1;+ _framesSinceAck = 0;+ _renderedSinceAckBytes = 0;+ _inputSeq = 0;+ _lastRealignedTo = null;+ _resizeSeq = 0;+ _utf8Tail = const [];+ _remoteCursorVisible = true;+ _cursorBlinkPhaseVisible = true;+ _resyncRequested = false;+ _resyncAttempts = 0;+ if (resetRecovery) {+ _autoReopenAttempts = 0;+ _openStallRecovered = false;+ }+ cols = _clampCols(initialCols);+ rows = _clampRows(initialRows);+ if (!preserveTerminal) terminal = _newTerminal()..resize(cols, rows);+ status = TerminalSessionStatus.opening;+ _openRequestId =+ 'term_${DateTime.now().microsecondsSinceEpoch}_${Random.secure().nextInt(1 << 31)}';+ notifyListeners();++ if (waitForViewportSize) {+ try {+ final measured = await _viewportSize.future.timeout(+ const Duration(seconds: 2),+ );+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening) {+ return;+ }+ cols = _clampCols(measured.cols);+ rows = _clampRows(measured.rows);+ if (!preserveTerminal) terminal.resize(cols, rows);+ notifyListeners();+ } on TimeoutException {+ // Keep the conservative fallback when the terminal viewport cannot be+ // measured; the normal resize path will reconcile it after attach.+ }+ }++ if (!_isCurrent(generation) || status != TerminalSessionStatus.opening) {+ return;+ }++ final openPayload = {+ 'protocolVersion': protocolVersion,+ 'requestId': _openRequestId,+ 'agentId': agentId,+ 'cols': cols,+ 'rows': rows,+ 'compression': const ['zlib', 'none'],+ };+ var sent = await send('terminal_open', openPayload);+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening ||+ streamId != null) {+ return;+ }+ if (!sent) {+ // Most commonly transient: the local transport is mid-reconnect at this exact instant (e.g.+ // right after the app itself just started, or another machine's relay hiccupped a moment ago).+ sent = await _recoverAndResend(openPayload, generation);+ }+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening ||+ streamId != null) {+ return;+ }+ if (!sent) {+ transportLost('Could not send terminal_open');+ return;+ }+ // An immediate ready/keyframe can arrive before send() resolves. Its+ // watchdog or live stream must not be replaced by an open timeout.+ if (status != TerminalSessionStatus.opening || streamId != null) return;+ // Armed unconditionally (not just on reopen attempts): a `terminal_open` sent through a silently+ // stale relay session never gets ANY reply — nothing else would ever notice or recover from that.+ _resyncTimer?.cancel();+ _resyncTimer = Timer(+ resyncTimeout,+ () => unawaited(_handleOpenTimeout(openPayload, generation)),+ );+ }++ /// The armed-on-every-open watchdog fired: no `terminal_ready` arrived in time even though the send+ /// itself succeeded — the relay session was silently stale (ciphertext for a dead E2EE session gets+ /// dropped, not rejected). Force a fresh dial and resend the SAME open request (same `requestId`, so+ /// a late reply for the original still matches) before giving up.+ Future<void> _handleOpenTimeout(+ Map<String, dynamic> openPayload,+ int generation,+ ) async {+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening ||+ streamId != null) {+ return;+ }+ final sent = await _recoverAndResend(openPayload, generation);+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening ||+ streamId != null) {+ return;+ }+ if (sent) {+ _resyncTimer?.cancel();+ _resyncTimer = Timer(+ resyncTimeout,+ () => unawaited(_handleOpenTimeout(openPayload, generation)),+ );+ return;+ }+ _fail(+ 'TERMINAL_RESYNC_TIMEOUT',+ _autoReopenAttempts > 0+ ? 'Terminal did not reopen after resync failed.'+ : 'Harness did not respond — check your connection.',+ );+ }++ /// Shared recovery for both open-failure paths (`send()` itself failing, and `terminal_ready` never+ /// arriving): force a fresh transport dial (see `WsConn.forceReconnect`), then poll-resend — a forced+ /// relay redial is a REAL network round trip (fresh E2EE handshake for a relayed machine), and+ /// `forceReconnect()` resolving only means the redial STARTED, not that the transport is ready again.+ /// Bounded by [_openStallRecovered] (one forced reconnect per open) and a fixed poll budget, so a+ /// persistently broken connection still fails closed instead of retrying forever.+ Future<bool> _recoverAndResend(+ Map<String, dynamic> openPayload,+ int generation,+ ) async {+ final recover = onOpenStalled;+ if (_openStallRecovered || recover == null) return false;+ _openStallRecovered = true;+ try {+ await recover();+ } catch (_) {+ // Still worth polling for readiness even if the forced reconnect itself errored.+ }+ for (var attempt = 0; attempt < 10; attempt++) {+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening ||+ streamId != null) {+ return false;+ }+ if (await send('terminal_open', openPayload)) return true;+ await Future.delayed(const Duration(milliseconds: 300));+ }+ return false;+ }++ /// Returns true when [type] belongs to this session's protocol.+ Future<bool> handleFrame(String type, Map<String, dynamic> payload) async {+ if (_disposed) return false;+ switch (type) {+ case 'terminal_ready':+ if (status != TerminalSessionStatus.opening ||+ payload['requestId'] != _openRequestId ||+ payload['agentId'] != agentId ||+ payload['protocolVersion'] != protocolVersion) {+ return true;+ }+ streamId = payload['streamId'] as String?;+ if (streamId == null || streamId!.isEmpty) {+ _fail('TERMINAL_READY_INVALID', 'Harness returned no stream id');+ return true;+ }+ _resyncTimer?.cancel();+ _resyncTimer = null;+ _heartbeat = Timer.periodic(+ const Duration(seconds: 5),+ (_) => unawaited(_sendHeartbeat()),+ );+ _armInitialKeyframeWatchdog();+ return true;+ case 'terminal_keyframe':+ case 'terminal_output':+ _fail(+ 'TERMINAL_BINARY_REQUIRED',+ 'Harness sent terminal bulk data as JSON',+ );+ return true;+ case 'terminal_chunked_upload_begin_result':+ if (!_matchesStream(payload)) return true;+ final accepted = payload['accepted'] == true;+ if (_activeUpload?.beginAccepted.isCompleted == false) {+ _activeUpload!.beginAccepted.complete(accepted);+ }+ return true;+ case 'terminal_chunked_upload_progress':+ if (!_matchesStream(payload)) return true;+ final bytesWritten = (payload['bytesWritten'] as num?)?.toInt();+ final totalBytes = (payload['totalBytes'] as num?)?.toInt();+ if (bytesWritten != null &&+ totalBytes != null &&+ uploadProgress != null) {+ uploadProgress = uploadProgress!.copyWith(+ bytesWritten: bytesWritten,+ totalBytes: totalBytes,+ );+ notifyListeners();+ }+ return true;+ case 'terminal_paste_image_result':+ case 'terminal_paste_file_result':+ if (!_matchesStream(payload)) return true;+ if (_activeUpload?.finished.isCompleted == false) {+ _activeUpload!.finished.complete(true);+ }+ return true;+ case 'terminal_link_mode':+ if (!_matchesStream(payload)) return true;+ final mode = payload['mode']?.toString();+ // Allow-list, not a blind assign: an older CLI knows only 'p2p'/'relay', a newer one may learn+ // values this build cannot draw, and either way linkMode must stay something the header has an+ // icon for. An unknown value leaves the previous state alone rather than blanking it.+ if (mode == 'p2p' || mode == 'turn' || mode == 'relay') {+ linkMode = mode;+ notifyListeners();+ }+ return true;+ case 'terminal_closed':+ if (!_matchesStream(payload)) return true;+ _generation++;+ _cancelTimers();+ final code = payload['code']?.toString();+ final takenOver = code == 'TERMINAL_TAKEN_OVER';+ status = takenOver+ ? TerminalSessionStatus.takenOver+ : TerminalSessionStatus.closed;+ errorCode = takenOver ? code : null;+ errorMessage = takenOver+ ? 'Another client connected to this terminal.'+ : payload['reason']?.toString();+ streamId = null;+ linkMode = null;+ _abortActiveUpload();+ notifyListeners();+ return true;+ case 'terminal_error':+ final errorStream = payload['streamId'];+ final errorRequest = payload['requestId'];+ if (errorStream != null && errorStream != streamId) return true;+ if (errorRequest != null && errorRequest != _openRequestId) return true;+ final errorCode = payload['code']?.toString() ?? 'TERMINAL_ERROR';+ // A rejected paste (empty, or over the daemon's sanity ceiling) never touched tmux — the+ // stream itself is completely fine, so this must not freeze it the way a real transport/+ // protocol failure does. `debugPrint` only: there is no dedicated per-action failure surface+ // to show the user something better than silence, and silence beats losing the terminal.+ // A malformed upload chunk (bad seq/size) is the same shape of non-event for the same+ // reason — nothing it describes ever reached tmux either.+ if (errorCode == 'TERMINAL_PASTE_INVALID' ||+ errorCode == 'TERMINAL_CHUNKED_UPLOAD_INVALID') {+ _abortActiveUpload();+ notifyListeners();+ debugPrint(+ 'TerminalSession: paste rejected: ${payload['message'] ?? errorCode}',+ );+ return true;+ }+ // A refused INPUT frame never reached tmux either: the stream is fine, only our counter+ // disagrees with the daemon's (a frame dropped on this side while resyncing, say). A daemon+ // that says what it expects gets realigned in place — the refused keystroke is gone either+ // way, and the person retypes it — and an older one that does not gets a fresh stream. What+ // it must NOT get is the frozen pane this used to be: every later keystroke was refused too,+ // and a working terminal read as a dead one.+ if (errorCode == 'TERMINAL_INPUT_INVALID') {+ final expected = payload['expectedSeq'];+ if (expected is int && expected >= 0) {+ // A stale duplicate: the daemon refused several in-flight frames+ // at once, each naming this same seq, and the counter has since+ // moved on from it and been accepted. Rewinding again would put the+ // next keystroke under a number the daemon has already taken.+ // Safe because its expectation only ever grows and its errors+ // arrive in order — a NEW gap always names a larger seq.+ if (expected == _lastRealignedTo) return true;+ _lastRealignedTo = expected;+ _inputSeq = expected;+ // Bytes still waiting in the coalescer are kept: they are numbered+ // on the way out, after this, so they go under the right seq.+ debugPrint(+ 'TerminalSession: input seq realigned to $expected '+ '(${payload['reason'] ?? payload['message'] ?? 'no reason given'})',+ );+ notifyListeners();+ } else {+ _inputBytes.clear();+ unawaited(_recoverByReopen(reason: 'TERMINAL_INPUT_INVALID'));+ }+ return true;+ }+ // A genuine mid-transfer failure (the daemon couldn't write the clipboard/disk, or the+ // pty write itself failed) IS treated like a real transport/protocol failure — same as+ // TERMINAL_PASTE_FAILED already is, since it may mean the pty is in an unknown state.+ // `_fail` itself resolves any in-flight upload (see `_abortActiveUpload`), so there is+ // nothing extra to do here for TERMINAL_PASTE_IMAGE_FAILED/TERMINAL_PASTE_FILE_FAILED.+ _fail(errorCode, payload['message']?.toString());+ return true;+ case 'terminal_transport_error':+ transportLost(+ payload['code']?.toString() ?? 'Terminal relay rejected the frame',+ );+ return true;+ default:+ return false;+ }+ }++ Future<void> handleBinary(TerminalBinaryFrame frame) async {+ if (_disposed || frame.streamId != streamId) return;+ final generation = _generation;+ _renderTail = _renderTail+ .then((_) async {+ if (!_isCurrent(generation) || frame.streamId != streamId) return;+ final bytes = _decodeBinaryBytes(frame);+ if (bytes == null) {+ await _requestResync('TERMINAL_BINARY_DECODE_FAILED');+ return;+ }+ if (frame.kind == TerminalBinaryKind.keyframe) {+ final nextCols = frame.cols;+ final nextRows = frame.rows;+ if (nextCols == null || nextRows == null) {+ await _requestResync('TERMINAL_KEYFRAME_INVALID');+ return;+ }+ // Publish a complete screen atomically. A damaged snapshot must+ // leave the retained screen available while resync recovers.+ final decoded = _decodeUtf8(_prepareKeyframeBytes(bytes));+ final replacement = _newTerminal(bindCallbacks: false)+ ..resize(_clampCols(nextCols), _clampRows(nextRows))+ ..write(decoded.text);+ _bindTerminal(replacement);+ terminal = replacement;+ cols = _clampCols(nextCols);+ rows = _clampRows(nextRows);+ _utf8Tail = decoded.tail;+ _remoteCursorVisible = terminal.cursorVisibleMode;+ _cursorBlinkPhaseVisible = true;+ _expectedSeq = frame.seq + 1;+ _lastRenderedSeq = frame.seq;+ _resyncRequested = false;+ _resyncAttempts = 0;+ _autoReopenAttempts = 0;+ errorCode = null;+ errorMessage = null;+ _resyncTimer?.cancel();+ _resyncTimer = null;+ status = TerminalSessionStatus.controlling;+ _markForAck(bytes.length);+ notifyListeners();+ final measured = _measuredViewport;+ if (measured != null) {+ _pendingCols = measured.cols;+ _pendingRows = measured.rows;+ }+ if (_pendingCols != null && _pendingRows != null) {+ unawaited(_flushResize());+ }+ return;+ }+ if (frame.kind == TerminalBinaryKind.sync) {+ if (status == TerminalSessionStatus.resyncing) return;+ if (_expectedSeq == null || frame.seq != _expectedSeq) {+ await _requestResync('TERMINAL_SEQUENCE_GAP');+ return;+ }+ _expectedSeq = frame.seq + 1;+ _lastRenderedSeq = frame.seq;+ _markForAck(0);+ return;+ }+ if (frame.kind != TerminalBinaryKind.output ||+ status == TerminalSessionStatus.resyncing) {+ return;+ }+ if (_expectedSeq == null || frame.seq != _expectedSeq) {+ await _requestResync('TERMINAL_SEQUENCE_GAP');+ return;+ }+ if (!_writeBytes(bytes)) {+ await _requestResync('TERMINAL_OUTPUT_DECODE_FAILED');+ return;+ }+ _expectedSeq = frame.seq + 1;+ _lastRenderedSeq = frame.seq;+ _markForAck(bytes.length);+ })+ .catchError((Object error, StackTrace stackTrace) async {+ if (!_isCurrent(generation)) return;+ debugPrint(+ '[terminal-session] renderer failed for '+ '$machineId/$agentId: $error\n$stackTrace',+ );+ CrashLog.record(error, stackTrace, context: 'renderer');+ await onRendererFailure();+ });+ await _renderTail;+ }++ /// Recover from an exception thrown while drawing a frame.+ ///+ /// A renderer fault is LOCAL, and calling it a lost transport was the wrong+ /// diagnosis: the bytes arrived intact and something in drawing them threw.+ /// That froze the tile behind a manual "attach new stream" for a fault the+ /// ordinary resync ladder already clears — it is what the decode failures in+ /// [handleBinary] do — and the ladder is bounded (resync x3, reopen x1, then+ /// a real failure), so a renderer that throws every time still ends up+ /// reporting itself rather than retrying for ever.+ ///+ /// A parser exception can leave the current buffer partially mutated, so the+ /// emulator is not reused: the resync's keyframe is authoritative and+ /// [handleBinary] builds a fresh Terminal for it. Nothing more is written to+ /// the damaged one in the meantime, because the output branch drops frames+ /// while the status is `resyncing`.+ @visibleForTesting+ Future<void> onRendererFailure() =>+ _requestResync('TERMINAL_RENDERER_FAILED');++ Uint8List? _decodeBinaryBytes(TerminalBinaryFrame frame) {+ try {+ return frame.compressed+ ? Uint8List.fromList(ZLibDecoder().convert(frame.bytes))+ : frame.bytes;+ } catch (_) {+ return null;+ }+ }++ void attachViewport(TerminalViewport viewport) {+ _viewport = viewport;+ }++ /// Reports the first grid measured from the actual Flutter terminal render+ /// object. This is deliberately separate from [Terminal.onResize]: creating+ /// a terminal at the conservative 80x24 fallback also fires onResize and+ /// must not be mistaken for a measured viewport.+ void reportViewport(int width, int height) {+ final measured = (cols: _clampCols(width), rows: _clampRows(height));+ _measuredViewport = measured;+ if (_viewportSize.isCompleted) return;+ _viewportSize.complete(measured);+ }++ void detachViewport(TerminalViewport viewport) {+ if (identical(_viewport, viewport)) _viewport = null;+ }++ /// Changes only the local paint phase of the cursor. Incoming terminal data+ /// is always parsed against [_remoteCursorVisible], so blinking cannot turn+ /// a remote DECTCEM hide/show command into terminal input or corrupt its+ /// authoritative cursor state.+ void setCursorBlinkPhase(bool visible) {+ if (_cursorBlinkPhaseVisible == visible) return;+ _cursorBlinkPhaseVisible = visible;+ _applyCursorVisibility();+ }++ void _writeTerminalText(String text) {+ terminal.setCursorVisibleMode(_remoteCursorVisible);+ terminal.write(text);+ _remoteCursorVisible = terminal.cursorVisibleMode;+ _applyCursorVisibility();+ }++ void _applyCursorVisibility() {+ terminal.setCursorVisibleMode(+ _remoteCursorVisible && _cursorBlinkPhaseVisible,+ );+ }++ bool _writeBytes(List<int> bytes) {+ // Most packets end on a scalar boundary. Decode their existing byte view+ // directly; only a split UTF-8 scalar needs a joined buffer.+ final combined = _utf8Tail.isEmpty ? bytes : <int>[..._utf8Tail, ...bytes];+ final decoded = _decodeUtf8(combined);+ if (decoded.text.isNotEmpty) _writeTerminalText(decoded.text);+ _utf8Tail = decoded.tail;+ return true;+ }++ ({String text, List<int> tail}) _decodeUtf8(List<int> combined) {+ for (+ var tailLength = 0;+ tailLength <= min(3, combined.length);+ tailLength+++ ) {+ try {+ final text = utf8.decoder.convert(+ combined,+ 0,+ combined.length - tailLength,+ );+ return (+ text: text,+ tail: tailLength == 0+ ? const []+ : combined.sublist(combined.length - tailLength),+ );+ } on FormatException {+ // A UTF-8 scalar can span at most four bytes; retain only a trailing+ // partial scalar before falling back to replacement rendering below.+ }+ }+ // PTY output is byte-oriented. A snapshot cut can rarely land between the+ // leading and continuation bytes of a scalar, leaving a continuation byte+ // at the start of the post-cut frame. Real terminals render malformed UTF-8+ // as U+FFFD; resyncing the entire screen creates a second keyframe race and+ // cannot recover the missing pre-cut byte anyway.+ return (text: utf8.decode(combined, allowMalformed: true), tail: const []);+ }++ List<int> _prepareKeyframeBytes(Uint8List bytes) {+ if (engineId != 'grok') return bytes;++ // Grok renders a full-screen TUI in tmux's normal buffer. Its tmux+ // scrollback therefore contains old full-screen repaint frames rather than+ // semantic history. Render Grok in the receiver's alternate buffer so the+ // stale frames cannot become local scrollback; wheel input is then routed+ // back to Grok, which owns and redraws its real transcript with ANSI style.+ const alternateBuffer = <int>[+ 0x1b,+ 0x5b,+ 0x3f,+ 0x31,+ 0x30,+ 0x34,+ 0x39,+ 0x68,+ ];+ if (bytes.length >= 2 && bytes[0] == 0x1b && bytes[1] == 0x63) {+ return <int>[bytes[0], bytes[1], ...alternateBuffer, ...bytes.sublist(2)];+ }+ return <int>[...alternateBuffer, ...bytes];+ }++ Terminal _newTerminal({bool bindCallbacks = true}) {+ final result = Terminal(+ maxLines: 10000,+ platform: TerminalTargetPlatform.macos,+ // ⌥⏎ has to become a Meta-prefixed Return before it reaches the pty, or the engine's prompt+ // reads it as the submit it is byte-identical to. See [MetaEnterInputHandler].+ inputHandler: harnessInputHandler,+ // The remote pane owns its grid and redraws after resize. Reflowing TUI+ // rows locally both changes their geometry and exercises an xterm.dart+ // circular-buffer bug when a remote/local switch changes viewport size.+ reflowEnabled: false,+ );+ if (bindCallbacks) _bindTerminal(result);+ return result;+ }++ void _bindTerminal(Terminal result) {+ result.onOutput = _onTerminalOutput;+ result.onResize = (width, height, _, _) => resize(width, height);+ }++ /// Sends a composed message as one turn.+ ///+ /// This does NOT write bytes into the pane. It sends the same `message` frame the web client+ /// uses to drive a turn (`sendMessage` in web's `lib/ws.ts`), and the machine's own handler owns+ /// the injection from there: it adapts slash commands to the pane's engine and retries the+ /// submit Enter. A client typing bytes can do neither — which is exactly how Codex ended up+ /// holding a composed line unsent, its Enter arriving in the same read as the text.+ Future<bool> sendComposerText(String text) async {+ if (!acceptsInput) return false;+ final content = text.trimRight();+ if (content.trim().isEmpty) return false;+ return send('message', {+ 'content': content,+ 'agentId': agentId,+ 'mode': 'auto',+ });+ }++ /// A clipboard paste made directly into this pane, delivered as one atomic unit instead of going+ /// through the same chunked pipeline as ordinary typing ([_onTerminalOutput]/[_flushInput]).+ ///+ /// A big paste run through that pipeline gets sliced into ≤8 KiB binary frames client-side and then+ /// into 2 KiB `send-keys -H` bursts on the daemon — each burst arrives far enough apart that the+ /// engine's own paste-detector (readline/Ink) can register it as a SEPARATE paste, which is why a+ /// large paste read as dozens of `[Pasted text #N]` markers instead of one. A [TerminalBinaryKind.paste]+ /// frame routes through the daemon's `tmux paste-buffer` instead, the same single-shot mechanism+ /// composer messages already use — see `pasteRawIntoTmux` in the harness CLI.+ ///+ /// Binary, not JSON: unlike a JSON frame type, a new binary `kind` needs no entry in the E2EE+ /// allowlist (`ENCRYPTED_DOWN_TYPES`) three OTHER codebases also pin a hash of — the AEAD wrapping+ /// that already covers `input`/`output` covers this too, with nothing extra to keep in sync. That is+ /// what lets this work over a relayed machine, not just a local one.+ ///+ /// The caller must check [MachineState.terminalPasteRawAvailable] first: an older CLI does not know+ /// this binary kind at all, so sending it there would silently go nowhere.+ Future<bool> pasteText(String text) async {+ if (!acceptsInput) return false;+ // Forwarded verbatim, including a stray 0x03 — same as _onTerminalOutput/sendComposerText.+ if (text.isEmpty) return false;+ final currentStreamId = streamId;+ if (currentStreamId == null) return false;+ final generation = _generation;+ final frame = TerminalBinaryFrame(+ kind: TerminalBinaryKind.paste,+ streamId: currentStreamId,+ // Unused server-side (a paste is one self-contained unit, not part of the ordered keystroke+ // stream `input`'s seq guards) — kept at 0 rather than threading a second counter for a field+ // nothing reads.+ seq: 0,+ bytes: Uint8List.fromList(utf8.encode(text)),+ compressed: false,+ );+ final sent = await sendBinary(frame);+ if (!sent && _isCurrent(generation)) {+ transportLost('Terminal paste was not sent');+ }+ return sent;+ }++ /// A clipboard IMAGE paste (raw PNG bytes) made directly into this pane, sent as a chunked+ /// upload (see [_uploadBytes]) over [TerminalBinaryKind.imagePaste] frames — the daemon's+ /// text-paste handler requires valid UTF-8 and would reject PNG bytes outright, hence its own+ /// kind, same reason [pasteText] doesn't carry it.+ ///+ /// The caller must check [MachineState.terminalImagePasteAvailable] first, same reason+ /// [pasteText] checks `terminalPasteRawAvailable`: an older CLI does not know this binary kind+ /// at all, so sending it there would silently go nowhere.+ Future<bool> pasteImage(Uint8List pngBytes) async {+ if (pngBytes.isEmpty) return false;+ return _uploadBytes(+ uploadKind: 'image',+ filename: null,+ bytes: pngBytes,+ binaryKind: TerminalBinaryKind.imagePaste,+ );+ }++ /// A dropped (non-image) FILE — sent as a chunked upload (see [_uploadBytes]) so the daemon can+ /// write it to disk on its own (REMOTE) machine and paste that path as text. Only meaningful for+ /// a genuinely remote pane: a LOCAL file already has a valid path on this same machine, so+ /// callers should paste that path directly via [pasteText] instead and never reach this method+ /// at all — see [MachineState.isLocalMachine].+ ///+ /// The caller must check [MachineState.terminalPasteFileAvailable] first, same reason+ /// [pasteImage] checks `terminalImagePasteAvailable`: an older CLI does not know this binary kind+ /// at all, so sending it there would silently go nowhere.+ Future<bool> pasteFile(String filename, Uint8List content) async {+ if (filename.isEmpty || content.isEmpty) return false;+ return _uploadBytes(+ uploadKind: 'file',+ filename: filename,+ bytes: content,+ binaryKind: TerminalBinaryKind.pasteFile,+ );+ }++ /// Cancels whatever image/file upload is currently in flight on this pane, if any — the user's+ /// own Cancel affordance on the upload-progress overlay. A no-op if nothing is uploading.+ Future<void> cancelUpload() async {+ final upload = _activeUpload;+ final currentStreamId = streamId;+ if (upload == null) return;+ if (!upload.finished.isCompleted) upload.finished.complete(false);+ _clearUpload();+ if (currentStreamId != null) {+ await send('terminal_chunked_upload_cancel', {+ 'streamId': currentStreamId,+ });+ }+ }++ /// Shared orchestration for [pasteImage]/[pasteFile]: announce the upload+ /// (`terminal_chunked_upload_begin`), wait to be accepted, send the bytes as a series of+ /// `binaryKind` frames — [TerminalBinaryFrame.seq] is the chunk index — each at most+ /// [terminalUploadChunkBytes], then wait for the daemon's completion/error frame. Chunked rather+ /// than sent whole because a single frame over 512 KiB never reaches a relayed or P2P-connected+ /// remote machine at all (both cap a binary message there); see the plan this shipped from.+ ///+ /// [uploadProgress] reflects the daemon's own per-chunk ACKs+ /// (`terminal_chunked_upload_progress`), not "chunks handed to the local socket" — that is what+ /// keeps the percentage honest on a slow link, mirroring the firmware pusher's `fw.progress`+ /// philosophy (`autonomous-harness/cli/src/cable/fwPush.ts`). Only one upload runs at a time per+ /// pane — a second call while one is active is refused immediately, matching the daemon's own+ /// "an upload is already in progress" rejection.+ Future<bool> _uploadBytes({+ required String uploadKind,+ required String? filename,+ required Uint8List bytes,+ required TerminalBinaryKind binaryKind,+ }) async {+ if (!acceptsInput) return false;+ if (_activeUpload != null) return false;+ final currentStreamId = streamId;+ if (currentStreamId == null) return false;++ final upload = _ActiveUpload();+ final generation = _generation;+ bool current() =>+ _isCurrent(generation) && identical(_activeUpload, upload);+ _activeUpload = upload;+ uploadProgress = UploadProgress(+ label: filename ?? 'image',+ bytesWritten: 0,+ totalBytes: bytes.length,+ );+ notifyListeners();++ final sentBegin = await send('terminal_chunked_upload_begin', {+ 'streamId': currentStreamId,+ 'uploadKind': uploadKind,+ 'totalBytes': bytes.length,+ 'filename': ?filename,+ });+ if (!current()) return false;+ if (!sentBegin) {+ transportLost('Terminal upload request was not sent');+ _clearUpload();+ return false;+ }++ final accepted = await upload.beginAccepted.future.timeout(+ const Duration(seconds: 10),+ onTimeout: () => false,+ );+ if (!current()) return false;+ if (!accepted) {+ _clearUpload();+ return false;+ }++ var offset = 0;+ var seq = 0;+ while (offset < bytes.length) {+ final end = min(offset + terminalUploadChunkBytes, bytes.length);+ final frame = TerminalBinaryFrame(+ kind: binaryKind,+ streamId: currentStreamId,+ seq: seq,+ bytes: Uint8List.sublistView(bytes, offset, end),+ compressed: false,+ );+ final sentChunk = await sendBinary(frame);+ if (!current()) return false;+ if (!sentChunk) {+ transportLost('Terminal upload chunk was not sent');+ _clearUpload();+ return false;+ }+ offset = end;+ seq++;+ }++ final finished = await upload.finished.future.timeout(+ const Duration(minutes: 2),+ onTimeout: () => false,+ );+ if (!current()) return false;+ _clearUpload();+ return finished;+ }++ void _clearUpload() {+ _activeUpload = null;+ uploadProgress = null;+ notifyListeners();+ }++ void _onTerminalOutput(String data) {+ if (!acceptsInput || data.isEmpty) return;+ final bytes = utf8.encode(data);+ final isBoundary =+ data.contains('\r') ||+ data.contains('\x1b[200~') ||+ data.contains('\x1b[201~');+ if (isBoundary) unawaited(_flushInput());+ var offset = 0;+ while (offset < bytes.length) {+ final available = 8 * 1024 - _inputBytes.length;+ final take = min(available, bytes.length - offset);+ _inputBytes.addAll(bytes.sublist(offset, offset + take));+ offset += take;+ if (_inputBytes.length == 8 * 1024) unawaited(_flushInput());+ }+ if (isBoundary) {+ unawaited(_flushInput());+ } else if (_inputBytes.isNotEmpty) {+ // Leading edge: the first keystroke after a pause goes out at once. The window exists to+ // batch key-repeat, and a lone keypress has nothing to batch with — making it wait was+ // 4ms of pure latency on every character typed at human speed. Anything arriving inside+ // the window still rides the trailing timer, so the frame rate stays bounded.+ final last = _lastInputFlushAt;+ final idle =+ last == null ||+ DateTime.now().difference(last) >= _inputCoalesceWindow;+ if (_inputTimer == null && idle) {+ unawaited(_flushInput());+ } else {+ _inputTimer ??= Timer(+ _inputCoalesceWindow,+ () => unawaited(_flushInput()),+ );+ }+ }+ }++ Future<void> _flushInput() async {+ _inputTimer?.cancel();+ _inputTimer = null;+ if (!acceptsInput || _inputBytes.isEmpty) {+ _inputBytes.clear();+ return;+ }+ final bytes = List<int>.from(_inputBytes);+ _inputBytes.clear();+ _lastInputFlushAt = DateTime.now();+ final currentStreamId = streamId;+ if (currentStreamId == null) return;+ final generation = _generation;+ final queued = _inputSendTail.then((_) async {+ if (!_isCurrent(generation) ||+ !acceptsInput ||+ streamId != currentStreamId) {+ return;+ }+ // Numbered HERE, on the tail, not when the flush was asked for. A frame+ // the guard above drops — the session went `resyncing` while an earlier+ // send was still in flight — must not consume a seq: the daemon wants+ // them contiguous and never re-syncs its counter, so one skipped number+ // had the very next keystroke refused and the whole pane frozen. The+ // tail runs one closure at a time, which is what keeps the numbers in+ // order.+ //+ // Never larger than the daemon accepts, either — split rather than let+ // one oversized frame be refused with the counter intact behind it.+ for (+ var offset = 0;+ offset < bytes.length;+ offset += kInputFrameMaxBytes+ ) {+ if (!_isCurrent(generation) ||+ !acceptsInput ||+ streamId != currentStreamId) {+ return;+ }+ final end = min(offset + kInputFrameMaxBytes, bytes.length);+ final frame = TerminalBinaryFrame(+ kind: TerminalBinaryKind.input,+ streamId: currentStreamId,+ seq: _inputSeq++,+ bytes: Uint8List.fromList(bytes.sublist(offset, end)),+ compressed: false,+ );+ final sent = await sendBinary(frame);+ if (!_isCurrent(generation)) return;+ if (!sent) {+ transportLost('Terminal input was not sent');+ return;+ }+ }+ });+ _inputSendTail = queued.catchError((_) {+ if (_isCurrent(generation)) transportLost('Terminal input was not sent');+ });+ await _inputSendTail;+ }++ /// A finger on the dial moved — scroll whatever this session is showing.+ ///+ /// Goes STRAIGHT to the renderer rather than through the machine: the scrollback being moved is the copy+ /// in this window, and the agent on the other end has no idea the view scrolled. Nothing is sent over+ /// the wire and nothing is echoed back.+ void scroll(int phase, int dy, int velocity) {+ _viewport?.scroll(phase, dy, velocity);+ }++ void find(TerminalFindAction action) => _viewport?.find(action);++ bool focusInput() => _viewport?.focusInput() ?? false;++ /// Coalescing windows for the two things the user drives directly.+ ///+ /// Both are leading + trailing: act on the first event, batch the rest. A flat trailing debounce+ /// charged its full window to every single keystroke and to the start of every drag, which is+ /// latency paid for a batch that mostly never materializes.+ static const _inputCoalesceWindow = Duration(milliseconds: 4);++ /// The daemon's ceiling on one input frame (`INPUT_MAX_BYTES` in+ /// `cli/src/lib/terminalStreamManager.ts`). Larger is refused, not split.+ static const kInputFrameMaxBytes = 64 * 1024;+ static const _resizeCoalesceWindow = Duration(milliseconds: 50);++ void resize(int width, int height) {+ _pendingCols = _clampCols(width);+ _pendingRows = _clampRows(height);+ final last = _lastResizeFlushAt;+ final idle =+ last == null ||+ DateTime.now().difference(last) >= _resizeCoalesceWindow;+ if (_resizeTimer == null && idle) {+ unawaited(_flushResize());+ return;+ }+ // Mid-drag: keep resetting so tmux is asked once, for the size the drag settles on.+ _resizeTimer?.cancel();+ _resizeTimer = Timer(+ _resizeCoalesceWindow,+ () => unawaited(_flushResize()),+ );+ }++ Future<void> _flushResize() async {+ // A keyframe can flush the measured viewport before the debounce fires.+ // Cancel that callback before releasing its handle.+ _resizeTimer?.cancel();+ _resizeTimer = null;+ if (!acceptsInput || _pendingCols == null || _pendingRows == null) return;+ final nextCols = _pendingCols!;+ final nextRows = _pendingRows!;+ _pendingCols = null;+ _pendingRows = null;+ if (nextCols == cols && nextRows == rows) return;+ cols = nextCols;+ rows = nextRows;+ _lastResizeFlushAt = DateTime.now();+ final generation = _generation;+ final sent = await send('terminal_resize', {+ 'streamId': streamId,+ 'resizeSeq': _resizeSeq++,+ 'cols': cols,+ 'rows': rows,+ });+ if (!_isCurrent(generation)) return;+ if (!sent) transportLost('Terminal resize was not sent');+ notifyListeners();+ }++ static const _scrollCoalesceWindow = Duration(milliseconds: 16);++ /// Alt-buffer scroll gesture for a [scrollViaTmuxCopyMode] session — see that getter's doc.+ /// Coalesces rapid deltas (a fast trackpad swipe can emit dozens a second) into one+ /// `terminal_scroll` frame per short burst, mirroring `resize()`'s own debounce. Fire-and-forget+ /// like resize, but a dropped frame here is just a missed scroll, not a transport-health signal —+ /// unlike resize, it never calls `transportLost`.+ void sendScrollCommand(bool up, int lines) {+ if (!scrollViaTmuxCopyMode || lines <= 0) return;+ if (_pendingScrollUp != null && _pendingScrollUp != up) {+ // Direction reversed mid-burst — flush what's accumulated before starting the new direction,+ // rather than let it cancel out into a smaller net scroll the user never asked for.+ unawaited(_flushScrollCommand());+ }+ _pendingScrollUp = up;+ _pendingScrollLines += lines;+ _scrollTimer?.cancel();+ _scrollTimer = Timer(+ _scrollCoalesceWindow,+ () => unawaited(_flushScrollCommand()),+ );+ }++ Future<void> _flushScrollCommand() async {+ _scrollTimer?.cancel();+ _scrollTimer = null;+ final up = _pendingScrollUp;+ final lines = _pendingScrollLines;+ _pendingScrollUp = null;+ _pendingScrollLines = 0;+ if (!acceptsInput || up == null || lines <= 0) return;+ await send('terminal_scroll', {+ 'streamId': streamId,+ 'direction': up ? 'up' : 'down',+ 'lines': lines,+ });+ }++ void _markForAck(int renderedBytes) {+ _framesSinceAck++;+ _renderedSinceAckBytes += renderedBytes;+ if (_renderedSinceAckBytes >= 64 * 1024) {+ unawaited(_flushAck());+ return;+ }+ _ackTimer ??= Timer(+ const Duration(milliseconds: 16),+ () => unawaited(_flushAck()),+ );+ }++ Future<void> _flushAck() async {+ _ackTimer?.cancel();+ _ackTimer = null;+ if (streamId == null || _lastRenderedSeq < 0 || _framesSinceAck == 0) {+ return;+ }+ _framesSinceAck = 0;+ _renderedSinceAckBytes = 0;+ final generation = _generation;+ final sent = await send('terminal_ack', {+ 'streamId': streamId,+ 'lastSeq': _lastRenderedSeq,+ });+ if (!sent && _isCurrent(generation)) {+ transportLost('Terminal ACK was not sent');+ }+ }++ Future<void> _sendHeartbeat() async {+ if (!acceptsInput) return;+ final generation = _generation;+ final sent = await send('terminal_alive', {'streamId': streamId});+ if (!sent && _isCurrent(generation)) {+ transportLost('Terminal heartbeat was not sent');+ }+ }++ Future<void> _requestResync(String reason) async {+ if (streamId == null) {+ _fail(reason, null);+ return;+ }+ if (!_resyncRequested) {+ _resyncRequested = true;+ _resyncAttempts = 0;+ status = TerminalSessionStatus.resyncing;+ errorCode = reason;+ _inputBytes.clear();+ notifyListeners();+ }+ if (_resyncAttempts > 0) return;+ await _sendResyncAttempt();+ }++ void _armInitialKeyframeWatchdog() {+ _resyncTimer?.cancel();+ _resyncTimer = Timer(resyncTimeout, () {+ if (streamId != null && _expectedSeq == null) {+ unawaited(_requestResync('TERMINAL_KEYFRAME_TIMEOUT'));+ }+ });+ }++ Future<void> _sendResyncAttempt() async {+ final currentStream = streamId;+ final generation = _generation;+ if (!_resyncRequested || currentStream == null) return;+ if (_resyncAttempts >= 3) {+ await _recoverByReopen();+ return;+ }+ _resyncAttempts++;+ debugPrint(+ '[terminal-session] resync_request agent=$agentId stream=$currentStream '+ 'attempt=$_resyncAttempts code=$errorCode',+ );+ final sent = await send('terminal_resync', {+ 'streamId': currentStream,+ 'attempt': _resyncAttempts,+ 'reason': errorCode,+ });+ if (!_isCurrent(generation) ||+ streamId != currentStream ||+ !_resyncRequested) {+ return;+ }+ if (!sent) {+ transportLost('Could not request terminal resync');+ return;+ }+ _resyncTimer?.cancel();+ _resyncTimer = Timer(resyncTimeout, () {+ if (_resyncRequested && streamId == currentStream) {+ unawaited(_sendResyncAttempt());+ }+ });+ }++ Future<void> _recoverByReopen({+ String reason = 'TERMINAL_RESYNC_TIMEOUT',+ }) async {+ final previousStream = streamId;+ if (_autoReopenAttempts >= 1) {+ debugPrint(+ '[terminal-session] recovery_failed agent=$agentId '+ 'stream=$previousStream reason=$reason attempts=$_resyncAttempts',+ );+ _fail(+ reason,+ reason == 'TERMINAL_RESYNC_TIMEOUT'+ ? 'Terminal did not recover after resync and reopen.'+ : 'Terminal did not recover after reopening the stream.',+ );+ return;+ }+ _autoReopenAttempts++;+ debugPrint(+ '[terminal-session] recovery_reopen agent=$agentId stream=$previousStream',+ );+ if (previousStream != null) {+ unawaited(send('terminal_close', {'streamId': previousStream}));+ }+ await _open(+ initialCols: cols,+ initialRows: rows,+ waitForViewportSize: false,+ resetRecovery: false,+ preserveTerminal: true,+ );+ }++ Future<void> close() async {+ _generation++;+ final closingStream = streamId;+ _cancelTimers();+ _inputBytes.clear();+ streamId = null;+ linkMode = null;+ status = TerminalSessionStatus.closed;+ _abortActiveUpload();+ notifyListeners();+ if (closingStream != null) {+ await send('terminal_close', {'streamId': closingStream});+ }+ }++ void transportLost([+ String message = 'Connection lost. Select the harness to reconnect.',+ ]) {+ // `takenOver` is a deliberate dead end (see `_paneNeedsAttach`): only the user's own retry+ // may reopen a stream someone else claimed. A WS hiccup must not quietly overwrite that into+ // `error`, which auto-reattach WOULD pick back up — that is exactly the two-machine tug-of-war+ // this status exists to prevent.+ if (_disposed ||+ status == TerminalSessionStatus.closed ||+ status == TerminalSessionStatus.takenOver) {+ return;+ }+ _generation++;+ _cancelTimers();+ _inputBytes.clear();+ streamId = null;+ linkMode = null;+ status = TerminalSessionStatus.error;+ errorCode = 'TERMINAL_DISCONNECTED';+ errorMessage = message;+ _abortActiveUpload();+ notifyListeners();+ }++ void _fail(String code, String? message) {+ if (_disposed) return;+ _generation++;+ _cancelTimers();+ _inputBytes.clear();+ streamId = null;+ linkMode = null;+ status = TerminalSessionStatus.error;+ errorCode = code;+ errorMessage = message;+ _abortActiveUpload();+ notifyListeners();+ }++ /// A safety net for any path that resets the stream (transport loss, a real failure) while an+ /// image/file upload happens to be in flight — resolves its awaiting Future rather than leaving+ /// it to hang until [_uploadBytes]'s own 2-minute timeout. The specific error codes that mean+ /// "the upload itself failed" already call this via [transportLost]/[_fail]; this also covers+ /// every OTHER way the stream can go away mid-upload.+ void _abortActiveUpload() {+ if (_activeUpload?.beginAccepted.isCompleted == false) {+ _activeUpload!.beginAccepted.complete(false);+ }+ if (_activeUpload?.finished.isCompleted == false) {+ _activeUpload!.finished.complete(false);+ }+ _activeUpload = null;+ uploadProgress = null;+ }++ bool _matchesStream(Map<String, dynamic> payload) =>+ streamId != null && payload['streamId'] == streamId;++ int _clampCols(int value) => value.clamp(minCols, maxCols);+ int _clampRows(int value) => value.clamp(minRows, maxRows);++ void _cancelTimers() {+ _heartbeat?.cancel();+ _heartbeat = null;+ _ackTimer?.cancel();+ _ackTimer = null;+ _inputTimer?.cancel();+ _inputTimer = null;+ _resizeTimer?.cancel();+ _resizeTimer = null;+ _resyncTimer?.cancel();+ _resyncTimer = null;+ _scrollTimer?.cancel();+ _scrollTimer = null;+ }++ @override+ void dispose() {+ _disposed = true;+ _generation++;+ _cancelTimers();+ super.dispose();+ }+}diff --git a/mobile/lib/terminal/terminal_snapshot.dart b/mobile/lib/terminal/terminal_snapshot.dartnew file mode 100644index 000000000..44cfe8e63--- /dev/null+++ b/mobile/lib/terminal/terminal_snapshot.dart@@ -0,0 +1,46 @@+import 'package:xterm/xterm.dart';++/// Rebase the few locations a reader is using when an authoritative screen+/// replaces a buffer. Matching neighbors distinguish repeated log lines.+/// Only requested rows retain text; the replacement is scanned once.+Map<int, int> remapTerminalRows(+ Buffer before,+ Buffer after,+ Iterable<int> rows,+) {+ final wanted = rows+ .where((row) => row >= 0 && row < before.lines.length)+ .toSet();+ if (wanted.isEmpty || after.lines.length == 0) return {};+ String? text(Buffer buffer, int row) => row >= 0 && row < buffer.lines.length+ ? buffer.lines[row].getText()+ : null;+ final context = {+ for (final row in wanted)+ row: (text(before, row - 1), text(before, row), text(before, row + 1)),+ };+ final byText = <String, List<int>>{};+ for (final row in wanted) {+ (byText[context[row]!.$2!] ??= []).add(row);+ }+ final matches = <int, ({int row, int score})>{};+ String? previous;+ var current = text(after, 0);+ for (var row = 0; row < after.lines.length; row++) {+ final next = text(after, row + 1);+ for (final old in byText[current] ?? const <int>[]) {+ final neighbors = context[old]!;+ final score =+ (neighbors.$1 == previous ? 1 : 0) + (neighbors.$3 == next ? 1 : 0);+ final best = matches[old];+ if (best == null ||+ score > best.score ||+ (score == best.score && (row - old).abs() < (best.row - old).abs())) {+ matches[old] = (row: row, score: score);+ }+ }+ previous = current;+ current = next;+ }+ return {for (final entry in matches.entries) entry.key: entry.value.row};+}diff --git a/mobile/lib/terminal/terminal_theme.dart b/mobile/lib/terminal/terminal_theme.dartnew file mode 100644index 000000000..d7d995ef8--- /dev/null+++ b/mobile/lib/terminal/terminal_theme.dart@@ -0,0 +1,134 @@+import 'package:flutter/material.dart';+import 'package:xterm/xterm.dart';++import '../shared/theme/color_palette.dart';+import 'terminal_theme_store.dart';++/// The colours a terminal pane draws itself in.+///+/// ⚠️ Returns a CACHED (or `const`) instance, never a fresh one. The vendored+/// renderer short-circuits on identity before repainting, so a new+/// [TerminalTheme] built per rebuild reads as "the colours changed" every+/// frame — the same trap [TerminalFontStore] documents for [TerminalStyle].+TerminalTheme terminalThemeFor(+ HarnessPalette palette,+ TerminalThemeChoice choice,+) => switch (choice) {+ // A whole scheme of its own: the app palette is not consulted at all, which+ // is the entire point of offering it.+ TerminalThemeChoice.tango => tangoTerminalTheme,+ TerminalThemeChoice.matchApp => _matchApp(palette),+};++/// Cached per palette. Switching colors repaints the existing terminal view;+/// it does not replace its controller, buffer, input connection or font.+TerminalTheme _matchApp(HarnessPalette palette) => _palettes.putIfAbsent(+ palette,+ () => TerminalTheme(+ cursor: palette.accent,+ selection: palette.accent.withValues(alpha: 0.3),+ foreground: palette.foreground,+ background: palette.background,+ black: darkTerminalTheme.black,+ red: darkTerminalTheme.red,+ green: darkTerminalTheme.green,+ yellow: darkTerminalTheme.yellow,+ blue: darkTerminalTheme.blue,+ magenta: darkTerminalTheme.magenta,+ cyan: darkTerminalTheme.cyan,+ white: darkTerminalTheme.white,+ brightBlack: darkTerminalTheme.brightBlack,+ brightRed: darkTerminalTheme.brightRed,+ brightGreen: darkTerminalTheme.brightGreen,+ brightYellow: darkTerminalTheme.brightYellow,+ brightBlue: darkTerminalTheme.brightBlue,+ brightMagenta: darkTerminalTheme.brightMagenta,+ brightCyan: darkTerminalTheme.brightCyan,+ brightWhite: darkTerminalTheme.brightWhite,+ searchHitBackground: darkTerminalTheme.searchHitBackground,+ searchHitBackgroundCurrent: darkTerminalTheme.searchHitBackgroundCurrent,+ searchHitForeground: darkTerminalTheme.searchHitForeground,+ ),+);++final _palettes = <HarnessPalette, TerminalTheme>{};++/// Harness owns the terminal's *default* appearance.+///+/// Terminal streams provide ANSI attributes, not the source application's+/// complete colour scheme. The default foreground, background, and ANSI ramp+/// must therefore follow Harness's own (dark-only) appearance. Explicit ANSI+/// and true-colour cells remain untouched by xterm, so a TUI keeps the colours+/// it deliberately emits.+const darkTerminalTheme = TerminalTheme(+ cursor: Color(0xffaeafad),+ // Translucent, not opaque: this is painted over the glyphs after they're drawn (see+ // render.dart's _paint), so an opaque fill here erased the selected text instead of+ // highlighting it, unlike every native terminal's selection. ~40% of the theme's own+ // brightBlue below, matching the tinted-overlay look those terminals use.+ selection: Color(0x663B8EEA),+ foreground: Color(0xffffffff),+ background: Color(0xff181818),+ black: Color(0xff000000),+ red: Color(0xffcd3131),+ green: Color(0xff0dbc79),+ yellow: Color(0xffe5e510),+ blue: Color(0xff2472c8),+ magenta: Color(0xffbc3fbc),+ cyan: Color(0xff11a8cd),+ white: Color(0xffe5e5e5),+ brightBlack: Color(0xff666666),+ brightRed: Color(0xfff14c4c),+ brightGreen: Color(0xff23d18b),+ brightYellow: Color(0xfff5f543),+ brightBlue: Color(0xff3b8eea),+ brightMagenta: Color(0xffd670d6),+ brightCyan: Color(0xff29b8db),+ brightWhite: Color(0xffffffff),+ searchHitBackground: Color(0xffffff2b),+ searchHitBackgroundCurrent: Color(0xff31ff26),+ searchHitForeground: Color(0xff000000),+);++/// The Tango palette, as GNOME Terminal ships it — what an agent looks like on+/// a stock Ubuntu desktop.+///+/// ⚠️ The sixteen ANSI slots below are Tango's, unmodified. The GROUND is not:+/// `#300A24` is Ubuntu's own aubergine, which it sets as a custom text colour+/// over this palette, and `#ffffff` the foreground that goes with it. Tango's+/// own dark is `#2e3436` and it is still here, as `black`, where a program+/// asking for colour 0 will find it. Swapping the ground for `black` would be+/// "more correct" and would stop looking like the thing people recognise.+///+/// `selection` is translucent for the reason [darkTerminalTheme] gives — it is+/// painted OVER the glyphs — at the same ~40% of this scheme's own brightBlue.+///+/// The three `searchHit*` colours are deliberately Harness's, shared with+/// [darkTerminalTheme]: find-in-terminal is this app's affordance, not+/// something the scheme has an opinion about, and a highlight that moved with+/// the palette would be a different colour to hunt for per scheme.+const tangoTerminalTheme = TerminalTheme(+ cursor: Color(0xffffffff),+ selection: Color(0x66729fcf),+ foreground: Color(0xffffffff),+ background: Color(0xff300a24),+ black: Color(0xff2e3436),+ red: Color(0xffcc0000),+ green: Color(0xff4e9a06),+ yellow: Color(0xffc4a000),+ blue: Color(0xff3465a4),+ magenta: Color(0xff75507b),+ cyan: Color(0xff06989a),+ white: Color(0xffd3d7cf),+ brightBlack: Color(0xff555753),+ brightRed: Color(0xffef2929),+ brightGreen: Color(0xff8ae234),+ brightYellow: Color(0xfffce94f),+ brightBlue: Color(0xff729fcf),+ brightMagenta: Color(0xffad7fa8),+ brightCyan: Color(0xff34e2e2),+ brightWhite: Color(0xffeeeeec),+ searchHitBackground: Color(0xffffff2b),+ searchHitBackgroundCurrent: Color(0xff31ff26),+ searchHitForeground: Color(0xff000000),+);diff --git a/mobile/lib/terminal/terminal_theme_store.dart b/mobile/lib/terminal/terminal_theme_store.dartnew file mode 100644index 000000000..58b590e0a--- /dev/null+++ b/mobile/lib/terminal/terminal_theme_store.dart@@ -0,0 +1,112 @@+import 'package:flutter/foundation.dart';++import '../core/harness_file_store.dart';+import '../core/local_key_value_store.dart';++/// A colour scheme the terminal is allowed to draw itself in.+///+/// Separate from [HarnessPalette] on purpose. The app's palette dresses the+/// window — sidebar, tabs, dialogs — and until this existed the terminal's+/// ground was simply borrowed from it, so the only way to sit an agent on a+/// different colour was to repaint the whole app. That is one value answering+/// two questions: "what colour is Harness" and "what colour is the screen a+/// remote program is drawing into". They are not the same question, and the+/// font settings beside this one already answer the second independently.+///+/// Deliberately a closed enum rather than free colour fields: sixteen ANSI+/// slots plus foreground, background, cursor and selection is a surface no+/// preferences pane can make legible, and a half-chosen ramp renders TUIs+/// unreadable in ways the user cannot attribute to what they changed. Adding a+/// scheme later is one value here and one `const` in `terminal_theme.dart`.+enum TerminalThemeChoice {+ /// Today's behaviour, and still the default: ground and cursor follow the+ /// palette chosen in Settings ▸ Appearance, ANSI ramp from `darkTerminalTheme`.+ matchApp(+ 'Match app appearance',+ 'Ground and cursor follow Settings ▸ Appearance',+ ),++ /// ⚠️ Named for the PALETTE, not for the distribution that popularised it.+ /// These sixteen colours are the Tango Desktop Project's, which GNOME+ /// Terminal ships as its built-in `Tango` scheme. Calling it "Ubuntu" would+ /// name a downstream of it and leave nothing to call the scheme itself when a+ /// second one arrives.+ ///+ /// The one thing here that is NOT Tango is the ground: `#300A24` is Ubuntu's+ /// own aubergine, set as a custom text colour over the Tango palette. Tango's+ /// own dark is `#2E3436` — kept below as `black`, where it belongs.+ tango('Tango', "GNOME Terminal's palette on Ubuntu's aubergine ground");++ const TerminalThemeChoice(this.label, this.detail);++ /// What the picker row says.+ final String label;++ /// The second line under it — what changes, in the user's terms.+ final String detail;++ /// What a fresh install opens with, and what a reset returns to.+ static const fallback = matchApp;+}++/// The user's chosen terminal colour scheme, remembered across launches.+///+/// A [ValueNotifier] singleton over [HarnessFileStore], loaded by+/// `loadPersistedSettings()` before the first frame — see that function's doc+/// for why a store that loads late is worse than one that never persisted.+///+/// Unlike [TerminalFontStore] the value here is the *choice*, not a resolved+/// theme: a resolved [TerminalTheme] depends on the app palette too (for+/// [TerminalThemeChoice.matchApp]), and caching that pairing belongs with the+/// colours in `terminal_theme.dart` rather than in the thing that remembers a+/// preference.+class TerminalThemeStore extends ValueNotifier<TerminalThemeChoice> {+ TerminalThemeStore({LocalKeyValueStore? storage})+ : _storage = storage ?? HarnessFileStore.shared,+ super(TerminalThemeChoice.fallback);++ static const _key = 'terminal_theme';++ final LocalKeyValueStore _storage;++ /// Read the saved choice, if there is one. Failure — or a scheme name from a+ /// build that had one this one does not — is silent and lands on the default.+ /// An unreadable state file is not a reason to refuse to start.+ /// `readMany`, not a plain `read`, for a single key: it is the batch path+ /// [TerminalFontStore] and [AppearancePrefsStore] take, so on a shared file+ /// store this preference arrives in the same snapshot as theirs rather than+ /// as a second pass over a file that may have been rewritten in between.+ Future<void> load() async {+ try {+ final saved = await _storage.readMany([_key]);+ value =+ TerminalThemeChoice.values+ .where((choice) => choice.name == saved[_key])+ .firstOrNull ??+ TerminalThemeChoice.fallback;+ } catch (_) {+ value = TerminalThemeChoice.fallback;+ }+ }++ Future<void> set(TerminalThemeChoice choice) async {+ if (choice == value) return;+ value = choice;+ try {+ await _storage.write(_key, choice.name);+ } catch (_) {+ // Kept in memory for this run; see load()'s doc.+ }+ }++ Future<void> reset() => set(TerminalThemeChoice.fallback);++ /// Whether the current pick *is* the default — so a Reset control can say it+ /// has nothing to do.+ bool get isDefault => value == TerminalThemeChoice.fallback;+}++/// The one instance the app reads. Lives here rather than beside `main()` for+/// the same reason [terminalFontStore] does: the terminal panel and the+/// Settings pane must not reach into the entrypoint for it.+final terminalThemeStore = TerminalThemeStore();diff --git a/mobile/lib/terminal/terminal_typography.dart b/mobile/lib/terminal/terminal_typography.dartnew file mode 100644index 000000000..a60e6662f--- /dev/null+++ b/mobile/lib/terminal/terminal_typography.dart@@ -0,0 +1,78 @@+import '../core/apple_fonts.dart';++/// The default terminal face, per platform.+///+/// Every family named here has to actually resolve on the OS it is named for,+/// and a *monospace* one: the renderer measures one cell by laying out ten `m`+/// glyphs and dividing by ten (`TerminalPainter._measureCharSize`), so a+/// proportional substitute misaligns every column a TUI draws.+///+/// Asking for a face the system does not have is not a loud failure. Measured+/// on Ubuntu 26.04 with a real Linux build (`TextPainter`, 13px, advance width+/// of `m` vs `i` — equal means monospace):+///+/// ```text+/// DejaVu Sans Mono m=7.83 i=7.83 ← monospace+/// Ubuntu Sans Mono m=7.28 i=7.28 ← monospace+/// Liberation Mono m=7.80 i=7.80 ← monospace+/// .AppleSystemUIFontMonospaced m=11.22 i=3.16 ← PROPORTIONAL+/// Menlo m=11.22 i=3.16 ← PROPORTIONAL+/// monospace (the generic) m=11.22 i=3.16 ← PROPORTIONAL+/// NoSuchFamilyXYZ m=11.22 i=3.16 ← the engine's own default+/// ```+///+/// Two things follow. The old macOS-only stack rendered the terminal in a+/// proportional face on Linux, at 3.5× the width for `m` over `i` — that is the+/// broken grid. And **the trailing `'monospace'` is inert**: Flutter resolves+/// families through Skia, which does not honour fontconfig's generic aliases,+/// so it measures exactly like a family that does not exist. It stays in the+/// lists as a last resort for other engines, but it is not a safety net — every+/// chain has to name a real face it can reach. On Linux that anchor is DejaVu+/// Sans Mono, the only monospace `ubuntu-desktop-minimal` depends on.+///+/// The live, user-chosen typography lives in `terminalFontStore`, not here;+/// these are what a fresh install opens with and what `reset()` returns to.++/// SF Mono's CoreText family name.+///+/// Flutter does not reliably resolve the human-facing `SF Mono` name on macOS;+/// this is the system alias that CoreText resolves to Apple's monospaced face.+const macTerminalFontFamily = '.AppleSystemUIFontMonospaced';++const macTerminalFontFallback = <String>[+ 'Menlo',+ 'Monaco',+ 'Courier New',+ 'monospace',+];++/// DejaVu Sans Mono, and why it leads on Linux.+///+/// It is the only monospace `ubuntu-desktop-minimal` *depends* on — the Ubuntu+/// and Noto mono packages are recommendations, which an install can decline —+/// and the only one of them carrying `✔ ✗ ● ╭ ▏`, the glyphs an agent's TUI+/// draws. That matters more than it sounds: a glyph missing from the primary+/// face is fetched from a fallback at a different advance width, and the grid+/// goes ragged in exactly the places a coding agent puts its output.+const linuxTerminalFontFamily = 'DejaVu Sans Mono';++const linuxTerminalFontFallback = <String>[+ 'Ubuntu Sans Mono',+ 'Noto Sans Mono',+ 'Liberation Mono',+ 'monospace',+];++/// The default face for the platform this build is running on.+///+/// A getter, not a `const`: the answer depends on the host. The per-platform+/// constants above stay `const` so `TerminalFontChoice` can still name them+/// from its const constructor.+String get terminalFontFamily =>+ hasAppleFonts ? macTerminalFontFamily : linuxTerminalFontFamily;++List<String> get terminalFontFallback =>+ hasAppleFonts ? macTerminalFontFallback : linuxTerminalFontFallback;++/// The default terminal font size — the same on every platform.+const terminalFontSize = 13.0;diff --git a/mobile/lib/terminal/terminal_viewport.dart b/mobile/lib/terminal/terminal_viewport.dartnew file mode 100644index 000000000..639a7f912--- /dev/null+++ b/mobile/lib/terminal/terminal_viewport.dart@@ -0,0 +1,18 @@+/// Local UI boundary for controls that operate on the rendered terminal but+/// do not travel to the remote tmux pane.+enum TerminalFindAction { open, next, previous }++abstract interface class TerminalViewport {+ /// One report from the hardware dial.+ ///+ /// [phase] is 0 (down), 1 (move), or 2 (up). [dy] is the movement in glass+ /// pixels and [velocity] is glass pixels per second at release.+ void scroll(int phase, int dy, int velocity);++ /// Opens or steps through local terminal output without sending a key.+ void find(TerminalFindAction action);++ /// Claims an already mounted editor before navigation's next rendered frame.+ /// False means the destination has no ready input view yet.+ bool focusInput();+}diff --git a/mobile/lib/theme/app_theme.dart b/mobile/lib/theme/app_theme.dartnew file mode 100644index 000000000..244f6367f--- /dev/null+++ b/mobile/lib/theme/app_theme.dart@@ -0,0 +1,101 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;++/// Shared terminal-shell palette.+///+/// ⚠️ THESE ARE NOW ADAPTERS, NOT VALUES, AND THAT IS THE POINT. Every one of+/// them used to be a `const` slate colour, which is why nine files could read+/// this palette and still paint a dark window while the rest of the app went+/// light: a constant cannot answer "which theme is it".+///+/// Each name below resolves through [grid.AppPalette], the design system that+/// already carries a light and a dark value for every role — and carries the+/// contrast ratio it was chosen for, in a comment, next to it. Mapping onto it+/// rather than inventing a second light palette is deliberate: two palettes for+/// one app do not stay in agreement, and the one that drifts is always the one+/// nobody is looking at.+///+/// The DARK values are unchanged in spirit but no longer identical — they are+/// now whatever the design system says dark is, so the two halves of the app+/// stop disagreeing by a few points of grey along the seam between them.+///+/// Being getters, they cannot appear in a `const` expression. That is a feature:+/// the compiler names every site that froze a colour at build time, which is+/// exactly the set of places light mode would otherwise have missed.+abstract final class AppColors {+ /// The window itself.+ static Color get background => grid.AppPalette.windowBg;++ /// The rail column, set apart from [background] by a hairline rather than a tone.+ static Color get sidebar => grid.AppPalette.panelBg;++ /// Quiet cards and input fills.+ static Color get surface => grid.AppPalette.cardBg;+ static Color get hover => grid.AppPalette.cardBgHover;+ static Color get selected => grid.AppSurface.selectedFill;++ /// A hairline between blocks, and the stronger one that has to hold a shape.+ static Color get border => grid.AppPalette.divider;+ static Color get borderStrong => grid.AppPalette.guide;++ /// Ink, in three weights.+ static Color get text => grid.AppPalette.textPrimary;+ static Color get textSoft => grid.AppPalette.textSecondary;+ static Color get muted => grid.AppPalette.textFaint;+ static Color get mutedStrong => grid.AppPalette.textSecondary;++ /// The accent as a MARK on a surface, not as a fill behind white text — which+ /// is what these call sites use it for (an icon, a link, a focused rim).+ static Color get accent => grid.AppPalette.accentOnSurface;++ static Color get success => grid.AppPalette.online;+ static Color get warning => grid.AppPalette.warn;++ /// Error ink on a surface. NOT [grid.AppPalette.dangerFill], which is tuned to+ /// carry white lettering on top of it and is far too dark to read AS text.+ static Color get danger =>+ grid.AppTheme.pick(const Color(0xFFB3261E), const Color(0xFFF2544B));+}++/// The app's two font stacks — adapters over the design system's, exactly like+/// [AppColors] above.+///+/// Mono is for strings the user copies (a token, a path, terminal output);+/// everything else is read, not copied, and reads faster in the system's own UI+/// face. Which face that is belongs to `grid.AppFont`, which answers per+/// platform — these used to re-declare the macOS names as `const`, which is how+/// the whole app came to be drawn in Noto Sans on Ubuntu (nothing in the Apple+/// stack resolves there) and how `mono` here drifted to `'Menlo'` while the+/// token said `.AppleSystemUIFontMonospaced`. Nothing is `const` for the same+/// reason nothing in [AppColors] is: freezing the value is what breaks the+/// second platform.+abstract final class AppFonts {+ static String get sans => grid.AppFont.sans;+ static List<String> get sansFallback => grid.AppFont.sansFallback;+ static String get mono => grid.AppFont.mono;+ static List<String> get monoFallback => grid.AppFont.monoFallback;+}++/// The app's ThemeData now comes from `grid.buildAppTheme` — see `main.dart`.+///+/// ⚠️ DO NOT REBUILD ONE HERE. What used to live at this spot was a second,+/// hand-written `ThemeData` (`AppTheme.terminalLight/terminalDark`), and it was+/// the one the app actually wore: `grid.buildAppTheme` had ZERO call sites in+/// `lib/` and was reached only from two tests. Everything the design system+/// defines was therefore dead at runtime —+///+/// * all ten `TextTheme` steps were assigned the SAME style (family and colour+/// only), so size, weight and `AppFont.trackingFor` fell through to+/// Material's Roboto metrics. That is why ~150 call sites hand-type+/// `fontSize:` across 14 different values: the theme gave them nothing, so+/// each screen re-measured the ramp by eye.+/// * `AppControl` had 0 references outside the token file — no call site could+/// see the 32/28/36 control heights or the radius ladder.+/// * `menuTheme` was null, so a `MenuAnchor` that passed no style of its own+/// opened Material's raw default.+///+/// [AppColors] and [AppFonts] above stay: they are thin aliases onto+/// `grid.AppPalette`, which is what let the swap be two lines in `main.dart`+/// instead of renaming 500 call sites. Adding chrome back here would recreate+/// exactly the split this deletion closed.diff --git a/mobile/lib/update/desktop_updater.dart b/mobile/lib/update/desktop_updater.dartnew file mode 100644index 000000000..f46fd1938--- /dev/null+++ b/mobile/lib/update/desktop_updater.dart@@ -0,0 +1,427 @@+import 'dart:async';+import 'dart:ffi';+import 'dart:io';++import 'package:cryptography/cryptography.dart';+import 'package:dio/dio.dart';+import 'package:flutter/foundation.dart';++import '../core/app_version.dart';++/// Published by `scripts/upload-desktop.sh` (`make upload-desktop`) — see+/// `RELEASE.md` for the full publish-side design this mirrors.+const _defaultMetadataUrl =+ 'https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/desktop/metadata.json';++/// Override for testing against a scratch manifest without touching the real one — see RELEASE.md's+/// "Rolling out safely" section. Empty (the default) means "use the real manifest".+const _metadataUrlOverride = String.fromEnvironment(+ 'DESKTOP_UPDATE_METADATA_URL',+);++/// The macOS build every Mac can run, rendered on Skia: what an Intel Mac installs, what every install+/// from before the Intel/Apple Silicon split polls on either CPU, and what the website download+/// serves. Must match the `intel` row of scripts/publish-macos-variant.sh — RELEASE.md, "Two macOS+/// builds", has the why.+const _otaKeyMacOS = 'desktop-macos';++/// The Apple Silicon build, rendered on Impeller. Must match the `apple-silicon` row of+/// scripts/publish-macos-variant.sh.+const _otaKeyMacOSArm64 = 'desktop-macos-arm64';++/// `arm64` or `x64` for the CPU this process runs on: which Linux artifact to fetch, and whether the+/// Apple Silicon macOS build is on offer. An Apple Silicon Mac running this under Rosetta reports x64+/// and is offered only the Skia build — harmless, since both macOS builds are universal.+String _currentArchitecture() => switch (Abi.current()) {+ Abi.linuxArm64 || Abi.macosArm64 || Abi.windowsArm64 => 'arm64',+ Abi.linuxX64 || Abi.macosX64 || Abi.windowsX64 => 'x64',+ _ => throw UnsupportedError(+ 'Harness Desktop updates do not support ${Abi.current()}',+ ),+};++String get _metadataUrl => _metadataUrlOverride.isNotEmpty+ ? _metadataUrlOverride+ : _defaultMetadataUrl;++class UpdateInfo {+ final String version;+ final String url;+ final String sha256;+ final int size;++ const UpdateInfo({+ required this.version,+ required this.url,+ required this.sha256,+ required this.size,+ });+}++/// A downloaded, sha256-verified build sitting in a temp directory, not yet swapped into place.+class StagedUpdate {+ final String version;++ /// On macOS: `.../Harness.app` inside [stagingDirPath], unpacked and version-confirmed. On+ /// Linux: the downloaded `.AppImage` file itself (already made executable), directly inside+ /// [stagingDirPath] — there is nothing to unpack.+ final String bundlePath;+ final String stagingDirPath;++ const StagedUpdate({+ required this.version,+ required this.bundlePath,+ required this.stagingDirPath,+ });+}++/// Strict X.Y.Z compare, prerelease/build metadata ignored — same rule as the CLI's own+/// `semverGt` (cli/src/lib/selfUpdate.ts in the harness CLI repo), so publishing an old build can+/// never look newer than what's already running.+bool semverGt(String a, String b) {+ final x = _parseSemverCore(a);+ final y = _parseSemverCore(b);+ if (x == null || y == null) return false;+ for (var i = 0; i < 3; i++) {+ if (x[i] != y[i]) return x[i] > y[i];+ }+ return false;+}++List<int>? _parseSemverCore(String version) {+ final match = RegExp(r'^(\d+)\.(\d+)\.(\d+)').firstMatch(version);+ if (match == null) return null;+ return [+ int.parse(match.group(1)!),+ int.parse(match.group(2)!),+ int.parse(match.group(3)!),+ ];+}++String _singleQuote(String value) => "'${value.replaceAll("'", "'\\''")}'";++/// Resolves the path the running build should be swapped at.+///+/// On macOS this walks up from the running executable to the enclosing+/// `.app` bundle — `.../Harness.app/Contents/MacOS/Harness` -> `.../Harness.app`.+/// On Linux the packaged build is a single `.AppImage` file (see+/// `scripts/upload-desktop-linux.sh`), and a running AppImage executes from a temporary FUSE mount,+/// not from that file — so the file's own path comes from [appImagePath] (tests) or the `APPIMAGE`+/// environment variable the AppImage runtime sets on launch (production), never from+/// `Platform.resolvedExecutable`.+String? currentBundlePath({+ String? executablePath,+ bool? isLinux,+ String? appImagePath,+}) {+ if (isLinux ?? Platform.isLinux) {+ return appImagePath ?? Platform.environment['APPIMAGE'];+ }+ final resolved = executablePath ?? Platform.resolvedExecutable;+ var dir = File(resolved).parent;+ for (var i = 0; i < 6; i++) {+ if (dir.path.endsWith('.app')) return dir.path;+ final parent = dir.parent;+ if (parent.path == dir.path) return null; // reached filesystem root+ dir = parent;+ }+ return null;+}++Future<void> _defaultLaunchDetached(String command) async {+ await Process.start(Platform.isLinux ? '/bin/bash' : '/bin/zsh', [+ '-l',+ '-c',+ command,+ ], mode: ProcessStartMode.detached);+}++/// Checks the public GCS manifest for a newer desktop build than the one currently running,+/// downloads + verifies it, and — once the caller applies it — swaps it into place and relaunches.+/// See `RELEASE.md` for the publish side and the full design (why this doesn't+/// silently auto-restart like the CLI's own self-updater does).+class DesktopUpdater {+ final Dio _dio;+ final Future<void> Function(String command) _launchDetached;+ final String _metadataUrlForInstance;+ final bool _releaseMode;+ final bool _enabled;+ final bool _isLinux;+ final String _architecture;++ DesktopUpdater({+ this._enabled = true,+ Dio? dio,+ Future<void> Function(String command)? launchDetached,+ // Defaults to the real manifest (or the --dart-define build-time override — see RELEASE.md's+ // "Rolling out safely"). Tests and any other caller that needs a different manifest (e.g. a+ // scratch one) pass this directly instead.+ String? metadataUrl,+ // Defaults to the real Flutter build mode — see checkOnce()'s guard. `flutter test` always runs+ // outside release mode, so tests that want to exercise checkOnce()'s real logic pass `true` here.+ bool? releaseMode,+ // Defaults to the real host OS. Tests force this to exercise the Linux packaging/relaunch branch+ // (a single downloaded file, no unpacking) from any host, since that branch needs no extra+ // tooling beyond the standard library, unlike ditto/plutil on macOS.+ bool? isLinux,+ // Defaults to the running CPU (`arm64`/`x64`): which Linux artifact to fetch, and whether the+ // Apple Silicon macOS build is on offer. Tests override it to exercise every key from any host.+ String? architecture,+ }) : _dio =+ dio ??+ Dio(+ BaseOptions(+ connectTimeout: const Duration(seconds: 10),+ receiveTimeout: const Duration(seconds: 30),+ ),+ ),+ _launchDetached = launchDetached ?? _defaultLaunchDetached,+ _metadataUrlForInstance = metadataUrl ?? _metadataUrl,+ _releaseMode = releaseMode ?? kReleaseMode,+ _isLinux = isLinux ?? Platform.isLinux,+ _architecture = architecture ?? _currentArchitecture();++ /// The manifest entries this build may install, most preferred first — [_newestEntry] takes the+ /// newest of them, an earlier key winning a tie.+ List<String> get _otaKeys {+ if (_isLinux) return ['desktop-linux-$_architecture'];+ // An Intel Mac reads only the Skia build: the arm64 one renders on Impeller, which is exactly+ // what it must not get, however new.+ if (_architecture != 'arm64') return const [_otaKeyMacOS];+ return const [_otaKeyMacOSArm64, _otaKeyMacOS];+ }++ /// Fetches the manifest and returns the newer entry, or null if this app is already current (or+ /// the manifest/network is unavailable — treated the same as "nothing to do", never surfaced as an+ /// error; this runs unattended in the background).+ ///+ /// A debug or profile build never reports an update — self-installing (swapping the running .app+ /// bundle for a downloaded release build and relaunching, see [applyStaged]) makes no sense for a+ /// local dev build and would silently clobber it mid-session.+ Future<UpdateInfo?> checkOnce({String? currentVersion}) async {+ if (!_enabled || !_releaseMode) return null;+ try {+ final running = currentVersion ?? await runningAppVersion();+ final response = await _dio.get<Map<String, dynamic>>(+ _metadataUrlForInstance,+ );+ final newest = _newestEntry(response.data);+ if (newest == null || !semverGt(newest.version, running)) return null;+ return newest;+ } catch (error) {+ debugPrint('DesktopUpdater.checkOnce: $error');+ return null;+ }+ }++ /// The newest of this host's [_otaKeys] entries, an earlier key winning a tie — so on Apple Silicon+ /// a release that published both macOS builds installs the Impeller one, while a release that only+ /// moved `desktop-macos` still reaches it instead of hiding behind an older arm64 entry.+ UpdateInfo? _newestEntry(Map<String, dynamic>? manifest) {+ UpdateInfo? newest;+ for (final key in _otaKeys) {+ final entry = _parseEntry(manifest?[key]);+ if (entry == null) continue;+ if (newest == null || semverGt(entry.version, newest.version)) {+ newest = entry;+ }+ }+ return newest;+ }++ /// One manifest entry, or null when it is missing or malformed — "nothing to install from this+ /// key", never an error.+ static UpdateInfo? _parseEntry(Object? entry) {+ if (entry is! Map) return null;+ final version = entry['version'];+ final url = entry['url'];+ final sha256 = entry['sha256'];+ final size = entry['size'];+ if (version is! String ||+ url is! String ||+ sha256 is! String ||+ size is! int) {+ return null;+ }+ return UpdateInfo(version: version, url: url, sha256: sha256, size: size);+ }++ /// Checks once immediately, then every [interval] — calls [onUpdateAvailable] each time a newer+ /// build is found (re-finding the same version on a later tick is harmless; the caller is expected+ /// to no-op if it's already showing that version). Cancel the returned [Timer] to stop.+ Timer startChecking({+ Duration interval = const Duration(minutes: 1),+ required void Function(UpdateInfo info) onUpdateAvailable,+ // Forwarded to checkOnce() on every tick — tests pass this to avoid checkOnce()'s default+ // runningAppVersion() call, which (via PackageInfo.fromPlatform()) needs a platform method+ // channel real production code gets for free but a plain `test()` doesn't.+ String? currentVersion,+ }) {+ void tick() {+ unawaited(+ checkOnce(currentVersion: currentVersion).then((info) {+ if (info != null) onUpdateAvailable(info);+ }),+ );+ }++ tick();+ return Timer.periodic(interval, (_) => tick());+ }++ /// Downloads [info] and verifies its sha256 BEFORE trusting the bytes. On macOS, unpacks the zip+ /// and confirms the staged bundle's own Info.plist really carries [info].version — the archive+ /// holds more than the hash alone authenticates. On Linux, the download itself is the artifact (a+ /// single AppImage file), so the sha256 check already covers everything there is: it is made+ /// executable and staged as-is, with nothing to unpack or recheck.+ /// Returns null (and cleans up anything partially written) on any verification failure.+ Future<StagedUpdate?> downloadAndStage(UpdateInfo info) async {+ if (!_enabled) return null;+ Directory? stagingDir;+ try {+ final response = await _dio.get<List<int>>(+ info.url,+ options: Options(responseType: ResponseType.bytes),+ );+ final bytes = response.data;+ if (bytes == null || bytes.length != info.size) {+ debugPrint(+ 'DesktopUpdater: unexpected download size for ${info.version}',+ );+ return null;+ }+ final hash = await Sha256().hash(bytes);+ final actualSha = hash.bytes+ .map((b) => b.toRadixString(16).padLeft(2, '0'))+ .join();+ if (actualSha != info.sha256) {+ debugPrint(+ 'DesktopUpdater: sha256 mismatch for ${info.version} — discarding download',+ );+ return null;+ }++ stagingDir = await Directory.systemTemp.createTemp('harness-update-');++ if (_isLinux) {+ final appImagePath =+ '${stagingDir.path}/Harness-linux-$_architecture.AppImage';+ await File(appImagePath).writeAsBytes(bytes, flush: true);+ await Process.run('/bin/chmod', ['+x', appImagePath]);+ return StagedUpdate(+ version: info.version,+ bundlePath: appImagePath,+ stagingDirPath: stagingDir.path,+ );+ }++ final archivePath = '${stagingDir.path}/Harness-macos.zip';+ await File(archivePath).writeAsBytes(bytes, flush: true);++ final unpack = await Process.run('/usr/bin/ditto', [+ '-x',+ '-k',+ archivePath,+ stagingDir.path,+ ]);+ if (unpack.exitCode != 0) {+ debugPrint('DesktopUpdater: ditto unpack failed: ${unpack.stderr}');+ await stagingDir.delete(recursive: true);+ return null;+ }++ final bundlePath = '${stagingDir.path}/Harness.app';+ if (!Directory(bundlePath).existsSync()) {+ debugPrint(+ 'DesktopUpdater: no Harness bundle inside the downloaded archive',+ );+ await stagingDir.delete(recursive: true);+ return null;+ }++ final plutil = await Process.run('/usr/bin/plutil', [+ '-extract',+ 'CFBundleShortVersionString',+ 'raw',+ '$bundlePath/Contents/Info.plist',+ ]);+ final stagedVersion = plutil.exitCode == 0+ ? (plutil.stdout as String?)?.trim()+ : null;+ if (stagedVersion != info.version) {+ debugPrint(+ 'DesktopUpdater: staged bundle reports version "$stagedVersion", expected "${info.version}"',+ );+ await stagingDir.delete(recursive: true);+ return null;+ }++ return StagedUpdate(+ version: info.version,+ bundlePath: bundlePath,+ stagingDirPath: stagingDir.path,+ );+ } catch (error) {+ debugPrint('DesktopUpdater.downloadAndStage: $error');+ try {+ await stagingDir?.delete(recursive: true);+ } catch (_) {+ // best-effort cleanup+ }+ return null;+ }+ }++ /// Hands off to a detached helper that waits for THIS process (pid [selfPid]) to exit, backs the+ /// running bundle up as `Harness.app.prev`, swaps [staged] into place, relaunches it, and restores+ /// the backup if the relaunch doesn't stay alive a few seconds later. Returns as soon as the helper+ /// has been spawned — the caller owns actually quitting (e.g. `exit(0)`) right after; this never+ /// exits the app itself, and never touches anything if [runningBundlePath] can't be resolved.+ Future<bool> applyStaged(+ StagedUpdate staged, {+ required int selfPid,+ String? runningBundlePath,+ }) async {+ if (!_enabled) return false;+ final bundlePath =+ runningBundlePath ?? currentBundlePath(isLinux: _isLinux);+ if (bundlePath == null) {+ debugPrint(+ 'DesktopUpdater: could not resolve the running bundle path — not applying',+ );+ return false;+ }+ final prevPath = '$bundlePath.prev';+ // On Linux, `bundlePath` IS the AppImage file (see currentBundlePath) — there is no enclosing+ // directory to exec into, so the "executable" is the swapped file itself. downloadAndStage()+ // already made staged.bundlePath executable, and mv preserves that bit across the swap below.+ final executableInBundle = _isLinux+ ? bundlePath+ : '$bundlePath/Contents/MacOS/Harness';+ // macOS relaunches through `open -n` (LaunchServices, so Dock/menu-bar identity stays correct).+ // Linux has no such registry for a plain packaged binary — exec it directly, detached from this+ // shell so it outlives the helper script.+ final relaunch = _isLinux+ ? 'nohup ${_singleQuote(executableInBundle)} >/dev/null 2>&1 & disown'+ : 'open -n ${_singleQuote(bundlePath)}';+ final command =+ '''+while kill -0 $selfPid 2>/dev/null; do sleep 0.2; done+rm -rf ${_singleQuote(prevPath)}+mv ${_singleQuote(bundlePath)} ${_singleQuote(prevPath)}+mv ${_singleQuote(staged.bundlePath)} ${_singleQuote(bundlePath)}+$relaunch+sleep 3+if pgrep -f ${_singleQuote(executableInBundle)} >/dev/null; then+ rm -rf ${_singleQuote(prevPath)}+else+ rm -rf ${_singleQuote(bundlePath)}+ mv ${_singleQuote(prevPath)} ${_singleQuote(bundlePath)}+ $relaunch+fi+rm -rf ${_singleQuote(staged.stagingDirPath)}+''';+ await _launchDetached(command);+ return true;+ }+}diff --git a/mobile/lib/update/manual_update_check.dart b/mobile/lib/update/manual_update_check.dartnew file mode 100644index 000000000..70f5ce7cc--- /dev/null+++ b/mobile/lib/update/manual_update_check.dart@@ -0,0 +1,12 @@+import 'desktop_updater.dart';++/// Result of a user-initiated check. A manually checked version remains+/// installable even when the user skipped its background notification earlier.+class ManualUpdateCheck {+ final UpdateInfo? update;+ final bool isSkipped;++ const ManualUpdateCheck({this.update, this.isSkipped = false});++ bool get isUpToDate => update == null;+}diff --git a/mobile/lib/usage/claude_usage_source.dart b/mobile/lib/usage/claude_usage_source.dartnew file mode 100644index 000000000..4787f6ff6--- /dev/null+++ b/mobile/lib/usage/claude_usage_source.dart@@ -0,0 +1,137 @@+import 'package:dio/dio.dart';++import '../logging/http_log.dart';+import 'usage_account_key.dart';+import 'usage_credentials.dart';+import 'usage_source.dart';+import 'usage_window.dart';++/// Claude Code's rate limits, read with the token `claude login` left behind.+///+/// ⚠️ **This endpoint is undocumented.** It is what the CLI itself asks when it+/// prints `/usage`, and it answers only to a token minted for the CLI — hence+/// the beta header and the CLI's own user agent, which together are what make+/// an OAuth token issued to Claude Code acceptable here. It can change without+/// notice, and when it does the failure is a parse error or a 4xx, both of+/// which this reports as a state rather than a crash. **TODO(BE):** replace+/// with a supported endpoint if one appears.+class ClaudeUsageSource implements UsageSource {+ ClaudeUsageSource({Dio? dio, UsageCredentials? credentials})+ : _dio = dio ?? attachHttpLog(buildUsageDio()),+ _credentials = credentials ?? const UsageCredentials();++ final Dio _dio;+ final UsageCredentials _credentials;++ static const _url = 'https://api.anthropic.com/api/oauth/usage';++ @override+ UsageProvider get provider => UsageProvider.claude;++ @override+ Future<ProviderUsage> read() async {+ final token = await _credentials.claude();+ if (token == null) return signedOut(provider);+ final accountId = await _credentials.claudeAccountId();+ // An expired token is spent as a sign-in rather than as a round trip: this+ // app does not refresh what the CLI owns, so the request could only fail.+ if (token.isExpired) {+ return ProviderUsage(+ provider: provider,+ status: UsageStatus.signedOut,+ message: 'Claude session expired — run claude to sign in again',+ );+ }+ try {+ final response = await _dio.getUri<Object?>(+ Uri.parse(_url),+ options: Options(+ headers: {+ 'Authorization': 'Bearer ${token.accessToken}',+ 'anthropic-beta': 'oauth-2025-04-20',+ 'User-Agent': 'claude-code/2.1.0',+ },+ ),+ );+ return claudeUsageFromAnswer(+ statusCode: response.statusCode,+ body: response.data,+ account: accountId == null+ ? null+ : usageAccountKey(provider, accountId),+ );+ } on DioException {+ return usageFailureFor(provider, null)!;+ }+ }++ /// The three windows the CLI itself shows, in the order they bite.+ ///+ /// Fable's weekly allowance has been spelled three ways across releases, so+ /// all three are tried — an absent window is simply not drawn, which is why+ /// a build reading a newer server loses a row rather than the whole panel.+ static ProviderUsage _mapWindows(+ Map<Object?, Object?> data, {+ String? account,+ }) {+ final windows = <UsageWindow>[+ ?_window('Session', data['five_hour']),+ ?_window(kWeeklyWindowLabel, data['seven_day']),+ ?_window(+ 'Fable',+ data['fable_weekly'] ??+ data['fable_seven_day'] ??+ data['seven_day_fable'],+ ),+ ];+ if (windows.isEmpty) {+ return const ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.failed,+ message: 'Claude reported no limits',+ );+ }+ return ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.ok,+ windows: windows,+ fetchedAt: DateTime.now(),+ account: account,+ );+ }++ static UsageWindow? _window(String label, Object? raw) {+ if (raw is! Map) return null;+ final used = parseUsedPercent([raw['utilization'], raw['used_percentage']]);+ if (used == null) return null;+ return UsageWindow(+ label: label,+ usedPercent: used,+ resetsAt: parseResetTimestamp(raw['resets_at']),+ );+ }+}++/// What Claude's usage endpoint said, as the rail draws it.+///+/// Shared by the two places an answer comes from — this computer asking with+/// its own token, and a REMOTE machine asking with its own and handing back+/// exactly what the vendor sent (`usage_read`, see `remote_usage.dart`). One+/// reading of the answer for both, so a window cannot be named one way here and+/// another way for a machine across the relay.+ProviderUsage claudeUsageFromAnswer({+ required int? statusCode,+ required Object? body,+ String? account,+}) {+ final failure = usageFailureFor(UsageProvider.claude, statusCode);+ if (failure != null) return failure;+ if (body is! Map) {+ return const ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.failed,+ message: 'Claude answered in a shape this build cannot read',+ );+ }+ return ClaudeUsageSource._mapWindows(body, account: account);+}diff --git a/mobile/lib/usage/codex_usage_source.dart b/mobile/lib/usage/codex_usage_source.dartnew file mode 100644index 000000000..25b5b59cd--- /dev/null+++ b/mobile/lib/usage/codex_usage_source.dart@@ -0,0 +1,134 @@+import 'package:dio/dio.dart';++import '../logging/http_log.dart';+import 'usage_account_key.dart';+import 'usage_credentials.dart';+import 'usage_source.dart';+import 'usage_window.dart';++/// Codex's rate limits, read with the token `codex login` left in+/// `~/.codex/auth.json`.+///+/// ⚠️ Undocumented, on the same terms as [ClaudeUsageSource]: this is the+/// backend the Codex CLI itself asks, and it can change without notice.+///+/// Codex numbers its windows rather than naming them — a primary and a+/// secondary, whose real durations arrive in the payload — so the labels here+/// are derived from `limit_window_seconds` instead of hardcoded. A build that+/// printed "5h" for a window the server had quietly changed to 24h would be+/// confidently wrong, which is worse than saying nothing.+class CodexUsageSource implements UsageSource {+ CodexUsageSource({Dio? dio, UsageCredentials? credentials})+ : _dio = dio ?? attachHttpLog(buildUsageDio()),+ _credentials = credentials ?? const UsageCredentials();++ final Dio _dio;+ final UsageCredentials _credentials;++ static const _url = 'https://chatgpt.com/backend-api/wham/usage';++ @override+ UsageProvider get provider => UsageProvider.codex;++ @override+ Future<ProviderUsage> read() async {+ final token = await _credentials.codex();+ if (token == null) return signedOut(provider);+ final accountId = await _credentials.codexAccountId();+ try {+ final response = await _dio.getUri<Object?>(+ Uri.parse(_url),+ options: Options(+ headers: {+ 'Authorization': 'Bearer ${token.accessToken}',+ 'ChatGPT-Account-Id': ?accountId,+ },+ ),+ );+ return codexUsageFromAnswer(+ statusCode: response.statusCode,+ body: response.data,+ account: accountId == null+ ? null+ : usageAccountKey(provider, accountId),+ );+ } on DioException {+ return usageFailureFor(provider, null)!;+ }+ }++ static ProviderUsage _mapWindows(+ Map<Object?, Object?> data, {+ String? account,+ }) {+ final limits = data['rate_limit'];+ final windows = limits is Map+ ? <UsageWindow>[+ ?_window(limits['primary_window']),+ ?_window(limits['secondary_window']),+ ]+ : const <UsageWindow>[];+ if (windows.isEmpty) {+ return const ProviderUsage(+ provider: UsageProvider.codex,+ status: UsageStatus.failed,+ message: 'Codex reported no limits',+ );+ }+ return ProviderUsage(+ provider: UsageProvider.codex,+ status: UsageStatus.ok,+ windows: windows,+ fetchedAt: DateTime.now(),+ account: account,+ );+ }++ static UsageWindow? _window(Object? raw) {+ if (raw is! Map) return null;+ final used = parseUsedPercent([raw['used_percent']]);+ if (used == null) return null;+ return UsageWindow(+ label: _labelFor(raw['limit_window_seconds']),+ usedPercent: used,+ resetsAt: parseResetTimestamp(raw['reset_at']),+ );+ }++ /// Names a window by how long it actually is.+ ///+ /// Falls back to the neutral "Limit" rather than guessing: a window whose+ /// duration the server did not send is one this build knows nothing about,+ /// and a made-up "5h" beside a real percentage would be read as measured.+ static String _labelFor(Object? seconds) {+ final value = seconds is num && seconds.isFinite && seconds > 0+ ? seconds.round()+ : null;+ if (value == null) return 'Limit';+ final hours = value ~/ 3600;+ if (hours < 1) return '${value ~/ 60}m';+ if (hours < 24) return '${hours}h';+ final days = hours ~/ 24;+ return days == 7 ? kWeeklyWindowLabel : '${days}d';+ }+}++/// What Codex's usage endpoint said, as the rail draws it — shared by this+/// computer's own reading and a remote machine's, for the reason+/// [claudeUsageFromAnswer] gives.+ProviderUsage codexUsageFromAnswer({+ required int? statusCode,+ required Object? body,+ String? account,+}) {+ final failure = usageFailureFor(UsageProvider.codex, statusCode);+ if (failure != null) return failure;+ if (body is! Map) {+ return const ProviderUsage(+ provider: UsageProvider.codex,+ status: UsageStatus.failed,+ message: 'Codex answered in a shape this build cannot read',+ );+ }+ return CodexUsageSource._mapWindows(body, account: account);+}diff --git a/mobile/lib/usage/remote_usage.dart b/mobile/lib/usage/remote_usage.dartnew file mode 100644index 000000000..c4115473f--- /dev/null+++ b/mobile/lib/usage/remote_usage.dart@@ -0,0 +1,70 @@+import 'claude_usage_source.dart';+import 'codex_usage_source.dart';+import 'usage_source.dart';+import 'usage_window.dart';++/// One remote machine's `usage_read_result`, as readings the rail can draw.+///+/// The machine answered with its vendors' replies exactly as they came — HTTP+/// status and body (`autonomous-harness/cli/src/lib/accountUsage.ts`) — so they+/// are read here by the SAME mappers that read this computer's own+/// ([claudeUsageFromAnswer], [codexUsageFromAnswer]). A window cannot be named+/// one way for this Mac and another way for a machine across the relay, because+/// there is only one place that names it.+///+/// Never throws: an entry this build cannot read is dropped rather than failing+/// the machine's whole answer, and an answer with no readable entry is empty —+/// which the caller treats as a machine with nothing to add.+List<ProviderUsage> parseUsageReadResult(Map<String, dynamic> reply) {+ final providers = reply['providers'];+ if (providers is! List) return const [];+ return [+ for (final entry in providers)+ if (entry is Map) ?_readingFrom(entry),+ ];+}++ProviderUsage? _readingFrom(Map<Object?, Object?> entry) {+ final provider = switch (entry['provider']) {+ 'claude' => UsageProvider.claude,+ 'codex' => UsageProvider.codex,+ // A provider a newer CLI reports and this build has never heard of.+ _ => null,+ };+ if (provider == null) return null;+ final account = entry['account'];+ final accountKey = account is String && account.isNotEmpty ? account : null;+ switch (entry['outcome']) {+ case 'answered':+ final status = entry['httpStatus'];+ final statusCode = status is int ? status : null;+ final body = entry['body'];+ return switch (provider) {+ UsageProvider.claude => claudeUsageFromAnswer(+ statusCode: statusCode,+ body: body,+ account: accountKey,+ ),+ UsageProvider.codex => codexUsageFromAnswer(+ statusCode: statusCode,+ body: body,+ account: accountKey,+ ),+ };+ case 'signedOut':+ // The machine's own sentence when it has one — it is the side that knows+ // whether the session expired or was never there.+ final message = entry['message'];+ return message is String && message.isNotEmpty+ ? ProviderUsage(+ provider: provider,+ status: UsageStatus.signedOut,+ message: message,+ )+ : signedOut(provider);+ default:+ // `unreachable`, or an outcome a newer CLI invented: the vendor was not+ // heard from, which reads exactly like this computer failing to reach it.+ return usageFailureFor(provider, null);+ }+}diff --git a/mobile/lib/usage/usage_account_key.dart b/mobile/lib/usage/usage_account_key.dartnew file mode 100644index 000000000..e55b9271f--- /dev/null+++ b/mobile/lib/usage/usage_account_key.dart@@ -0,0 +1,31 @@+import 'dart:convert';++import 'package:cryptography/dart.dart';++import 'usage_window.dart';++/// An account, as both ends of `usage_read` name it: the first 16 hex+/// characters of sha256(`<provider>:<id>`).+///+/// Hashed rather than carried raw because RPC answers are LOGGED — `WsConn`+/// writes every reply to `~/.harness/logs` — and an account id has no business+/// there. Equality survives hashing, and equality is all the strip needs: it is+/// what decides whether a remote machine's subscription is this one again or a+/// different one worth its own figure.+///+/// ⚠️ **A cross-language contract.** A remote machine computes the SAME key in+/// `autonomous-harness/cli/src/lib/accountUsage.ts` (`accountKey`), and the two+/// must agree byte for byte — drift, and every remote reading looks like a+/// different account, so the strip prints one subscription twice. Both suites+/// pin the same vector (`test/usage_account_key_test.dart` here,+/// `accountUsage.spec.ts` there) for exactly that reason.+String usageAccountKey(UsageProvider provider, String accountId) {+ final digest = const DartSha256().hashSync(+ utf8.encode('${provider.name}:$accountId'),+ );+ final hex = StringBuffer();+ for (final byte in digest.bytes) {+ hex.write(byte.toRadixString(16).padLeft(2, '0'));+ }+ return hex.toString().substring(0, 16);+}diff --git a/mobile/lib/usage/usage_accounts.dart b/mobile/lib/usage/usage_accounts.dartnew file mode 100644index 000000000..db63a25a6--- /dev/null+++ b/mobile/lib/usage/usage_accounts.dart@@ -0,0 +1,121 @@+import 'usage_window.dart';++/// One remote machine's answer to `usage_read`: what ITS agent accounts have+/// spent, read there with its own credentials.+class MachineUsage {+ const MachineUsage({required this.machineName, required this.readings});++ /// How the machine is named on screen — the strip's label for a figure that+ /// is not this computer's.+ final String machineName;++ final List<ProviderUsage> readings;+}++/// One account's figures, and where it was seen.+class UsageAccount {+ const UsageAccount({+ required this.reading,+ required this.isLocal,+ this.machines = const [],+ });++ final ProviderUsage reading;++ /// This computer's own account. The strip never labels it: it is the figure+ /// a person reads as "mine" without being told.+ final bool isLocal;++ /// The remote machines signed in to this account, in the order they+ /// answered. For the local account these are the machines that turned out to+ /// share it — worth saying in the panel, never on the strip.+ final List<String> machines;++ UsageProvider get provider => reading.provider;+}++/// Every account worth a figure: ONE per account, however many machines are+/// signed in to it.+///+/// A rate limit belongs to an account rather than to a computer, so three+/// machines on one Claude subscription are one figure — printing three would+/// triple-count a single budget. A machine on a DIFFERENT subscription is a+/// figure of its own, because that is a second budget somebody can run out of.+///+/// Per provider, in [UsageProvider] order: this computer's account first, then+/// each distinct remote account. Only remote readings with figures are+/// considered — a machine signed in to nothing has nothing to add, and saying+/// so for every machine on the account would fill the panel with apologies.+///+/// ⚠️ **A null account never matches**, itself included (see+/// [ProviderUsage.account]). Two readings nobody can name are not provably one+/// account, and merging them could hide a subscription that is running out.+List<UsageAccount> groupUsageAccounts(+ List<ProviderUsage> local,+ List<MachineUsage> remote,+) {+ final accounts = <UsageAccount>[];+ for (final provider in UsageProvider.values) {+ final own = _readingFor(local, provider);+ final sharedWithOwn = <String>[];+ final others = <_Group>[];+ for (final machine in remote) {+ final reading = _readingFor(machine.readings, provider);+ if (reading == null || !reading.hasFigures) continue;+ final key = reading.account;+ // ⚠️ Merged into this computer's figure only when that figure EXISTS.+ // Otherwise a Claude token that expired here would swallow the live+ // reading a remote machine took of the very same account, and the strip+ // would go blank while the numbers were sitting in the reply.+ if (key != null && own != null && own.hasFigures && key == own.account) {+ sharedWithOwn.add(machine.machineName);+ continue;+ }+ final existing = key == null+ ? null+ : _firstWhereOrNull(others, (group) => group.key == key);+ if (existing != null) {+ existing.machines.add(machine.machineName);+ } else {+ others.add(_Group(key, reading, [machine.machineName]));+ }+ }+ if (own != null) {+ accounts.add(+ UsageAccount(reading: own, isLocal: true, machines: sharedWithOwn),+ );+ }+ for (final group in others) {+ accounts.add(+ UsageAccount(+ reading: group.reading,+ isLocal: false,+ machines: group.machines,+ ),+ );+ }+ }+ return accounts;+}++class _Group {+ _Group(this.key, this.reading, this.machines);++ final String? key;+ final ProviderUsage reading;+ final List<String> machines;+}++ProviderUsage? _readingFor(+ List<ProviderUsage> readings,+ UsageProvider provider,+) => _firstWhereOrNull(readings, (reading) => reading.provider == provider);++/// A plain loop rather than `firstWhereOrNull`: `package:collection` is not a+/// dependency of this project, and a three-line lookup is not worth adding one.+T? _firstWhereOrNull<T>(Iterable<T> items, bool Function(T) test) {+ for (final item in items) {+ if (test(item)) return item;+ }+ return null;+}diff --git a/mobile/lib/usage/usage_credentials.dart b/mobile/lib/usage/usage_credentials.dartnew file mode 100644index 000000000..ae5351165--- /dev/null+++ b/mobile/lib/usage/usage_credentials.dart@@ -0,0 +1,153 @@+/// Where the agent CLIs keep the tokens their usage endpoints want.+///+/// This app reads them; it never writes them and never refreshes them. One+/// sign-in per machine, owned by the CLI that made it. A second copy here+/// would be a second thing to expire and to disagree about.+///+/// **Nothing in this file may be logged.** Every value it returns is a bearer+/// token; the CLI transcript exists precisely so secrets stay out of argv, and+/// a `print` here would undo that. Callers get the token and nothing else —+/// no wrapper carrying it into an error message.+library;++import 'dart:convert';+import 'dart:io';++/// A token, and when it stops working.+class UsageToken {+ const UsageToken({required this.accessToken, this.expiresAt});++ final String accessToken;++ /// When the token expires, when the store said so. Null means unknown, which+ /// is treated as "try it" rather than "assume dead" — the endpoint answering+ /// 401 is a better authority than a clock we may be reading wrong.+ final DateTime? expiresAt;++ /// Already dead, so the request can be skipped and reported as a sign-in+ /// rather than spent as a round trip that will fail.+ bool get isExpired {+ final at = expiresAt;+ return at != null && at.isBefore(DateTime.now());+ }+}++/// Reads the tokens the usage endpoints need, from wherever each CLI put them.+class UsageCredentials {+ const UsageCredentials({this.home, this.runProcess});++ /// Overridden by tests. Null means this machine's real home.+ final String? home;++ /// Overridden by tests so nothing shells out to the real `security`.+ final Future<ProcessResult> Function(String, List<String>)? runProcess;++ String? get _home => home ?? Platform.environment['HOME'];++ /// Claude Code's OAuth token.+ ///+ /// macOS keeps it in the login Keychain and Linux in a file, so both are+ /// tried in that order — and the file is tried on macOS too, because a+ /// Keychain that will not answer (a locked login chain, a Finder launch with+ /// no authorization) is a state, not the end of the road.+ Future<UsageToken?> claude() async {+ final fromKeychain = await _readKeychain();+ final token =+ _parseClaude(fromKeychain) ??+ _parseClaude(_readFile('.claude/.credentials.json'));+ return token;+ }++ /// Codex's OAuth token, written by `codex login`.+ Future<UsageToken?> codex() async {+ final raw = _readFile('.codex/auth.json');+ if (raw == null) return null;+ final decoded = _decode(raw);+ final tokens = decoded?['tokens'];+ if (tokens is! Map) return null;+ final access = tokens['access_token'];+ if (access is! String || access.isEmpty) return null;+ return UsageToken(accessToken: access);+ }++ /// The account id Codex's backend scopes the reading to.+ Future<String?> codexAccountId() async {+ final decoded = _decode(_readFile('.codex/auth.json'));+ final tokens = decoded?['tokens'];+ if (tokens is! Map) return null;+ final id = tokens['account_id'];+ return id is String && id.isNotEmpty ? id : null;+ }++ /// The account Claude Code is signed in as: `oauthAccount.accountUuid` in+ /// `~/.claude.json`, which is where it records who it is on every platform.+ /// The token store — Keychain or `.credentials.json` — does not carry it.+ Future<String?> claudeAccountId() async {+ final profile = _decode(_readFile('.claude.json'))?['oauthAccount'];+ if (profile is! Map) return null;+ final id = profile['accountUuid'];+ return id is String && id.isNotEmpty ? id : null;+ }++ UsageToken? _parseClaude(String? raw) {+ if (raw == null) return null;+ final oauth = _decode(raw)?['claudeAiOauth'];+ if (oauth is! Map) return null;+ final access = oauth['accessToken'];+ if (access is! String || access.isEmpty) return null;+ final expires = oauth['expiresAt'];+ return UsageToken(+ accessToken: access,+ expiresAt: expires is num+ ? DateTime.fromMillisecondsSinceEpoch(expires.round())+ : null,+ );+ }++ Map<String, Object?>? _decode(String? raw) {+ if (raw == null) return null;+ try {+ final decoded = jsonDecode(raw);+ return decoded is Map<String, Object?> ? decoded : null;+ } on FormatException {+ // A half-written credentials file is not news: the CLI that owns it is+ // mid-refresh, and the next poll a minute from now will read it whole.+ return null;+ }+ }++ String? _readFile(String relative) {+ final home = _home;+ if (home == null) return null;+ final file = File('$home${Platform.pathSeparator}$relative');+ if (!file.existsSync()) return null;+ try {+ return file.readAsStringSync();+ } on FileSystemException {+ return null;+ }+ }++ /// The macOS Keychain item Claude Code writes.+ ///+ /// `security` is used rather than a plugin because the item is a plain+ /// generic password and this is one read on a timer — a native channel would+ /// be a second thing to keep in step across two platforms for it.+ Future<String?> _readKeychain() async {+ if (!Platform.isMacOS) return null;+ final run = runProcess ?? Process.run;+ try {+ final result = await run('security', const [+ 'find-generic-password',+ '-s',+ 'Claude Code-credentials',+ '-w',+ ]);+ if (result.exitCode != 0) return null;+ final out = result.stdout;+ return out is String && out.trim().isNotEmpty ? out.trim() : null;+ } on ProcessException {+ return null;+ }+ }+}diff --git a/mobile/lib/usage/usage_source.dart b/mobile/lib/usage/usage_source.dartnew file mode 100644index 000000000..679d088cf--- /dev/null+++ b/mobile/lib/usage/usage_source.dart@@ -0,0 +1,70 @@+import 'package:dio/dio.dart';++import 'usage_window.dart';++/// One account's usage, fetched from whoever knows it.+///+/// An interface rather than two hard-wired calls, because the two vendors agree+/// on nothing but the question: different hosts, different auth, different+/// field names, different window sets. It is also the seam a per-machine source+/// would arrive through — the CLI could answer this for a remote machine one+/// day without a single widget changing.+abstract class UsageSource {+ UsageProvider get provider;++ /// The current reading, or the state that stands in for one.+ ///+ /// Never throws: every failure is a [ProviderUsage] carrying its own reason,+ /// because the rail has to draw *something* and a thrown exception would make+ /// the caller invent the sentence instead of the source that knows it.+ Future<ProviderUsage> read();+}++/// A Dio configured the way every usage call wants it.+///+/// `validateStatus` lets 4xx through so a 401 can be read as "sign in" rather+/// than surfacing as a transport failure — the split [ApiClient] draws too.+Dio buildUsageDio({String? baseUrl}) => Dio(+ BaseOptions(+ baseUrl: baseUrl ?? '',+ connectTimeout: const Duration(seconds: 10),+ receiveTimeout: const Duration(seconds: 15),+ validateStatus: (status) => status != null && status >= 200 && status < 600,+ ),+);++/// Turns a finished request into the state the rail should draw.+///+/// Shared because the two vendors fail in the same four ways even though they+/// succeed in different shapes.+ProviderUsage? usageFailureFor(UsageProvider provider, int? statusCode) {+ if (statusCode == null) {+ return ProviderUsage(+ provider: provider,+ status: UsageStatus.failed,+ message: 'Could not reach ${provider.label}',+ );+ }+ if (statusCode == 401 || statusCode == 403) {+ return ProviderUsage(+ provider: provider,+ status: UsageStatus.signedOut,+ message: 'Sign in to ${provider.label} to see usage',+ );+ }+ if (statusCode >= 400) {+ return ProviderUsage(+ provider: provider,+ status: UsageStatus.failed,+ message: '${provider.label} answered $statusCode',+ );+ }+ return null;+}++/// The state a provider is in when its CLI has never signed in here.+ProviderUsage signedOut(UsageProvider provider) => ProviderUsage(+ provider: provider,+ status: UsageStatus.signedOut,+ message: 'Sign in to ${provider.label} to see usage',+);diff --git a/mobile/lib/usage/usage_window.dart b/mobile/lib/usage/usage_window.dartnew file mode 100644index 000000000..6ea8e1a93--- /dev/null+++ b/mobile/lib/usage/usage_window.dart@@ -0,0 +1,192 @@+/// What an agent account has spent of its rate limits, and when that resets.+///+/// The vendors answer in different shapes — Claude names its windows, Codex+/// numbers them — so both are mapped onto this one model before anything draws+/// them. A rail that had to know which provider it was printing would grow a+/// branch per provider in every widget.+library;++/// What both vendors call their seven-day window.+///+/// Claude names it outright; Codex's label is derived from+/// `limit_window_seconds` and lands on the same word at seven days. Written+/// down once because the rail MATCHES on it — see [ProviderUsage.railWindow] —+/// and a match against a string spelled in two files is a match that breaks+/// silently the day one of them is reworded.+const String kWeeklyWindowLabel = 'Weekly';++/// Which account a reading belongs to.+///+/// Only the two whose usage endpoints are known. The other engines (copilot,+/// grok, hermes, opencode, pi) publish nothing comparable, so+/// they are absent rather than listed as perpetually unavailable — a row that+/// can only ever say "unsupported" is a row that costs a glance and returns+/// nothing.+enum UsageProvider {+ claude('Claude'),+ codex('Codex');++ const UsageProvider(this.label);++ /// How the provider is named on screen.+ final String label;++ /// The engine id this account's agents run under, which is also how+ /// `EngineMark` finds the logo the machine rail already draws beside every+ /// agent. The enum's own name is that id — spelled the same on purpose, so+ /// there is no second mapping to keep in step.+ String get engineId => name;+}++/// Why a provider's figures are, or are not, on screen.+///+/// [signedOut] is deliberately kept apart from [failed]: signing in fixes the+/// first and retrying fixes the second, and offering a Retry for a missing+/// session fails identically forever.+enum UsageStatus { loading, ok, signedOut, failed }++/// One rate-limit window: how much of it is spent, and when it starts over.+class UsageWindow {+ const UsageWindow({+ required this.label,+ required this.usedPercent,+ this.resetsAt,+ });++ /// What the window is called on screen — `Session`, `Weekly`, `Fable`.+ final String label;++ /// How much of the window is spent, 0–100.+ final double usedPercent;++ /// When it starts over, or null when the vendor did not say.+ ///+ /// **Null is not zero here.** A window with no reset time prints no+ /// countdown; printing "resets in 0m" for an answer we never got would be a+ /// measurement invented out of a silence.+ final DateTime? resetsAt;++ /// The countdown as the rail prints it — `4h 34m`, `5d 11h`, `43m` — or null+ /// when there is no reset time or it has already passed.+ ///+ /// Minute granularity on purpose: the poll behind this runs once a minute, so+ /// a seconds figure would be wrong for most of its life and would need a+ /// second timer to stop being wrong.+ String? resetsInLabel({DateTime? now}) {+ final at = resetsAt;+ if (at == null) return null;+ final left = at.difference(now ?? DateTime.now());+ if (left.isNegative || left.inMinutes < 1) return null;+ if (left.inHours < 1) return '${left.inMinutes}m';+ if (left.inDays < 1) {+ return '${left.inHours}h ${left.inMinutes % 60}m';+ }+ return '${left.inDays}d ${left.inHours % 24}h';+ }+}++/// One account's reading: every window it reports, or why there is none.+class ProviderUsage {+ const ProviderUsage({+ required this.provider,+ required this.status,+ this.windows = const [],+ this.message,+ this.fetchedAt,+ this.account,+ });++ /// The state a provider is in before it has ever answered.+ const ProviderUsage.loading(this.provider)+ : status = UsageStatus.loading,+ windows = const [],+ message = null,+ fetchedAt = null,+ account = null;++ final UsageProvider provider;+ final UsageStatus status;++ /// Every window this account reports, in the order it should be read:+ /// shortest window first, because that is the one about to bite.+ final List<UsageWindow> windows;++ /// Why there are no figures. Set for [UsageStatus.signedOut] and+ /// [UsageStatus.failed], null otherwise.+ final String? message;++ /// When these figures were read. Null until the first answer lands.+ final DateTime? fetchedAt;++ /// Which account these figures belong to — `usageAccountKey`, never the id+ /// itself — or null when the machine that read them could not say.+ ///+ /// It is what lets the strip show one figure per ACCOUNT rather than one per+ /// machine: a remote machine signed in to this same subscription is this+ /// figure again, and one signed in to another is a figure of its own. **Null+ /// never matches anything**, itself included — two readings nobody can name+ /// are not provably one account, and merging them could hide a subscription.+ final String? account;++ bool get hasFigures => status == UsageStatus.ok && windows.isNotEmpty;++ /// The window closest to being spent — the limit that will actually stop the+ /// work first.+ UsageWindow? get tightest {+ if (windows.isEmpty) return null;+ return windows.reduce((a, b) => b.usedPercent > a.usedPercent ? b : a);+ }++ /// The ONE window the status rail prints.+ ///+ /// The weekly one. Claude reports three windows and Codex usually one, so+ /// printing them all made one account three figures wide and the other one —+ /// two readouts that looked like different KINDS of thing rather than the+ /// same thing about two accounts. Weekly is also the figure worth a glance:+ /// the five-hour window refills all day and is back to nothing by the time+ /// anyone reads it, while the week is the budget somebody actually plans+ /// against.+ ///+ /// Falls back to [tightest] for a provider that reports no weekly window at+ /// all — one figure is the rule, and an empty strip would be a worse answer+ /// than the wrong window. The panel behind the figure still shows every+ /// window, which is where the detail belongs.+ UsageWindow? get railWindow {+ for (final window in windows) {+ if (window.label == kWeeklyWindowLabel) return window;+ }+ return tightest;+ }+}++/// Reads a vendor's reset timestamp, which arrives as an ISO string, epoch+/// seconds, or epoch milliseconds depending on the vendor and the field.+///+/// 1e10 is the discriminator: it sits above any plausible seconds epoch (year+/// 2286) and below any plausible milliseconds one (year 2001), so the unit can+/// be told from the magnitude without the vendor having to label it.+DateTime? parseResetTimestamp(Object? value) {+ if (value is num) {+ if (!value.isFinite) return null;+ final ms = value > 10000000000 ? value : value * 1000;+ return DateTime.fromMillisecondsSinceEpoch(ms.round());+ }+ if (value is! String || value.trim().isEmpty) return null;+ final numeric = num.tryParse(value.trim());+ if (numeric != null) return parseResetTimestamp(numeric);+ return DateTime.tryParse(value);+}++/// Reads a vendor's utilization figure, clamped to the 0–100 the UI draws.+///+/// The vendors disagree on the field name, so the caller passes each candidate+/// in turn; the first that is actually a number wins.+double? parseUsedPercent(List<Object?> candidates) {+ for (final candidate in candidates) {+ final value = candidate is num+ ? candidate.toDouble()+ : double.tryParse('$candidate');+ if (value != null && value.isFinite) return value.clamp(0, 100).toDouble();+ }+ return null;+}diff --git a/mobile/lib/viewer/direct_auth.dart b/mobile/lib/viewer/direct_auth.dartnew file mode 100644index 000000000..8f7a9b69e--- /dev/null+++ b/mobile/lib/viewer/direct_auth.dart@@ -0,0 +1,71 @@+import '../api/access_token_source.dart';+import '../auth/auth_session.dart';+import 'direct_auth_api.dart';++/// A viewer build's SSO session — authSession.ts's `AuthSessionManager`, moved into the app because+/// a device with no harness CLI has nobody else to hold it: the tokens `/api/auth/exchange` issued,+/// kept in [AuthSession], refreshed [_refreshSkew] before they lapse, one refresh at a time.+class DirectAuth implements AccessTokenSource {+ DirectAuth({required this.session, required this.api});++ final AuthSession session;+ final DirectAuthApi api;+ Future<String>? _refreshing;++ static const _refreshSkew = Duration(seconds: 60);++ Future<bool> hasSession() async =>+ ((await session.accessToken()) ?? '').isNotEmpty;++ Future<void> signIn(IssuedTokens tokens) => session.saveLogin(+ token: tokens.token,+ refreshToken: tokens.refreshToken,+ autonomousEnv: tokens.autonomousEnv ?? api.config.autonomousEnv,+ expiresIn: tokens.expiresIn,+ );++ Future<void> signOut() => session.clear();++ @override+ Future<String> accessToken({bool force = false, String? failedToken}) async {+ final current = await session.accessToken();+ if (current == null || current.isEmpty) {+ throw const DirectAuthException('Not signed in.', signedOut: true);+ }+ // Someone else already refreshed past the token that failed — use theirs.+ if (failedToken != null && failedToken != current) return current;+ if (!force && !await _isStale()) return current;+ return _refreshing ??= _refresh().whenComplete(() => _refreshing = null);+ }++ Future<bool> _isStale() async {+ final expiresAt = await session.accessTokenExpiresAt();+ return expiresAt != null &&+ expiresAt.isBefore(DateTime.now().toUtc().add(_refreshSkew));+ }++ Future<String> _refresh() async {+ final refreshToken = await session.refreshToken();+ if (refreshToken == null || refreshToken.isEmpty) {+ await session.clear();+ throw const DirectAuthException(+ 'Your sign-in expired. Sign in again.',+ signedOut: true,+ );+ }+ try {+ final autonomousEnv = await session.autonomousEnv();+ final tokens = await api.refresh(refreshToken, autonomousEnv: autonomousEnv);+ await session.saveRefresh(+ token: tokens.token,+ refreshToken: tokens.refreshToken,+ autonomousEnv: autonomousEnv,+ expiresIn: tokens.expiresIn,+ );+ return tokens.token;+ } on DirectAuthException catch (error) {+ if (error.signedOut) await session.clear();+ rethrow;+ }+ }+}diff --git a/mobile/lib/viewer/direct_auth_api.dart b/mobile/lib/viewer/direct_auth_api.dartnew file mode 100644index 000000000..812bc3e4c--- /dev/null+++ b/mobile/lib/viewer/direct_auth_api.dart@@ -0,0 +1,137 @@+import 'package:dio/dio.dart';++import '../api/api_client.dart';+import '../core/config.dart';+import '../logging/http_log.dart';++/// A sign-in or refresh that produced no usable session.+class DirectAuthException implements Exception {+ const DirectAuthException(this.message, {this.signedOut = false});++ final String message;++ /// The session is gone for good: retrying cannot help, only signing in again.+ final bool signedOut;++ @override+ String toString() => message;+}++/// What `/api/auth/exchange` and `/api/auth/refresh` hand back.+class IssuedTokens {+ const IssuedTokens({+ required this.token,+ this.refreshToken,+ this.expiresIn,+ this.autonomousEnv,+ });++ final String token;+ final String? refreshToken;++ /// Seconds.+ final int? expiresIn;+ final String? autonomousEnv;++ static IssuedTokens? fromData(Object? data) {+ if (data is! Map) return null;+ final token = data['token'], refresh = data['refreshToken'];+ final expiresIn = data['expiresIn'], env = data['autonomousEnv'];+ if (token is! String || token.isEmpty) return null;+ return IssuedTokens(+ token: token,+ refreshToken: refresh is String && refresh.isNotEmpty ? refresh : null,+ expiresIn: expiresIn is int && expiresIn > 0 ? expiresIn : null,+ autonomousEnv: env is String ? env : null,+ );+ }+}++/// The backend's auth endpoints, called by the app itself — in a desktop build the harness CLI+/// calls them (cli.ts `loginCommand`, authSession.ts `refreshRequest`). No bearer rides these:+/// they are how one is got.+class DirectAuthApi {+ DirectAuthApi({required this.config, Dio? dio})+ : _dio =+ dio ??+ attachHttpLog(+ Dio(+ BaseOptions(+ baseUrl: config.apiBaseUrl,+ connectTimeout: const Duration(seconds: 15),+ receiveTimeout: const Duration(seconds: 30),+ validateStatus: (status) => status != null && status < 600,+ ),+ ),+ );++ final AppConfig config;+ final Dio _dio;++ static const _unavailable =+ 'Could not renew your sign-in. That is usually the sign-in service having a moment — '+ 'if it keeps happening, sign out and sign in again.';++ Future<({String authorizeUrl, String tx})> authorizeNative(+ String redirectUri,+ ) async {+ final data = unwrapApiResponse(+ await _dio.post(+ '/api/auth/authorize-native',+ data: {'redirectUri': redirectUri, 'autonomousEnv': config.autonomousEnv},+ ),+ );+ final url = data is Map ? data['authorizeUrl'] : null;+ final tx = data is Map ? data['tx'] : null;+ if (url is! String || url.isEmpty || tx is! String || tx.isEmpty) {+ throw const DirectAuthException('The server did not return a sign-in page.');+ }+ return (authorizeUrl: url, tx: tx);+ }++ Future<IssuedTokens> exchange({+ required String code,+ required String state,+ required String tx,+ }) async {+ final data = unwrapApiResponse(+ await _dio.post(+ '/api/auth/exchange',+ data: {'code': code, 'state': state, 'tx': tx},+ ),+ );+ return IssuedTokens.fromData(data) ??+ (throw const DirectAuthException('Sign-in returned no access token.'));+ }++ /// authSession.ts `refreshRequest`, down to its one subtle rule: only a 401 or+ /// `REFRESH_TOKEN_INVALID` means the session is dead. An unusable refresh token and a real outage+ /// both come back as the same 503, and reading that as dead would delete a refresh token nothing+ /// can bring back — on a blip.+ Future<IssuedTokens> refresh(+ String refreshToken, {+ required String autonomousEnv,+ }) async {+ final Response<dynamic> res;+ try {+ res = await _dio.post(+ '/api/auth/refresh',+ data: {'refreshToken': refreshToken, 'autonomousEnv': autonomousEnv},+ );+ } on DioException {+ throw const DirectAuthException(_unavailable);+ }+ final body = res.data is Map ? res.data as Map : const {};+ final error = body['error'] is Map ? body['error'] as Map : const {};+ if (res.statusCode == 401 || error['code'] == 'REFRESH_TOKEN_INVALID') {+ throw const DirectAuthException(+ 'Your sign-in expired. Sign in again.',+ signedOut: true,+ );+ }+ final tokens = body['success'] == false+ ? null+ : IssuedTokens.fromData(body['data']);+ return tokens ?? (throw const DirectAuthException(_unavailable));+ }+}diff --git a/mobile/lib/viewer/direct_link.dart b/mobile/lib/viewer/direct_link.dartnew file mode 100644index 000000000..17d0dc13c--- /dev/null+++ b/mobile/lib/viewer/direct_link.dart@@ -0,0 +1,88 @@+import '../auth/cli_link.dart';+import '../auth/link_errors.dart';+import '../auth/peer_link_client.dart';+import '../core/config.dart';+import '../e2ee/keys.dart';+import 'direct_auth.dart';+import 'direct_auth_api.dart';+import 'password_link.dart';+import 'viewer_key_store.dart';++/// `harness link connect/list/unlink` for a device with no harness CLI: the password exchange runs+/// here ([linkWithPassword]) and the pin lands in [ViewerKeyStore] rather than `machinePeers.json`.+class DirectLink implements PeerLinkClient {+ DirectLink({+ required this.keys,+ required this.auth,+ required this.config,+ this.socket = defaultRelaySocket,+ });++ final ViewerKeyStore keys;+ final DirectAuth auth;+ final AppConfig config;+ final RelaySocketFactory socket;++ @override+ Future<CliLinkConnectResult> connect(+ String machineId,+ String password, {+ void Function(String stage)? onProgress,+ String? displayName,+ }) async {+ final String token;+ try {+ token = await auth.accessToken();+ } on DirectAuthException catch (error) {+ return CliLinkConnectResult(error: error.message);+ }+ final result = await linkWithPassword(+ machineId: machineId,+ password: password,+ identity: await keys.identity(),+ accessToken: token,+ wsBaseUrl: config.wsBaseUrl,+ autonomousEnv: config.autonomousEnv,+ onProgress: (stage) => onProgress?.call(stage.wireName),+ socket: socket,+ );+ switch (result) {+ case PasswordLinked(:final peerPub, :final fingerprint):+ await keys.pin(machineId, peerPub);+ return CliLinkConnectResult(+ linkedMachineId: machineId,+ fingerprint: fingerprint,+ );+ case PasswordLinkFailed(:final code, :final retryAt):+ // Named the way the CLI's `--name` names it: the id is all a stranger to this rail sees.+ final name = displayName == null || displayName.isEmpty+ ? machineId+ : displayName;+ return CliLinkConnectResult(+ error: humanizeLinkError(code, name, retryAt: retryAt),+ );+ }+ }++ @override+ Future<CliLinkListResult> list() async => CliLinkListResult(+ machines: [+ for (final peer in await keys.peers())+ LinkedMachine(+ machineId: peer.machineId,+ fingerprint: fingerprint(peer.pub),+ linkedAt: _asCliPrints(peer.linkedAt),+ ),+ ],+ );++ @override+ Future<String?> unlink(String machineId) async =>+ await keys.unlink(machineId) ? null : '$machineId is not linked.';+}++/// `YYYY-MM-DD HH:MM`, the form `harness link list` prints and [LinkedMachine] carries.+String _asCliPrints(DateTime at) {+ String two(int n) => n.toString().padLeft(2, '0');+ return '${at.year}-${two(at.month)}-${two(at.day)} ${two(at.hour)}:${two(at.minute)}';+}diff --git a/mobile/lib/viewer/direct_login.dart b/mobile/lib/viewer/direct_login.dartnew file mode 100644index 000000000..ccddf0284--- /dev/null+++ b/mobile/lib/viewer/direct_login.dart@@ -0,0 +1,107 @@+import 'dart:async';+import 'dart:io';++import '../auth/cli_login.dart';+import '../auth/sign_in_client.dart';+import 'direct_auth.dart';+import 'direct_auth_api.dart';++/// Signing in with no harness CLI — cli.ts `loginCommand`, run by the app: a loopback listener for+/// the SSO redirect, `authorize-native` for the page to show, `exchange` for the tokens.+///+/// It deliberately skips the CLI's closing `resolve-computer`, which registers the computer as a+/// Harness machine. A viewer is not one.+class DirectLogin implements SignInClient {+ DirectLogin({required this.auth});++ final DirectAuth auth;+ _LoopbackCallback? _pending;++ static const _callbackTimeout = Duration(minutes: 5);++ @override+ Future<CliAuthStatus> checkStatus() async =>+ CliAuthStatus(loggedIn: await auth.hasSession());++ @override+ Future<void> login({+ required void Function(String url) onAuthorizeUrl,+ }) async {+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ final callback = _pending = _LoopbackCallback(server);+ try {+ final start = await auth.api.authorizeNative(+ 'http://127.0.0.1:${server.port}/callback',+ );+ onAuthorizeUrl(start.authorizeUrl);+ final redirect = await callback.result.timeout(+ _callbackTimeout,+ onTimeout: () => throw const DirectAuthException('Sign-in timed out.'),+ );+ await auth.signIn(+ await auth.api.exchange(+ code: redirect.code,+ state: redirect.state,+ tx: start.tx,+ ),+ );+ } finally {+ _pending = null;+ await server.close(force: true);+ }+ }++ @override+ void cancel() => _pending?.cancel();++ @override+ Future<void> logout() => auth.signOut();+}++/// The loopback end of the redirect: the first `/callback` carrying `code` and `state` completes+/// it and an `error` fails it; anything else the browser asks for (a favicon) is turned away.+class _LoopbackCallback {+ _LoopbackCallback(HttpServer server) {+ server.listen(_onRequest);+ }++ final _completer = Completer<({String code, String state})>();++ Future<({String code, String state})> get result => _completer.future;++ Future<void> _onRequest(HttpRequest request) async {+ final response = request.response;+ if (request.uri.path != '/callback') {+ response.statusCode = HttpStatus.notFound;+ await response.close();+ return;+ }+ final query = request.uri.queryParameters;+ final code = query['code'], state = query['state'], error = query['error'];+ final signedIn = error == null && code != null && state != null;+ response+ ..statusCode = signedIn ? HttpStatus.ok : HttpStatus.badRequest+ ..headers.contentType = ContentType.html+ ..write(_page(signedIn ? 'Signed in to Harness' : 'Harness sign-in failed'));+ await response.close();+ if (_completer.isCompleted) return;+ if (signedIn) {+ _completer.complete((code: code, state: state));+ } else {+ _completer.completeError(+ DirectAuthException('Sign-in failed: ${error ?? 'no code returned'}'),+ );+ }+ }++ void cancel() {+ if (_completer.isCompleted) return;+ _completer.completeError(const DirectAuthException('Sign-in was cancelled.'));+ }+}++String _page(String title) =>+ '<!doctype html><meta charset="utf-8"><title>$title</title>'+ '<body style="font:16px system-ui,sans-serif;text-align:center;padding:4em 1em">'+ '<h1 style="font-weight:600">$title</h1>'+ '<p>You can close this window and go back to Harness.</p></body>';diff --git a/mobile/lib/viewer/e2ee_relay_codec.dart b/mobile/lib/viewer/e2ee_relay_codec.dartnew file mode 100644index 000000000..2d4057a95--- /dev/null+++ b/mobile/lib/viewer/e2ee_relay_codec.dart@@ -0,0 +1,67 @@+import 'dart:typed_data';++import '../e2ee/envelope.dart';+import '../e2ee/relay_session_crypto.dart';+import '../terminal/terminal_binary.dart';+import '../ws/relay_codec.dart';+import 'viewer_key_store.dart';++/// [RelaySessionCrypto] as a [RelayCodec]: the conversion the harness CLI's `remoteRelay.ts` does+/// between the relay's HTRM frames and the loopback HTRL ones, done in the app instead.+class E2eeRelayCodec implements RelayCodec {+ E2eeRelayCodec(this._session);++ final RelaySessionCrypto _session;++ @override+ Map<String, dynamic> helloFrame() => _session.helloFrame();++ @override+ Future<bool> handleWelcome(Map<String, dynamic> payload) =>+ _session.handleWelcome(payload);++ @override+ bool handleRekey(Map<String, dynamic> payload) =>+ _session.handleRekey(payload);++ @override+ int get terminalP2pVersion => _session.terminalP2pVersion;++ @override+ Map<String, dynamic>? encodeFrame(Map<String, dynamic> frame) {+ final type = frame['type'];+ final mustSeal = type is String && encryptedDownTypes.contains(type);+ if (mustSeal && !_session.ready) return null;+ return _session.wrapOutgoing(frame);+ }++ @override+ Map<String, dynamic>? decodeFrame(Map<String, dynamic> frame) =>+ _session.unwrapIncoming(frame);++ @override+ Uint8List? encodeBinary(Uint8List localFrame) {+ final clear = decodeTerminalLocal(localFrame);+ return clear == null ? null : _session.encryptTerminal(clear);+ }++ @override+ Uint8List? decodeBinary(Uint8List wireFrame) {+ final clear = _session.decryptTerminal(wireFrame);+ return clear == null ? null : encodeTerminalLocal(clear);+ }+}++/// The viewer's [RelayCodecFactory]: a new session per connection, against the identity this+/// device pinned for the machine when it linked — or none, when it never has.+RelayCodecFactory viewerRelayCodecs(ViewerKeyStore keys) => (machineId) async {+ final peer = await keys.peer(machineId);+ if (peer == null) return null;+ return E2eeRelayCodec(+ await RelaySessionCrypto.start(+ machineId: machineId,+ identity: await keys.identity(),+ peerPub: peer.pub,+ ),+ );+};diff --git a/mobile/lib/viewer/password_link.dart b/mobile/lib/viewer/password_link.dartnew file mode 100644index 000000000..5c366f989--- /dev/null+++ b/mobile/lib/viewer/password_link.dart@@ -0,0 +1,256 @@+import 'dart:async';+import 'dart:convert';+import 'dart:typed_data';++import 'package:web_socket_channel/web_socket_channel.dart';++import '../e2ee/bytes.dart';+import '../e2ee/cpace.dart';+import '../e2ee/envelope.dart';+import '../e2ee/keys.dart';+import '../e2ee/password_pake.dart';+import '../e2ee/primitives.dart';++/// How far a password link has got — the stages `harness link connect --json` reports, spelled the+/// same (see [wireName]) so the link form shows one progress for either build.+enum PasswordLinkStage {+ connecting('connecting'),+ derivingKey('deriving_key'),+ exchanging('exchanging'),+ verifying('verifying');++ const PasswordLinkStage(this.wireName);++ final String wireName;+}++sealed class PasswordLinkResult {+ const PasswordLinkResult();+}++final class PasswordLinked extends PasswordLinkResult {+ const PasswordLinked(this.peerPub, this.fingerprint);++ /// The machine's identity, to pin.+ final Uint8List peerPub;+ final String fingerprint;+}++final class PasswordLinkFailed extends PasswordLinkResult {+ const PasswordLinkFailed(this.code, {this.retryAt});++ /// The CLI's own code: `WRONG_PASSWORD`, `TIMEOUT`, or whatever the machine refused with.+ final String code;++ /// When a locked-out password may be tried again, if the machine said.+ final DateTime? retryAt;+}++typedef RelaySocketFactory =+ WebSocketChannel Function(Uri uri, Iterable<String> protocols);++WebSocketChannel defaultRelaySocket(Uri uri, Iterable<String> protocols) =>+ WebSocketChannel.connect(uri, protocols: protocols);++/// relayClient.ts `connectWithPassword`: over a short-lived relay socket, prove to [machineId] that+/// this device knows its `harness remote-password`, and learn the identity to pin for it. Nobody+/// approves anything on the machine — knowing the password is the approval.+///+/// [timeout] is twice the CLI's 15s: the stretch inside it is about a second on a laptop and can be+/// several on a phone, and a link that fails for being slow reads exactly like a wrong password.+Future<PasswordLinkResult> linkWithPassword({+ required String machineId,+ required String password,+ required E2eeIdentity identity,+ required String accessToken,+ required String wsBaseUrl,+ required String autonomousEnv,+ void Function(PasswordLinkStage stage)? onProgress,+ RelaySocketFactory socket = defaultRelaySocket,+ Duration timeout = const Duration(seconds: 30),+}) async {+ onProgress?.call(PasswordLinkStage.connecting);+ final uri = Uri.parse('$wsBaseUrl/api/web-ws').replace(+ queryParameters: {'autonomousEnv': autonomousEnv},+ );+ final channel = socket(uri, [accessToken]);+ final run = _PasswordLinkRun(machineId, password, identity, channel, onProgress);+ try {+ await channel.ready;+ return await run.drive().timeout(+ timeout,+ onTimeout: () => const PasswordLinkFailed('TIMEOUT'),+ );+ } catch (_) {+ return const PasswordLinkFailed('CONNECTION_ERROR');+ } finally {+ unawaited(channel.sink.close());+ }+}++const _wrongPassword = PasswordLinkFailed('WRONG_PASSWORD');++/// The joiner ('b') side of the machine's `onPwPairIntent`/`onPwPake` state machine.+class _PasswordLinkRun {+ _PasswordLinkRun(+ this.machineId,+ this.password,+ this.identity,+ this.channel,+ this.onProgress,+ );++ final String machineId;+ final String password;+ final E2eeIdentity identity;+ final WebSocketChannel channel;+ final void Function(PasswordLinkStage stage)? onProgress;++ final Uint8List _sid = secureRandomBytes(16);+ late final String _sidB64 = b64e(_sid);+ final String _requestId = b64e(secureRandomBytes(16));+ late final String _ci = pwContext(machineId);+ bool _selected = false;+ Uint8List? _stretched;+ Uint8List? _isk;+ Uint8List? _transcript;+ Uint8List? _machinePub;++ Future<PasswordLinkResult> drive() async {+ _send('machine_select', {'machineId': machineId});+ await for (final raw in channel.stream) {+ final frame = raw is String ? jsonObjectOf(utf8Bytes(raw)) : null;+ if (frame == null) continue;+ final PasswordLinkResult? result;+ try {+ result = await _step(frame);+ } catch (_) {+ // Anything this side cannot parse or verify is the protocol failing, as in the CLI.+ return const PasswordLinkFailed('PROTOCOL_ERROR');+ }+ if (result != null) return result;+ }+ return PasswordLinkFailed('CONNECTION_CLOSED:${channel.closeCode}');+ }++ Future<PasswordLinkResult?> _step(Map<String, dynamic> frame) async {+ final type = frame['type'];+ final payload = frame['payload'] is Map<String, dynamic>+ ? frame['payload'] as Map<String, dynamic>+ : const <String, dynamic>{};+ if (!_selected) {+ if (payload['machineId'] != machineId) return null;+ if (type == 'connected') return _sendIntent();+ if (type == 'machine_select_error') {+ return PasswordLinkFailed(_codeOr(payload['error'], 'SELECT_FAILED'));+ }+ return null;+ }+ if (type == 'e2e_pw_pair_result' && payload['requestId'] == _requestId) {+ return payload['ok'] == true ? null : _refused(payload);+ }+ if (type != 'e2e_pw_pake' || payload['sid'] != _sidB64) return null;+ final error = payload['error'];+ return switch (payload['round']) {+ 1 when error != null => PasswordLinkFailed('$error'),+ 1 => _answerShare(payload),+ 3 when error != null => PasswordLinkFailed('$error'),+ 3 => await _answerIdentity(payload),+ 5 => _finish(payload),+ _ => null,+ };+ }++ Future<PasswordLinkResult?> _sendIntent() async {+ _selected = true;+ onProgress?.call(PasswordLinkStage.derivingKey);+ try {+ _stretched = await stretchPassword(password, machineId);+ } catch (_) {+ return const PasswordLinkFailed('DERIVE_FAILED');+ }+ onProgress?.call(PasswordLinkStage.exchanging);+ _send('e2e_pw_pair_intent', {'requestId': _requestId, 'sid': _sidB64});+ return null;+ }++ /// Round 1 in, round 2 out: our CPace share, and a MAC only the right password could have made.+ PasswordLinkResult? _answerShare(Map<String, dynamic> payload) {+ final stretched = _stretched;+ if (stretched == null) return null;+ final theirs = b64d(payload['ya'] as String);+ final ours = cpaceStart(pwCpaceGenerator(stretched, _sid, _ci));+ final isk = _isk = cpaceIsk(+ _sid,+ cpaceShared(theirs, ours.scalar),+ theirs,+ ours.share,+ );+ final transcript = _transcript = transcriptHash(_sid, _ci, theirs, ours.share);+ onProgress?.call(PasswordLinkStage.verifying);+ _send('e2e_pw_pake', {+ 'sid': _sidB64,+ 'round': 2,+ 'yb': b64e(ours.share),+ 'mac': b64e(macTag(kcKeys(isk, _ci).web, transcript)),+ });+ return null;+ }++ /// Round 3 in, round 4 out: the machine proves the password too and hands over its identity,+ /// bound to this transcript; ours goes back the same way.+ Future<PasswordLinkResult?> _answerIdentity(Map<String, dynamic> payload) async {+ final isk = _isk, transcript = _transcript;+ if (isk == null || transcript == null) {+ return const PasswordLinkFailed('PROTOCOL_ERROR');+ }+ final mac = b64d(payload['mac'] as String);+ if (!macVerify(kcKeys(isk, _ci).adapter, transcript, mac)) {+ return _wrongPassword;+ }+ final key = pairKey(isk, _ci);+ final opened = aeadOpen(key, 3, utf8Bytes('e2e-id'), b64d(payload['enc'] as String));+ final claim = opened == null ? null : jsonObjectOf(opened);+ final id = claim?['id'], sig = claim?['sig'];+ if (id is! String || sig is! String) return _wrongPassword;+ final machinePub = b64d(id);+ if (!await pairBindVerify(machinePub, transcript, b64d(sig))) {+ return _wrongPassword;+ }+ _machinePub = machinePub;+ final ours = jsonEncode({+ 'id': b64e(identity.pub),+ 'sig': b64e(await pairBindSig(identity, transcript)),+ });+ _send('e2e_pw_pake', {+ 'sid': _sidB64,+ 'round': 4,+ 'enc': b64e(aeadSeal(key, 4, utf8Bytes('e2e-id'), utf8Bytes(ours))),+ });+ return null;+ }++ /// The fingerprint is computed here rather than taken from the frame, unlike the CLI: round 5+ /// crosses the relay in the clear, and the pinned key is the thing it must describe.+ PasswordLinkResult _finish(Map<String, dynamic> payload) {+ final machinePub = _machinePub;+ if (payload['ok'] != true || machinePub == null) {+ return PasswordLinkFailed(_codeOr(payload['error'], 'PAIR_FAILED'));+ }+ return PasswordLinked(machinePub, fingerprint(machinePub));+ }++ PasswordLinkFailed _refused(Map<String, dynamic> payload) {+ final retryAt = payload['retryAt'];+ return PasswordLinkFailed(+ _codeOr(payload['error'], 'PAIR_FAILED'),+ retryAt: retryAt is int ? DateTime.fromMillisecondsSinceEpoch(retryAt) : null,+ );+ }++ void _send(String type, Map<String, Object> payload) =>+ channel.sink.add(jsonEncode({'type': type, 'payload': payload}));+}++String _codeOr(Object? value, String fallback) =>+ value is String && value.isNotEmpty ? value : fallback;diff --git a/mobile/lib/viewer/sign_in_browser.dart b/mobile/lib/viewer/sign_in_browser.dartnew file mode 100644index 000000000..8b760ace7--- /dev/null+++ b/mobile/lib/viewer/sign_in_browser.dart@@ -0,0 +1,24 @@+import 'dart:io';++import 'package:url_launcher/url_launcher.dart';++/// Where the SSO page opens: the system browser, as it always has — except on a phone.+///+/// There, handing the person to Safari or Chrome suspends this app and with it the loopback+/// listener the page redirects back to, so the page opens in-app (SFSafariViewController on iOS,+/// a Custom Tab on Android), where the app keeps running, and [closeSignInPage] takes it down+/// once the redirect lands.+///+/// ⚠️ Unverified on a device: the SSO page's Google button opens a popup, and whether an in-app+/// browser view lets that popup post back to its opener is exactly what the first run on a phone+/// has to answer.+Future<bool> openSignInPage(Uri url) => launchUrl(+ url,+ mode: Platform.isIOS || Platform.isAndroid+ ? LaunchMode.inAppBrowserView+ : LaunchMode.externalApplication,+);++Future<void> closeSignInPage() async {+ if (Platform.isIOS || Platform.isAndroid) await closeInAppWebView();+}diff --git a/mobile/lib/viewer/viewer_key_store.dart b/mobile/lib/viewer/viewer_key_store.dartnew file mode 100644index 000000000..8514aa9f7--- /dev/null+++ b/mobile/lib/viewer/viewer_key_store.dart@@ -0,0 +1,125 @@+import 'dart:convert';+import 'dart:typed_data';++import '../core/harness_file_store.dart';+import '../core/local_key_value_store.dart';+import '../e2ee/bytes.dart';+import '../e2ee/keys.dart';++/// A machine this device linked to by its remote password, and the identity it pinned for it — the+/// same shape as the harness CLI's `machinePeers.json` rows.+class MachinePeer {+ const MachinePeer({+ required this.machineId,+ required this.pub,+ required this.linkedAt,+ this.label = '',+ });++ final String machineId;+ final Uint8List pub;+ final String label;+ final DateTime linkedAt;++ /// Null for a row that is not one — a damaged file loses that row, not every link.+ static MachinePeer? tryParse(Object? json) {+ if (json is! Map) return null;+ final machineId = json['machineId'], pub = json['pub'];+ final linkedAt = json['linkedAt'], label = json['label'];+ if (machineId is! String || pub is! String || linkedAt is! int) return null;+ try {+ return MachinePeer(+ machineId: machineId,+ pub: b64d(pub),+ label: label is String ? label : '',+ linkedAt: DateTime.fromMillisecondsSinceEpoch(linkedAt),+ );+ } on FormatException {+ return null;+ }+ }++ Map<String, Object> toJson() => {+ 'machineId': machineId,+ 'pub': b64e(pub),+ 'label': label,+ 'linkedAt': linkedAt.millisecondsSinceEpoch,+ };+}++/// This device's E2EE identity and the machines it has linked — what the harness CLI keeps under+/// its `e2e/` directory, kept here where there is no CLI.+///+/// TODO(security): the identity seed lives in the state file — 0600 on a desktop, the app sandbox+/// on iOS — the protection the CLI gives its own and less than Keychain/DPAPI would. Moving it+/// into the platform keystore is a follow-up.+class ViewerKeyStore {+ ViewerKeyStore({LocalKeyValueStore? storage})+ : _storage = storage ?? HarnessFileStore.shared;++ final LocalKeyValueStore _storage;+ Future<E2eeIdentity>? _identity;++ static const _seedKey = 'viewer_e2ee_identity_seed';+ static const _peersKey = 'viewer_e2ee_machine_peers';++ /// Minted on first use and kept: every linked machine has pinned it.+ Future<E2eeIdentity> identity() => _identity ??= _loadOrMintIdentity();++ Future<E2eeIdentity> _loadOrMintIdentity() async {+ final stored = await _storage.read(_seedKey);+ if (stored != null) return E2eeIdentity.fromSeed(b64d(stored));+ final minted = await E2eeIdentity.generate();+ await _storage.write(_seedKey, b64e(minted.seed));+ return minted;+ }++ /// Newest link first.+ Future<List<MachinePeer>> peers() async {+ final raw = await _storage.read(_peersKey);+ if (raw == null) return const [];+ final Object? decoded;+ try {+ decoded = jsonDecode(raw);+ } on FormatException {+ return const [];+ }+ if (decoded is! List) return const [];+ return decoded.map(MachinePeer.tryParse).whereType<MachinePeer>().toList()+ ..sort((a, b) => b.linkedAt.compareTo(a.linkedAt));+ }++ Future<MachinePeer?> peer(String machineId) async {+ for (final peer in await peers()) {+ if (peer.machineId == machineId) return peer;+ }+ return null;+ }++ Future<void> pin(String machineId, List<int> pub, {String label = ''}) async {+ await _write([+ for (final peer in await peers())+ if (peer.machineId != machineId) peer,+ MachinePeer(+ machineId: machineId,+ pub: Uint8List.fromList(pub),+ label: label,+ linkedAt: DateTime.now(),+ ),+ ]);+ }++ /// False when [machineId] was not linked.+ Future<bool> unlink(String machineId) async {+ final current = await peers();+ final remaining = current.where((peer) => peer.machineId != machineId).toList();+ if (remaining.length == current.length) return false;+ await _write(remaining);+ return true;+ }++ Future<void> _write(List<MachinePeer> peers) => _storage.write(+ _peersKey,+ jsonEncode([for (final peer in peers) peer.toJson()]),+ );+}diff --git a/mobile/lib/viewer/viewer_services.dart b/mobile/lib/viewer/viewer_services.dartnew file mode 100644index 000000000..d99814709--- /dev/null+++ b/mobile/lib/viewer/viewer_services.dart@@ -0,0 +1,60 @@+import '../auth/auth_session.dart';+import '../core/config.dart';+import '../ws/relay_codec.dart';+import '../ws/terminal_transport_plugin.dart';+import 'direct_auth.dart';+import 'direct_auth_api.dart';+import 'direct_link.dart';+import 'direct_login.dart';+import 'e2ee_relay_codec.dart';+import 'viewer_key_store.dart';++/// The second wire a viewer build offers its relay connections — the phone's WebRTC+/// data channel to the machine. Set once, from that app's `main()` through+/// `startHarness`, before the first frame; a mutable global because its one+/// writer runs before any widget tree exists to carry it. Null — the desktop, or+/// a viewer without one — leaves every terminal frame on the relay socket.+TerminalTransportPluginFactory? harnessTransportPlugins;++/// Everything a viewer build uses in place of the harness CLI, built once and handed to+/// `AppNotifier`: the SSO session, signing in, the machines this device has linked and the E2EE+/// sessions to them. A desktop build has none — and where it is null, nothing in the app behaves+/// any differently than it did before viewers existed.+class ViewerServices {+ const ViewerServices._({+ required this.keys,+ required this.auth,+ required this.login,+ required this.links,+ required this.relayCodecs,+ required this.transportPlugins,+ });++ factory ViewerServices({+ required AppConfig config,+ required AuthSession session,+ ViewerKeyStore? keys,+ TerminalTransportPluginFactory? transportPlugins,+ }) {+ final store = keys ?? ViewerKeyStore();+ final auth = DirectAuth(+ session: session,+ api: DirectAuthApi(config: config),+ );+ return ViewerServices._(+ keys: store,+ auth: auth,+ login: DirectLogin(auth: auth),+ links: DirectLink(keys: store, auth: auth, config: config),+ relayCodecs: viewerRelayCodecs(store),+ transportPlugins: transportPlugins ?? harnessTransportPlugins,+ );+ }++ final ViewerKeyStore keys;+ final DirectAuth auth;+ final DirectLogin login;+ final DirectLink links;+ final RelayCodecFactory relayCodecs;+ final TerminalTransportPluginFactory? transportPlugins;+}diff --git a/mobile/lib/widgets/agent_drag.dart b/mobile/lib/widgets/agent_drag.dartnew file mode 100644index 000000000..ed208c4ef--- /dev/null+++ b/mobile/lib/widgets/agent_drag.dart@@ -0,0 +1,94 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../theme/app_theme.dart';++/// An agent in flight between the rail and the grid.+class AgentDragRef {+ const AgentDragRef({+ required this.machineId,+ required this.agentId,+ required this.name,+ });++ final String machineId;+ final String agentId;+ final String name;+}++/// A PANE in flight between two grid slots.+///+/// A type of its own rather than a flag on [AgentDragRef], because the two+/// drags mean opposite things at the same drop point: a rail row landing on a+/// tile REPLACES what that tile shows, a pane landing on it SWAPS the two.+/// `DragTarget<T>` already separates them by generic, so each target only ever+/// sees the payload it knows what to do with, and neither has to ask what kind+/// of drag is in flight.+class PaneDragRef {+ const PaneDragRef({required this.paneId});++ final int paneId;+}++/// Everything the header needs to drag its own pane: what to say it is, and+/// where to photograph it from.+///+/// The key is not part of [PaneDragRef] because that is the PAYLOAD — it+/// crosses to the drop target, where a key into the source tile means nothing.+class PaneDragHandle {+ const PaneDragHandle({required this.ref, required this.size});++ final PaneDragRef ref;++ /// The tile's size, so the ghost comes out the shape of the pane it carries.+ ///+ /// Passed IN from a LayoutBuilder rather than read off a render object: the+ /// header builds this during a build, and `RenderBox.size` throws there.+ final Size size;+}++/// Whether a rail row is currently being dragged, readable by the grid.++///+/// A [ValueNotifier] beside the widgets rather than a field on AppNotifier: it+/// describes a hand on a mouse for the length of one gesture, and nothing about+/// machines, agents or sessions. Putting it in the domain state would mean every+/// listener of that state rebuilding on mouse-down, and would outlive the+/// gesture in a place where later readers would reasonably expect it to mean+/// something.+///+/// The grid watches it to reveal the empty slot: an "add a tile" cell that is+/// always on screen would permanently halve a single terminal to advertise a+/// feature, so it appears when there is something to drop into it and goes away+/// again afterwards.+final agentDrag = ValueNotifier<AgentDragRef?>(null);++/// Whether a pane is currently being dragged by its header, readable by the grid.+///+/// Kept apart from [agentDrag] for the same reason [PaneDragRef] is a separate+/// type: the two drags are live at different times and the grid reveals+/// different things for each — an agent drag offers an empty slot to open into,+/// a pane drag offers the other tiles to trade places with.+final paneDragging = ValueNotifier<PaneDragRef?>(null);++class PaneCloseButton extends StatelessWidget {+ const PaneCloseButton({super.key, required this.onPressed});++ final VoidCallback onPressed;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Tooltip(+ message: 'Close pane',+ child: IconButton(+ onPressed: onPressed,+ icon: Icon(Icons.close, size: 15, color: AppColors.muted),+ splashRadius: 13,+ constraints: const BoxConstraints.tightFor(width: 26, height: 26),+ padding: EdgeInsets.zero,+ visualDensity: VisualDensity.compact,+ ),+ );+ }+}diff --git a/mobile/lib/widgets/bootstrapping_screen.dart b/mobile/lib/widgets/bootstrapping_screen.dartnew file mode 100644index 000000000..791bdf2b5--- /dev/null+++ b/mobile/lib/widgets/bootstrapping_screen.dart@@ -0,0 +1,158 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import 'login_relay_diagram.dart';++/// The quiet bridge between opening Harness and reaching the user's workspace.+///+/// Bootstrap does not expose truthful percentage progress, so this screen names+/// the current operation without inventing steps or a completion estimate. It+/// shares the sign-in and pre-flight visual language so startup feels like one+/// product instead of a framework spinner between two designed screens.+class BootstrappingScreen extends StatelessWidget {+ const BootstrappingScreen({super.key, this.statusMessage});++ final String? statusMessage;++ static const double _cardWidth = 420;+ static const String _fallbackStatus = 'Opening Harness…';++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final reduceMotion = MediaQuery.disableAnimationsOf(context);+ final status = statusMessage ?? _fallbackStatus;++ return Scaffold(+ backgroundColor: grid.AppPalette.panelBg,+ body: Stack(+ children: [+ const Positioned.fill(child: LoginAurora()),+ Center(+ child: SingleChildScrollView(+ padding: const EdgeInsets.symmetric(vertical: 32, horizontal: 24),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: _cardWidth),+ child: Container(+ width: double.infinity,+ padding: const EdgeInsets.all(32),+ decoration: BoxDecoration(+ color: grid.AppGlass.surfaceFill,+ borderRadius: BorderRadius.circular(grid.AppCard.radius),+ boxShadow: grid.AppCard.shadow,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ const _BootAppMark(),+ const SizedBox(height: 20),+ Text(+ 'Getting Harness ready',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.titleLarge,+ ),+ const SizedBox(height: 8),+ Text(+ 'Connecting this window to the local Harness service.',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodySmall,+ ),+ const SizedBox(height: 24),+ Semantics(+ key: const Key('boot-status'),+ container: true,+ liveRegion: true,+ label: 'Harness startup status',+ value: status,+ child: ExcludeSemantics(+ child: Container(+ width: double.infinity,+ padding: const EdgeInsets.symmetric(+ horizontal: 16,+ vertical: 14,+ ),+ decoration: BoxDecoration(+ color: grid.AppCard.inset,+ borderRadius: BorderRadius.circular(+ grid.AppCard.insetRadius,+ ),+ border: Border.all(color: grid.AppCard.insetHair),+ ),+ child: Row(+ mainAxisAlignment: MainAxisAlignment.center,+ mainAxisSize: MainAxisSize.min,+ children: [+ TickerMode(+ key: const Key('boot-status-ticker'),+ enabled: !reduceMotion,+ child: const SizedBox(+ width: 18,+ height: 18,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ ),+ ),+ ),+ const SizedBox(width: 12),+ Flexible(+ child: AnimatedSwitcher(+ duration: reduceMotion+ ? Duration.zero+ : const Duration(milliseconds: 180),+ child: Text(+ status,+ key: ValueKey(status),+ textAlign: TextAlign.center,+ style: Theme.of(context)+ .textTheme+ .labelLarge,+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ const SizedBox(height: 16),+ Text(+ 'This usually takes a few seconds.',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.labelSmall+ ?.copyWith(color: grid.AppPalette.textSecondary),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}++class _BootAppMark extends StatelessWidget {+ const _BootAppMark();++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Container(+ width: 56,+ height: 56,+ decoration: BoxDecoration(+ color: grid.AppCard.inset,+ borderRadius: BorderRadius.circular(12),+ ),+ alignment: Alignment.center,+ child: Image.asset(+ 'assets/app_icon.png',+ width: 36,+ height: 36,+ filterQuality: FilterQuality.medium,+ ),+ );+ }+}diff --git a/mobile/lib/widgets/engine_identity.dart b/mobile/lib/widgets/engine_identity.dartnew file mode 100644index 000000000..595fde858--- /dev/null+++ b/mobile/lib/widgets/engine_identity.dart@@ -0,0 +1,231 @@+import 'dart:math' as math;++import 'package:flutter/material.dart';++import '../theme/app_theme.dart';++class EngineIdentity {+ final String id;+ final String label;+ final Color color;+ final String? asset;++ const EngineIdentity({+ required this.id,+ required this.label,+ required this.color,+ this.asset,+ });+}++const _engines = <String, EngineIdentity>{+ 'claude': EngineIdentity(+ id: 'claude',+ label: 'Claude',+ color: Color(0xffcc7c5e),+ ),+ 'codex': EngineIdentity(+ id: 'codex',+ label: 'Codex',+ color: Color(0xff64d2ff),+ asset: 'assets/engine-icons/codex.png',+ ),+ 'cursor': EngineIdentity(+ id: 'cursor',+ label: 'Cursor',+ color: Color(0xffc6ff72),+ asset: 'assets/engine-icons/cursor.png',+ ),+ 'opencode': EngineIdentity(+ id: 'opencode',+ label: 'OpenCode',+ color: Color(0xfff1ecec),+ asset: 'assets/engine-icons/opencode.png',+ ),+ 'pi': EngineIdentity(+ id: 'pi',+ label: 'Pi',+ color: Colors.white,+ asset: 'assets/engine-icons/pi.png',+ ),+ 'hermes': EngineIdentity(+ id: 'hermes',+ label: 'Hermes',+ color: Color(0xff9b8cff),+ asset: 'assets/engine-icons/hermes.png',+ ),+ 'commandcode': EngineIdentity(+ id: 'commandcode',+ label: 'Command Code',+ color: Color(0xfff5f5f5),+ asset: 'assets/engine-icons/commandcode.png',+ ),+ 'devin': EngineIdentity(+ id: 'devin',+ label: 'Devin',+ color: Color(0xff8fb8ff),+ asset: 'assets/engine-icons/devin.png',+ ),+ 'muse': EngineIdentity(+ id: 'muse',+ label: 'Muse',+ color: Color(0xff0082fb),+ asset: 'assets/engine-icons/muse.png',+ ),+ 'amp': EngineIdentity(+ id: 'amp',+ label: 'Amp',+ color: Color(0xfff34e3f),+ asset: 'assets/engine-icons/amp.png',+ ),+ 'kilo': EngineIdentity(+ id: 'kilo',+ label: 'Kilo',+ color: Color(0xfff8f676),+ asset: 'assets/engine-icons/kilo.png',+ ),+ 'grok': EngineIdentity(+ id: 'grok',+ label: 'Grok',+ color: Colors.white,+ asset: 'assets/engine-icons/grok.png',+ ),+ 'copilot': EngineIdentity(+ id: 'copilot',+ label: 'Copilot',+ color: Color(0xff8957e5),+ asset: 'assets/engine-icons/copilot.png',+ ),+ 'agy': EngineIdentity(+ id: 'agy',+ label: 'Antigravity',+ color: Color(0xff3287fb),+ asset: 'assets/engine-icons/agy.png',+ ),+};++/// All known engines, in declaration order — for the New Agent engine picker.+List<EngineIdentity> get allEngines => _engines.values.toList(growable: false);++EngineIdentity engineIdentity(String? engine, {String? displayName}) {+ final id = engine?.trim().toLowerCase() ?? '';+ final known = _engines[id];+ if (known != null) return known;+ final raw = displayName?.trim().isNotEmpty == true+ ? displayName!.trim()+ : id.isEmpty+ ? 'Agent'+ : id;+ final label = raw[0].toUpperCase() + raw.substring(1);+ return EngineIdentity(+ id: id.isEmpty ? 'unknown' : id,+ label: label,+ color: AppColors.mutedStrong,+ );+}++class EngineMark extends StatelessWidget {+ final String? engine;+ final String? displayName;+ final bool enabled;+ final double size;++ const EngineMark({+ super.key,+ required this.engine,+ this.displayName,+ this.enabled = true,+ this.size = 16,+ });++ @override+ Widget build(BuildContext context) {+ final identity = engineIdentity(engine, displayName: displayName);+ final mark = identity.asset != null+ ? Image.asset(+ identity.asset!,+ key: ValueKey('engine-icon-${identity.id}'),+ width: size,+ height: size,+ fit: BoxFit.contain,+ filterQuality: FilterQuality.high,+ errorBuilder: (_, _, _) => _InitialMark(+ key: ValueKey('engine-fallback-${identity.id}'),+ identity: identity,+ size: size,+ ),+ )+ : identity.id == 'claude'+ ? CustomPaint(+ key: const ValueKey('engine-icon-claude'),+ size: Size.square(size),+ painter: _ClaudeMarkPainter(identity.color),+ )+ : _InitialMark(+ key: ValueKey('engine-fallback-${identity.id}'),+ identity: identity,+ size: size,+ );+ return Opacity(opacity: enabled ? 1 : 0.45, child: mark);+ }+}++class _InitialMark extends StatelessWidget {+ final EngineIdentity identity;+ final double size;++ const _InitialMark({super.key, required this.identity, required this.size});++ @override+ Widget build(BuildContext context) {+ return SizedBox.square(+ dimension: size,+ child: Center(+ child: Text(+ identity.label.characters.first.toUpperCase(),+ // ⚠️ Sized from [size], a FIXED box, not from the type ramp — so it+ // must not take the app's UI scale either. At the top of the range the+ // glyph would grow while its 17px square did not, and the letter would+ // clip out of its own mark.+ textScaler: TextScaler.noScaling,+ style: TextStyle(+ color: identity.color,+ // The app's mono stack, not a literal: `Menlo` names nothing on+ // Linux, so this initial was drawn in the proportional default+ // while every mark beside it was monospaced.+ fontFamily: AppFonts.mono,+ fontFamilyFallback: AppFonts.monoFallback,+ fontSize: size * 0.68,+ height: 1,+ fontWeight: FontWeight.w700,+ ),+ ),+ ),+ );+ }+}++class _ClaudeMarkPainter extends CustomPainter {+ final Color color;+ const _ClaudeMarkPainter(this.color);++ @override+ void paint(Canvas canvas, Size size) {+ final paint = Paint()+ ..color = color+ ..strokeWidth = size.width * 0.098+ ..strokeCap = StrokeCap.round;+ final c = Offset(size.width / 2, size.height / 2);+ final radius = size.width * 0.39;+ for (var i = 0; i < 4; i++) {+ final angle = i * 0.78539816339;+ final dx = radius * math.cos(angle);+ final dy = radius * math.sin(angle);+ canvas.drawLine(c - Offset(dx, dy), c + Offset(dx, dy), paint);+ }+ }++ @override+ bool shouldRepaint(covariant _ClaudeMarkPainter oldDelegate) =>+ oldDelegate.color != color;+}diff --git a/mobile/lib/widgets/environment_preflight_screen.dart b/mobile/lib/widgets/environment_preflight_screen.dartnew file mode 100644index 000000000..8180c9884--- /dev/null+++ b/mobile/lib/widgets/environment_preflight_screen.dart@@ -0,0 +1,124 @@+import 'package:flutter/material.dart';++import '../bootstrap/environment_provisioner.dart';+import '../shared/theme/app_theme.dart' as grid;+import 'login_relay_diagram.dart';++/// The quiet read-only gate shown before either sign-in or environment setup.+///+/// This is deliberately not part of the environment setup wizard: a computer that+/// is already ready should never look as though it has entered an installer.+/// The ready state has no artificial dwell or action; it stays visible only+/// while the app asks the local Harness CLI whether this user is signed in.+class EnvironmentPreflightScreen extends StatelessWidget {+ const EnvironmentPreflightScreen({super.key, required this.readiness});++ final EnvironmentReadiness readiness;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final ready = readiness.isReady;++ return Scaffold(+ backgroundColor: grid.AppPalette.panelBg,+ body: Stack(+ children: [+ const Positioned.fill(child: LoginAurora()),+ Center(+ child: SingleChildScrollView(+ padding: const EdgeInsets.symmetric(vertical: 32, horizontal: 24),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 420),+ child: Container(+ width: double.infinity,+ padding: const EdgeInsets.all(32),+ decoration: BoxDecoration(+ color: grid.AppGlass.surfaceFill,+ borderRadius: BorderRadius.circular(14),+ boxShadow: grid.AppCard.shadow,+ ),+ child: AnimatedSwitcher(+ duration: const Duration(milliseconds: 180),+ child: ready+ ? const _ReadyContent(+ key: ValueKey('environment-ready'),+ )+ : const _CheckingContent(+ key: ValueKey('environment-checking'),+ ),+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}++class _CheckingContent extends StatelessWidget {+ const _CheckingContent({super.key});++ @override+ Widget build(BuildContext context) => Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ const SizedBox(+ width: 34,+ height: 34,+ child: CircularProgressIndicator(strokeWidth: 2.5),+ ),+ const SizedBox(height: 24),+ Text(+ 'Checking this computer',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.titleLarge,+ ),+ const SizedBox(height: 8),+ Text(+ 'Verifying the tools Harness needs. This check is read-only and nothing is being installed.',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodySmall,+ ),+ ],+ );+}++class _ReadyContent extends StatelessWidget {+ const _ReadyContent({super.key});++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final success = grid.AppPalette.online;+ return Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Container(+ width: 48,+ height: 48,+ decoration: BoxDecoration(+ color: success.withValues(alpha: 0.12),+ shape: BoxShape.circle,+ ),+ alignment: Alignment.center,+ child: Icon(Icons.check_rounded, size: 28, color: success),+ ),+ const SizedBox(height: 20),+ Text(+ 'Environment ready',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.titleLarge,+ ),+ const SizedBox(height: 8),+ Text(+ 'All required tools passed verification.',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodySmall,+ ),+ ],+ );+ }+}diff --git a/mobile/lib/widgets/environment_setup_screen.dart b/mobile/lib/widgets/environment_setup_screen.dartnew file mode 100644index 000000000..d374f4fa5--- /dev/null+++ b/mobile/lib/widgets/environment_setup_screen.dart@@ -0,0 +1,868 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../bootstrap/environment_provisioner.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/command_row.dart';+import '../state/app_state.dart';+import '../theme/app_theme.dart';++/// One setup review with a direct install action. Launch probes stay read-only;+/// installation starts only after the user chooses the visible install action.+class EnvironmentSetupScreen extends StatefulWidget {+ final AppNotifier notifier;++ const EnvironmentSetupScreen({super.key, required this.notifier});++ @override+ State<EnvironmentSetupScreen> createState() => _EnvironmentSetupScreenState();+}++class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {+ String? _copied;+ final _scroll = ScrollController();+ final _primaryFocus = FocusNode(debugLabel: 'Setup action');+ final _bodyFocus = FocusNode(+ debugLabel: 'Setup details',+ skipTraversal: true,+ );+ final _manualFocus = FocusNode(debugLabel: 'Switch setup method');+ EnvironmentSetupPhase? _lastPhase;+ bool _actionWasAvailable = false;+ bool _detailsOpen = false;++ @override+ void dispose() {+ _scroll.dispose();+ _primaryFocus.dispose();+ _bodyFocus.dispose();+ _manualFocus.dispose();+ super.dispose();+ }++ Future<void> _copy(String value) async {+ await Clipboard.setData(ClipboardData(text: value));+ if (!mounted) return;+ setState(() => _copied = value);+ Future<void>.delayed(const Duration(milliseconds: 1400), () {+ if (mounted && _copied == value) setState(() => _copied = null);+ });+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final state = widget.notifier.environmentReadiness;+ final phaseChanged = _lastPhase != state.phase;+ final actionAvailable =+ !widget.notifier.environmentSetupInFlight &&+ const {+ EnvironmentSetupPhase.review,+ EnvironmentSetupPhase.chooseMethod,+ EnvironmentSetupPhase.failed,+ EnvironmentSetupPhase.waitingForTerminal,+ EnvironmentSetupPhase.ready,+ }.contains(state.phase);+ if (phaseChanged || (actionAvailable && !_actionWasAvailable)) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || ModalRoute.of(context)?.isCurrent == false) return;+ if (widget.notifier.environmentReadiness.phase != state.phase) return;+ if (phaseChanged && _scroll.hasClients) _scroll.jumpTo(0);+ // A new next step should be usable with Enter. Keep an explicit choice+ // to read/copy details or change methods when asynchronous updates land.+ if (actionAvailable &&+ !widget.notifier.environmentSetupInFlight &&+ !_bodyFocus.hasFocus &&+ !_manualFocus.hasFocus) {+ _primaryFocus.requestFocus();+ }+ });+ }+ _lastPhase = state.phase;+ _actionWasAvailable = actionAvailable;+ final compact = MediaQuery.sizeOf(context).height < 640;+ return Scaffold(+ backgroundColor: AppColors.background,+ body: SafeArea(+ child: Padding(+ padding: EdgeInsets.all(compact ? 16 : 24),+ child: Center(+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 760),+ child: Material(+ color: AppColors.sidebar,+ clipBehavior: Clip.antiAlias,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(14),+ side: BorderSide(color: AppColors.border),+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Flexible(+ child: SingleChildScrollView(+ controller: _scroll,+ padding: EdgeInsets.all(compact ? 20 : 28),+ child: Focus(+ focusNode: _bodyFocus,+ child: _body(state),+ ),+ ),+ ),+ _footer(state),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }++ Widget _body(EnvironmentReadiness state) => switch (state.phase) {+ EnvironmentSetupPhase.preflight => _preflight(state),+ EnvironmentSetupPhase.review ||+ EnvironmentSetupPhase.chooseMethod => _choose(state),+ EnvironmentSetupPhase.installing ||+ EnvironmentSetupPhase.waitingForTerminal ||+ EnvironmentSetupPhase.verifying => _installing(state),+ EnvironmentSetupPhase.failed => _failure(state),+ EnvironmentSetupPhase.ready => _ready(state),+ };++ Widget _heading(String eyebrow, String title, String lead) => Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ eyebrow.toUpperCase(),+ style: TextStyle(+ color: AppColors.accent,+ fontSize: 11,+ fontWeight: FontWeight.w700,+ letterSpacing: 1.4,+ ),+ ),+ const SizedBox(height: 6),+ Text(+ title,+ style: const TextStyle(fontSize: 28, fontWeight: FontWeight.w600),+ ),+ const SizedBox(height: 8),+ Text(lead, style: TextStyle(color: AppColors.textSoft, height: 1.55)),+ const SizedBox(height: 16),+ ],+ );++ Widget _preflight(EnvironmentReadiness state) => Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _heading(+ 'Getting started',+ 'Checking this computer',+ 'Checking the tools Harness needs to run your harnesses.',+ ),+ _checkList(state, checking: true),+ ],+ );++ Widget _choose(EnvironmentReadiness state) {+ final mode = state.mode ?? EnvironmentSetupMode.automatic;+ final items = _installItems(state);+ final count = items.length;+ final countLabel = '$count ${count == 1 ? 'tool' : 'tools'}';+ final needsTerminal = items.any((item) => item.requiresTerminal);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _heading(+ 'Getting started',+ 'Get this computer ready',+ count == 0+ ? 'Your tools are ready. Verify them to continue.'+ : count == 1+ ? 'Install this tool, then sign in to start your first harness.'+ : 'Install these $countLabel, then sign in to start your first harness.',+ ),+ Row(+ children: [+ const Expanded(+ child: Text(+ 'Required tools',+ style: TextStyle(fontWeight: FontWeight.w500),+ ),+ ),+ TextButton(+ style: TextButton.styleFrom(foregroundColor: AppColors.textSoft),+ onPressed: () => widget.notifier.selectEnvironmentSetupMode(+ mode == EnvironmentSetupMode.automatic+ ? EnvironmentSetupMode.manual+ : EnvironmentSetupMode.automatic,+ ),+ child: Text(+ mode == EnvironmentSetupMode.automatic+ ? 'Manual setup'+ : 'Use automatic setup',+ ),+ ),+ ],+ ),+ const SizedBox(height: 8),+ if (mode == EnvironmentSetupMode.automatic) ...[+ if (needsTerminal) ...[+ _notice(+ Icons.terminal,+ 'Admin prompts stay in Terminal',+ 'Complete any installation prompts there, then return to Harness.',+ ),+ const SizedBox(height: 16),+ ],+ _planList(items),+ ] else+ _manualList(items),+ ],+ );+ }++ Widget _installing(EnvironmentReadiness state) => Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _heading(+ 'Getting started',+ state.phase == EnvironmentSetupPhase.waitingForTerminal+ ? 'Finish setup in Terminal'+ : state.phase == EnvironmentSetupPhase.verifying+ ? 'Running final verification'+ : 'Preparing this computer',+ state.message ?? 'Installing only the missing required tools.',+ ),+ if (state.phase == EnvironmentSetupPhase.waitingForTerminal)+ _notice(+ Icons.lock_outline,+ 'Harness cannot see your password',+ 'Finish the prompts in Terminal, then return here. Harness checks progress automatically.',+ ),+ const SizedBox(height: 18),+ _checkList(state, checking: true),+ _logs(state),+ ],+ );++ Widget _failure(EnvironmentReadiness state) {+ final failure = state.failure;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _heading(+ 'Setup needs attention',+ failure?.title ?? 'Environment setup failed',+ failure?.detail ?? state.message ?? 'Review the full error below.',+ ),+ _checkList(state),+ if (failure?.command != null) ...[+ const SizedBox(height: 16),+ CommandRow(+ command: failure!.command!,+ copied: _copied == failure.command,+ onCopy: () => _copy(failure.command!),+ ),+ ],+ _logs(state),+ ],+ );+ }++ Widget _ready(EnvironmentReadiness state) => Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _heading(+ 'Setup complete',+ 'This computer is ready',+ 'Every required command passed. Continue to Harness sign-in.',+ ),+ _checkList(state),+ ],+ );++ Widget _checkList(EnvironmentReadiness state, {bool checking = false}) =>+ _Panel(+ child: Column(+ children: [+ const _CheckSectionLabel('Host dependencies'),+ _CheckRow(+ label: 'System tools & writable home',+ detail: Platform.isMacOS+ ? 'Shell, curl, tar, sed, awk, shasum · Xcode or Command Line Tools'+ : 'Shell, curl, tar, sed, awk, sha256sum · writable home',+ status: _systemStatus(state),+ checking:+ checking && state.phase == EnvironmentSetupPhase.preflight,+ ),+ _CheckRow(+ label: Platform.isMacOS+ ? 'Homebrew & tmux terminal backend'+ : 'tmux terminal backend',+ detail: 'Required for every terminal session',+ status: state.steps[EnvironmentStep.tmux],+ ),+ if (Platform.isLinux)+ _CheckRow(+ label: 'Native image clipboard',+ detail: _linuxClipboardDetail,+ status: state.steps[EnvironmentStep.clipboard],+ ),+ const _CheckSectionLabel('Harness components'),+ _CheckRow(+ label: 'Managed Node 20+ & Harness CLI',+ detail: '~/.harness/runtime · harness version',+ status: state.steps[EnvironmentStep.harness],+ ),+ ],+ ),+ );++ EnvironmentStepStatus? _systemStatus(EnvironmentReadiness state) {+ if (state.systemReady) return EnvironmentStepStatus.ready;+ if (state.phase == EnvironmentSetupPhase.preflight) return null;+ if (state.phase == EnvironmentSetupPhase.waitingForTerminal &&+ state.terminalSetup == EnvironmentTerminalSetup.linuxHost) {+ return EnvironmentStepStatus.needsTerminal;+ }+ if (state.phase == EnvironmentSetupPhase.installing) {+ return EnvironmentStepStatus.running;+ }+ return EnvironmentStepStatus.failed;+ }++ String? get _linuxClipboardPackage {+ if ((Platform.environment['WAYLAND_DISPLAY'] ?? '').isNotEmpty) {+ return 'wl-clipboard';+ }+ if ((Platform.environment['DISPLAY'] ?? '').isNotEmpty) return 'xclip';+ return null;+ }++ String get _linuxClipboardDetail => switch (_linuxClipboardPackage) {+ 'wl-clipboard' => 'wl-copy · provided by wl-clipboard',+ 'xclip' => 'xclip · required for native image paste',+ _ => 'Not applicable · image paste uses file-path fallback',+ };++ bool _needsInstall(EnvironmentStepStatus? status) =>+ status != EnvironmentStepStatus.ready &&+ status != EnvironmentStepStatus.notApplicable;++ List<_InstallItem> _installItems(EnvironmentReadiness state) {+ final items = <_InstallItem>[];+ final tmuxStatusMissing = _needsInstall(state.steps[EnvironmentStep.tmux]);+ final tmuxMissing =+ state.tmuxBinaryReady == false ||+ (state.tmuxBinaryReady == null && tmuxStatusMissing);++ if (Platform.isMacOS) {+ if (!state.systemReady) {+ items.add(+ const _InstallItem(+ title: 'Apple developer tools',+ detail: 'Xcode or Command Line Tools',+ command: '/usr/bin/xcrun --find clang || { if [ -x /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild ]; then sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer; else xcode-select --install; fi; }',+ requiresTerminal: true,+ ),+ );+ }+ final homebrewMissing =+ state.homebrewReady == false ||+ (state.homebrewReady == null && tmuxStatusMissing);+ if (homebrewMissing) {+ items.add(+ const _InstallItem(+ title: 'Homebrew',+ detail: 'Required package manager for tmux',+ command: '/bin/bash -c "\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"',+ requiresTerminal: true,+ ),+ );+ }+ if (tmuxMissing) {+ items.add(+ const _InstallItem(+ title: 'tmux',+ detail: 'Required for every terminal session',+ command: 'eval "\$(/opt/homebrew/bin/brew shellenv 2>/dev/null || /usr/local/bin/brew shellenv)" && brew install tmux',+ ),+ );+ }+ } else if (Platform.isLinux) {+ final packages = <String>{...state.missingLinuxPackages};+ if (!state.systemReady && packages.isEmpty) {+ packages.addAll(const [+ 'bash',+ 'curl',+ 'tar',+ 'sed',+ 'gawk',+ 'coreutils',+ ]);+ }+ if (_needsInstall(state.steps[EnvironmentStep.clipboard]) &&+ _linuxClipboardPackage != null) {+ packages.add(_linuxClipboardPackage!);+ }+ if (tmuxMissing) packages.add('tmux');+ if (packages.isNotEmpty) {+ final names = packages.join(', ');+ items.add(+ _InstallItem(+ title: 'Linux host dependencies',+ detail: '$names · one apt transaction',+ command: 'sudo apt-get install -y ${packages.join(' ')}',+ requiresTerminal: true,+ ),+ );+ }+ }++ if (_needsInstall(state.steps[EnvironmentStep.harness])) {+ items.add(+ const _InstallItem(+ title: 'Managed Node 20+ & Harness CLI',+ detail: '~/.harness only',+ command: kHarnessDesktopInstallCommand,+ ),+ );+ }+ return items;+ }++ Widget _planList(List<_InstallItem> items) {+ if (items.isEmpty) {+ return _notice(+ Icons.check_circle_outline,+ 'Nothing left to install',+ 'Every dependency is ready. Continue to final verification.',+ );+ }+ final stacked = MediaQuery.textScalerOf(context).scale(1) > 1.25;+ return _Panel(+ child: Column(+ children: [+ for (var index = 0; index < items.length; index++)+ ListTile(+ dense: true,+ leading: CircleAvatar(+ radius: 14,+ backgroundColor: AppColors.hover,+ child: Text(+ '${index + 1}',+ style: const TextStyle(fontSize: 11),+ ),+ ),+ title: Text(+ items[index].title,+ style: const TextStyle(fontSize: 13),+ ),+ subtitle: stacked+ ? Text(+ items[index].detail,+ style: TextStyle(color: AppColors.textSoft, fontSize: 11),+ )+ : null,+ trailing: stacked+ ? null+ : ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 280),+ child: Text(+ items[index].detail,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.end,+ style: TextStyle(color: AppColors.muted, fontSize: 11),+ ),+ ),+ ),+ ],+ ),+ );+ }++ Widget _manualList(List<_InstallItem> items) => Column(+ children: [+ if (items.isEmpty)+ _notice(+ Icons.check_circle_outline,+ 'Nothing left to install',+ 'Every dependency is ready. Continue to final verification.',+ ),+ for (var index = 0; index < items.length; index++)+ Padding(+ padding: const EdgeInsets.only(bottom: 10),+ child: _Panel(+ padding: const EdgeInsets.all(14),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ '${index + 1} · ${items[index].title}',+ style: const TextStyle(+ fontSize: 12,+ fontWeight: FontWeight.w600,+ ),+ ),+ const SizedBox(height: 9),+ CommandRow(+ command: items[index].command,+ copied: _copied == items[index].command,+ onCopy: () => _copy(items[index].command),+ ),+ ],+ ),+ ),+ ),+ ],+ );++ Widget _logs(EnvironmentReadiness state) {+ if (state.output.isEmpty) return const SizedBox.shrink();+ final diagnostics = state.output.join('\n');+ return Container(+ width: double.infinity,+ margin: const EdgeInsets.only(top: 18),+ decoration: BoxDecoration(+ color: AppColors.background,+ border: Border.all(color: AppColors.border),+ borderRadius: BorderRadius.circular(10),+ ),+ child: ExpansionTile(+ initiallyExpanded: _detailsOpen,+ maintainState: true,+ expandedCrossAxisAlignment: CrossAxisAlignment.stretch,+ expansionAnimationStyle: AnimationStyle.noAnimation,+ onExpansionChanged: (open) => setState(() => _detailsOpen = open),+ title: Row(+ children: [+ const Expanded(+ child: Text(+ 'Setup details',+ style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),+ ),+ ),+ TextButton.icon(+ onPressed: () => _copy(diagnostics),+ icon: const Icon(Icons.copy, size: 14),+ label: Text(+ _copied == diagnostics ? 'Copied' : 'Copy diagnostics',+ ),+ ),+ ],+ ),+ children: [+ Divider(height: 1, color: AppColors.border),+ ConstrainedBox(+ constraints: const BoxConstraints(maxHeight: 210),+ child: SingleChildScrollView(+ reverse: true,+ padding: const EdgeInsets.all(14),+ child: SelectableText(+ diagnostics,+ style: TextStyle(+ fontFamily: AppFonts.mono,+ fontSize: 11,+ height: 1.55,+ color: AppColors.textSoft,+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }++ Widget _notice(IconData icon, String title, String detail) {+ final tone = AppColors.accent;+ return Container(+ padding: const EdgeInsets.all(14),+ decoration: BoxDecoration(+ color: tone.withValues(alpha: 0.07),+ border: Border.all(color: tone.withValues(alpha: 0.35)),+ borderRadius: BorderRadius.circular(10),+ ),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Icon(icon, size: 18, color: tone),+ const SizedBox(width: 11),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ title,+ style: const TextStyle(+ fontSize: 12,+ fontWeight: FontWeight.w600,+ ),+ ),+ const SizedBox(height: 4),+ Text(+ detail,+ style: TextStyle(+ color: AppColors.textSoft,+ fontSize: 12,+ height: 1.45,+ ),+ ),+ ],+ ),+ ),+ ],+ ),+ );+ }++ Widget _footer(EnvironmentReadiness state) {+ final busy = widget.notifier.environmentSetupInFlight;+ final mode = state.mode ?? EnvironmentSetupMode.automatic;+ final missingCount = _installItems(state).length;+ final manual = mode == EnvironmentSetupMode.manual;+ String? label;+ VoidCallback? action;+ IconData? icon;+ switch (state.phase) {+ case EnvironmentSetupPhase.review || EnvironmentSetupPhase.chooseMethod:+ label = manual+ ? 'Check again'+ : missingCount == 0+ ? 'Verify and continue'+ : 'Install $missingCount ${missingCount == 1 ? 'tool' : 'tools'}';+ icon = manual ? Icons.refresh : Icons.download_outlined;+ action = manual+ ? widget.notifier.retryEnvironmentSetup+ : widget.notifier.startEnvironmentSetup;+ case EnvironmentSetupPhase.failed:+ label = 'Retry';+ action = manual+ ? widget.notifier.retryEnvironmentSetup+ : widget.notifier.startEnvironmentSetup;+ case EnvironmentSetupPhase.ready:+ label = 'Continue to sign in';+ action = widget.notifier.continueAfterEnvironmentSetup;+ case EnvironmentSetupPhase.waitingForTerminal:+ label = 'Recheck now';+ icon = Icons.refresh;+ action = () => widget.notifier.recheckEnvironmentStep(+ state.steps[EnvironmentStep.clipboard] ==+ EnvironmentStepStatus.needsTerminal+ ? EnvironmentStep.clipboard+ : EnvironmentStep.tmux,+ );+ default:+ break;+ }+ final actions = Wrap(+ alignment: WrapAlignment.end,+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: 8,+ runSpacing: 8,+ children: [+ if (state.phase == EnvironmentSetupPhase.failed && !manual)+ TextButton(+ focusNode: _manualFocus,+ onPressed: busy+ ? null+ : () {+ widget.notifier.selectEnvironmentSetupMode(+ EnvironmentSetupMode.manual,+ );+ widget.notifier.showEnvironmentMethodChoice();+ },+ child: const Text('Switch to Manual'),+ ),+ if (label != null)+ FilledButton.icon(+ focusNode: _primaryFocus,+ autofocus: true,+ onPressed: busy ? null : action,+ icon: icon == null ? null : Icon(icon, size: 16),+ label: Text(label),+ )+ else if (busy)+ const SizedBox(+ width: 18,+ height: 18,+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ ],+ );+ final next = Text(+ 'Next: sign in and start a harness.',+ style: TextStyle(color: AppColors.textSoft, fontSize: 11),+ );+ return Container(+ padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),+ decoration: BoxDecoration(+ color: AppColors.sidebar,+ border: Border(top: BorderSide(color: AppColors.border)),+ ),+ child: LayoutBuilder(+ builder: (context, constraints) {+ if (constraints.maxWidth < 600 ||+ MediaQuery.textScalerOf(context).scale(1) > 1.25) {+ return Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [next, const SizedBox(height: 12), actions],+ );+ }+ return Row(+ children: [+ Expanded(child: next),+ const SizedBox(width: 12),+ actions,+ ],+ );+ },+ ),+ );+ }+}++class _InstallItem {+ final String title;+ final String detail;+ final String command;+ final bool requiresTerminal;++ const _InstallItem({+ required this.title,+ required this.detail,+ required this.command,+ this.requiresTerminal = false,+ });+}++class _Panel extends StatelessWidget {+ final Widget child;+ final EdgeInsetsGeometry padding;+ const _Panel({required this.child, this.padding = EdgeInsets.zero});++ @override+ Widget build(BuildContext context) => Container(+ width: double.infinity,+ padding: padding,+ clipBehavior: Clip.antiAlias,+ decoration: BoxDecoration(+ color: AppColors.surface,+ border: Border.all(color: AppColors.border),+ borderRadius: BorderRadius.circular(11),+ ),+ child: child,+ );+}++class _CheckSectionLabel extends StatelessWidget {+ final String label;+ const _CheckSectionLabel(this.label);++ @override+ Widget build(BuildContext context) => Container(+ width: double.infinity,+ padding: const EdgeInsets.fromLTRB(16, 11, 16, 8),+ decoration: BoxDecoration(+ color: AppColors.background.withValues(alpha: 0.28),+ border: Border(bottom: BorderSide(color: AppColors.border)),+ ),+ child: Text(+ label.toUpperCase(),+ style: TextStyle(+ color: AppColors.textSoft,+ fontSize: 10,+ fontWeight: FontWeight.w700,+ letterSpacing: 1.1,+ ),+ ),+ );+}++class _CheckRow extends StatelessWidget {+ final String label;+ final String detail;+ final EnvironmentStepStatus? status;+ final bool checking;+ const _CheckRow({+ required this.label,+ required this.detail,+ required this.status,+ this.checking = false,+ });++ @override+ Widget build(BuildContext context) {+ final color = switch (status) {+ EnvironmentStepStatus.ready => AppColors.success,+ EnvironmentStepStatus.failed => AppColors.danger,+ EnvironmentStepStatus.needsTerminal => AppColors.warning,+ EnvironmentStepStatus.running => AppColors.accent,+ EnvironmentStepStatus.notApplicable => AppColors.muted,+ _ => AppColors.muted,+ };+ return Container(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),+ decoration: BoxDecoration(+ border: Border(bottom: BorderSide(color: AppColors.border)),+ ),+ child: Row(+ children: [+ if (checking || status == EnvironmentStepStatus.running)+ SizedBox(+ width: 16,+ height: 16,+ child: CircularProgressIndicator(strokeWidth: 2, color: color),+ )+ else+ Icon(+ status == EnvironmentStepStatus.ready+ ? Icons.check_circle+ : status == EnvironmentStepStatus.failed+ ? Icons.cancel_outlined+ : status == EnvironmentStepStatus.notApplicable+ ? Icons.remove_circle_outline+ : Icons.circle_outlined,+ size: 17,+ color: color,+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ label,+ style: const TextStyle(+ fontSize: 13,+ fontWeight: FontWeight.w500,+ ),+ ),+ const SizedBox(height: 3),+ Text(+ detail,+ style: TextStyle(color: AppColors.muted, fontSize: 11),+ ),+ ],+ ),+ ),+ Text(switch (status) {+ EnvironmentStepStatus.ready => 'Ready',+ EnvironmentStepStatus.failed => 'Missing',+ EnvironmentStepStatus.needsTerminal => 'Terminal',+ EnvironmentStepStatus.running => 'Working',+ EnvironmentStepStatus.notApplicable => 'Not applicable',+ _ => checking ? 'Checking' : 'Required',+ }, style: TextStyle(color: color, fontSize: 11)),+ ],+ ),+ );+ }+}diff --git a/mobile/lib/widgets/flash_firmware_dialog.dart b/mobile/lib/widgets/flash_firmware_dialog.dartnew file mode 100644index 000000000..103f6e871--- /dev/null+++ b/mobile/lib/widgets/flash_firmware_dialog.dart@@ -0,0 +1,813 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../flash/flasher.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';++/// Writes firmware to the plugged-in dial, and shows the flasher's own output+/// while it happens.+Future<void> showFlashFirmwareDialog(BuildContext context, {Flasher? flasher}) {+ return showAppDialog<void>(+ context: context,+ // A half-written image is a board that will not boot. The dialog refuses to+ // leave while the write is in flight; PopScope below does the same for the+ // Escape key and the window's own close.+ barrierDismissible: false,+ builder: (context) => _FlashDialog(flasher: flasher ?? Flasher()),+ );+}++enum _Phase { probing, ready, noBoard, flashing, done, failed }++class _FlashDialog extends StatefulWidget {+ const _FlashDialog({required this.flasher});++ final Flasher flasher;++ @override+ State<_FlashDialog> createState() => _FlashDialogState();+}++class _FlashDialogState extends State<_FlashDialog> {+ final List<FlashLine> _log = [];+ final ScrollController _logScroll = ScrollController();++ _Phase _phase = _Phase.probing;+ List<String> _ports = const [];+ String? _port;+ String? _problem;++ /// Step titles in the order the script announced them, and which one is live.+ final List<String> _steps = [];+ bool _stepFailed = false;++ Stopwatch? _elapsed;+ Timer? _ticker;++ @override+ void initState() {+ super.initState();+ unawaited(_probe());+ }++ @override+ void dispose() {+ _ticker?.cancel();+ _logScroll.dispose();+ super.dispose();+ }++ Future<void> _probe() async {+ setState(() {+ _phase = _Phase.probing;+ _log.clear();+ _steps.clear();+ _problem = null;+ });+ final probe = await widget.flasher.probe();+ if (!mounted) return;+ setState(() {+ _log+ ..clear()+ ..addAll(probe.log);+ _ports = probe.ports;+ _port = probe.ports.length == 1 ? probe.ports.first : null;+ _problem = probe.problem;+ _phase = probe.found ? _Phase.ready : _Phase.noBoard;+ });+ }++ Future<void> _flash() async {+ setState(() {+ _phase = _Phase.flashing;+ _log.clear();+ _steps.clear();+ _stepFailed = false;+ _problem = null;+ _elapsed = Stopwatch()..start();+ });+ _ticker = Timer.periodic(+ const Duration(seconds: 1),+ (_) => mounted ? setState(() {}) : null,+ );++ final result = await widget.flasher.flash(port: _port, onLine: _onLine);+ _ticker?.cancel();+ _elapsed?.stop();+ if (!mounted) return;+ setState(() {+ if (!result.ok) _stepFailed = true;+ _phase = result.ok ? _Phase.done : _Phase.failed;+ if (!result.ok) {+ _problem = result.cancelled+ ? 'Stopped. Harness has been started again.'+ : _lastTrouble() ?? 'The flasher exited with ${result.exitCode}.';+ }+ });+ }++ void _onLine(FlashLine line) {+ if (!mounted) return;+ setState(() {+ _log.add(line);+ if (line.kind == FlashLineKind.step) _steps.add(line.title);+ });+ // Follow the tail the way a terminal does.+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (_logScroll.hasClients) {+ _logScroll.jumpTo(_logScroll.position.maxScrollExtent);+ }+ });+ }++ String? _lastTrouble() {+ for (final line in _log.reversed) {+ if (line.kind == FlashLineKind.error ||+ line.kind == FlashLineKind.warning) {+ return line.text.trim().replaceFirst(RegExp(r'^error:\s*'), '');+ }+ }+ return null;+ }++ /// The version the script said it wrote, once it has said so.+ String? get _version {+ for (final line in _log) {+ final match = RegExp(r'^>> release: \S+ (\S+)').firstMatch(line.text);+ if (match != null) return match.group(1);+ }+ return null;+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return PopScope(+ canPop: _phase != _Phase.flashing,+ child: Dialog(+ // See the note on the other two dialogs: `dialogTheme` owns the+ // fill, the radius and the absence of a rim.+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 540),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(18, 17, 18, 0),+ child: _header(),+ ),+ Flexible(+ child: SingleChildScrollView(+ padding: const EdgeInsets.fromLTRB(18, 14, 18, 0),+ child: _body(),+ ),+ ),+ _actions(),+ ],+ ),+ ),+ ),+ );+ }++ // ---------------------------------------------------------------- header++ Widget _header() {+ final (+ IconData? icon,+ Color tone,+ String title,+ String sub,+ ) = switch (_phase) {+ _Phase.probing => (+ null,+ grid.AppPalette.accentOnSurface,+ 'Looking for the dial…',+ 'Checking the USB ports on this Mac.',+ ),+ _Phase.ready => (+ LucideIcons.zap300,+ grid.AppPalette.accentOnSurface,+ 'Flash firmware to the dial',+ 'Writes the latest circle release over USB.',+ ),+ _Phase.noBoard => (+ LucideIcons.usb300,+ grid.AppPalette.warn,+ 'No dial found',+ _problem ??+ 'Plug the dial into this Mac with a USB cable, then look '+ 'again.',+ ),+ _Phase.flashing => (+ null,+ grid.AppPalette.accentOnSurface,+ _version == null+ ? 'Flashing the dial…'+ : 'Flashing $_version → ${_port ?? 'the dial'}',+ 'Don’t unplug the dial.',+ ),+ _Phase.done => (+ LucideIcons.circleCheck300,+ grid.AppPalette.online,+ _version == null+ ? 'The dial is flashed'+ : 'circle $_version is on the dial',+ 'Harness is running again. Your machines are back.',+ ),+ _Phase.failed => (+ LucideIcons.triangleAlert300,+ grid.AppPalette.dangerFill,+ 'Flash failed',+ _problem ?? 'Nothing else was changed. Harness has been started again.',+ ),+ };++ return Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Container(+ width: 34,+ height: 34,+ decoration: BoxDecoration(+ color: tone.withValues(alpha: 0.13),+ borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),+ ),+ alignment: Alignment.center,+ child: icon == null+ ? SizedBox(+ width: 17,+ height: 17,+ child: CircularProgressIndicator(strokeWidth: 2, color: tone),+ )+ : Icon(icon, size: 18, color: tone),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ title,+ style: TextStyle(+ color: grid.AppPalette.textPrimary,+ fontSize: 15,+ fontWeight: grid.AppFont.semibold,+ ),+ ),+ const SizedBox(height: 3),+ Text(+ sub,+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 12.5,+ height: 1.5,+ ),+ ),+ ],+ ),+ ),+ ],+ );+ }++ // ------------------------------------------------------------------ body++ Widget _body() {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (_phase == _Phase.ready) ...[+ _facts(),+ if (_ports.length > 1) _portPicker(),+ _daemonNotice(),+ ],+ if (_phase == _Phase.done) _facts(),+ if (_phase == _Phase.flashing || _phase == _Phase.failed) ...[+ _stepList(),+ if (_phase == _Phase.flashing) ...[+ const SizedBox(height: 13),+ // Indeterminate on purpose. esptool prints a percentage, but it is+ // the percentage of ONE write — following it would run the bar to+ // full and drop it back to zero several times over.+ LinearProgressIndicator(+ minHeight: 2,+ backgroundColor: grid.AppGlass.hair,+ color: grid.AppPalette.accentOnSurface,+ ),+ ],+ ],+ if (_log.isNotEmpty && _phase != _Phase.ready) _logPane(),+ ],+ );+ }++ Widget _facts() {+ final done = _phase == _Phase.done;+ return Column(+ children: [+ _fact('Board', _port ?? 'the dial'),+ const SizedBox(height: 7),+ if (done) ...[+ _fact('Flashed', _version ?? 'circle'),+ const SizedBox(height: 7),+ _fact('Took', _formatElapsed(), tone: grid.AppPalette.textSecondary),+ ] else+ // Not a version number: --detect-only returns before the script+ // resolves the release, so nothing here knows it yet, and inventing+ // one would be a guess presented as a fact.+ _fact('Will install', 'circle · latest'),+ ],+ );+ }++ Widget _fact(String label, String value, {Color? tone}) {+ grid.AppTheme.watch(context);+ return Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(+ width: 104,+ child: Text(+ label,+ style: TextStyle(color: grid.AppPalette.textFaint, fontSize: 11.5),+ ),+ ),+ Expanded(+ child: Text(+ value,+ style: TextStyle(+ color: tone ?? grid.AppPalette.textSecondary,+ fontSize: 11.5,+ fontFamily: grid.AppFont.mono,+ fontFamilyFallback: grid.AppFont.monoFallback,+ ),+ ),+ ),+ ],+ );+ }++ Widget _portPicker() {+ return Padding(+ padding: const EdgeInsets.only(top: 13),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'More than one board is connected — pick one:',+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 12,+ ),+ ),+ const SizedBox(height: 7),+ for (final port in _ports)+ _PortChoice(+ port: port,+ selected: port == _port,+ onTap: () => setState(() => _port = port),+ ),+ ],+ ),+ );+ }++ Widget _daemonNotice() {+ return Container(+ margin: const EdgeInsets.only(top: 13),+ padding: const EdgeInsets.fromLTRB(11, 10, 11, 10),+ decoration: BoxDecoration(+ color: grid.AppPalette.warn.withValues(alpha: 0.09),+ border: Border.all(color: grid.AppPalette.warn.withValues(alpha: 0.24)),+ borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),+ ),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Icon(+ LucideIcons.triangleAlert300,+ size: 14,+ color: grid.AppPalette.warn,+ ),+ const SizedBox(width: 9),+ Expanded(+ child: RichText(+ text: TextSpan(+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 11.5,+ height: 1.5,+ ),+ children: [+ TextSpan(+ text: 'Harness stops while flashing. ',+ style: TextStyle(+ color: grid.AppPalette.textPrimary,+ fontWeight: grid.AppFont.semibold,+ ),+ ),+ const TextSpan(+ text:+ 'The flasher has to close the serial port, so your '+ 'machines go offline for about a minute and come back '+ 'on their own.',+ ),+ ],+ ),+ ),+ ),+ ],+ ),+ );+ }++ Widget _stepList() {+ return Column(+ children: [+ for (var i = 0; i < _steps.length; i++)+ _StepRow(+ label: _steps[i],+ state: i < _steps.length - 1+ ? _StepState.done+ : _stepFailed+ ? _StepState.failed+ : _phase == _Phase.flashing+ ? _StepState.running+ : _StepState.done,+ ),+ ],+ );+ }++ Widget _logPane() {+ return Container(+ margin: const EdgeInsets.only(top: 13),+ decoration: BoxDecoration(+ border: Border.all(color: grid.AppGlass.hair),+ borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),+ ),+ clipBehavior: Clip.antiAlias,+ child: Column(+ children: [+ Container(+ padding: const EdgeInsets.fromLTRB(10, 7, 10, 7),+ color: grid.AppPalette.windowBg,+ child: Row(+ children: [+ Icon(+ LucideIcons.squareTerminal300,+ size: 13,+ color: grid.AppPalette.textFaint,+ ),+ const SizedBox(width: 8),+ Text(+ 'Output',+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 11.5,+ ),+ ),+ const Spacer(),+ Text(+ 'flash-circle.sh',+ style: TextStyle(+ color: grid.AppPalette.textFaint,+ fontSize: 11.5,+ ),+ ),+ ],+ ),+ ),+ Container(+ constraints: const BoxConstraints(maxHeight: 170),+ width: double.infinity,+ color: grid.AppPalette.windowBg,+ child: SingleChildScrollView(+ controller: _logScroll,+ padding: const EdgeInsets.fromLTRB(11, 9, 11, 9),+ child: SelectableText.rich(+ TextSpan(+ children: [+ for (final line in _log)+ TextSpan(+ text: '${line.text}\n',+ style: TextStyle(color: _inkFor(line.kind)),+ ),+ ],+ ),+ style: TextStyle(+ fontSize: 11,+ height: 1.62,+ fontFamily: grid.AppFont.mono,+ fontFamilyFallback: grid.AppFont.monoFallback,+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }++ Color _inkFor(FlashLineKind kind) => switch (kind) {+ FlashLineKind.step => grid.AppPalette.textPrimary,+ FlashLineKind.detail => grid.AppPalette.textSecondary,+ FlashLineKind.warning => grid.AppPalette.warn,+ FlashLineKind.error => grid.AppPalette.dangerFill,+ };++ // --------------------------------------------------------------- actions++ Widget _actions() {+ final children = <Widget>[];++ if (_log.isNotEmpty && _phase != _Phase.probing) {+ children.add(+ _DialogButton(+ label: 'Copy log',+ onPressed: () => unawaited(+ Clipboard.setData(+ ClipboardData(text: _log.map((l) => l.text).join('\n')),+ ),+ ),+ ),+ );+ }+ children.add(const Spacer());++ switch (_phase) {+ case _Phase.probing:+ children.add(+ _DialogButton(+ label: 'Cancel',+ onPressed: () => Navigator.pop(context),+ ),+ );+ case _Phase.ready:+ children+ ..add(+ _DialogButton(+ label: 'Cancel',+ kind: _ButtonKind.ghost,+ onPressed: () => Navigator.pop(context),+ ),+ )+ ..add(const SizedBox(width: 8))+ ..add(+ _DialogButton(+ key: const Key('flash-start-button'),+ label: 'Flash',+ kind: _ButtonKind.primary,+ // The script asks for confirmation on a terminal it does not+ // have here, so it runs with --yes. THIS is the confirmation.+ onPressed: _port == null && _ports.length > 1+ ? null+ : () => unawaited(_flash()),+ ),+ );+ case _Phase.noBoard:+ children+ ..add(+ _DialogButton(+ label: 'Close',+ kind: _ButtonKind.ghost,+ onPressed: () => Navigator.pop(context),+ ),+ )+ ..add(const SizedBox(width: 8))+ ..add(+ _DialogButton(+ label: 'Look again',+ kind: _ButtonKind.primary,+ onPressed: () => unawaited(_probe()),+ ),+ );+ case _Phase.flashing:+ children.add(+ _DialogButton(+ key: const Key('flash-stop-button'),+ label: 'Stop',+ kind: _ButtonKind.ghost,+ onPressed: widget.flasher.cancel,+ ),+ );+ case _Phase.done:+ children.add(+ _DialogButton(+ label: 'Done',+ kind: _ButtonKind.primary,+ onPressed: () => Navigator.pop(context),+ ),+ );+ case _Phase.failed:+ children+ ..add(+ _DialogButton(+ label: 'Close',+ kind: _ButtonKind.ghost,+ onPressed: () => Navigator.pop(context),+ ),+ )+ ..add(const SizedBox(width: 8))+ ..add(+ _DialogButton(+ label: 'Try again',+ kind: _ButtonKind.primary,+ onPressed: () => unawaited(_flash()),+ ),+ );+ }++ return Container(+ margin: const EdgeInsets.only(top: 14),+ padding: const EdgeInsets.fromLTRB(18, 12, 18, 12),+ decoration: BoxDecoration(+ border: Border(top: BorderSide(color: grid.AppGlass.hair)),+ ),+ child: Row(children: children),+ );+ }++ String _formatElapsed() {+ final seconds = (_elapsed?.elapsed.inSeconds ?? 0);+ final minutes = seconds ~/ 60;+ return '$minutes:${(seconds % 60).toString().padLeft(2, '0')}';+ }+}++enum _StepState { done, running, failed }++class _StepRow extends StatelessWidget {+ const _StepRow({required this.label, required this.state});++ final String label;+ final _StepState state;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final (Widget mark, Color ink) = switch (state) {+ _StepState.done => (+ Icon(+ LucideIcons.circleCheck300,+ size: 14,+ color: grid.AppPalette.online,+ ),+ grid.AppPalette.textSecondary,+ ),+ _StepState.running => (+ SizedBox(+ width: 13,+ height: 13,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ color: grid.AppPalette.accentOnSurface,+ ),+ ),+ grid.AppPalette.textPrimary,+ ),+ _StepState.failed => (+ Icon(+ LucideIcons.triangleAlert300,+ size: 14,+ color: grid.AppPalette.dangerFill,+ ),+ grid.AppPalette.textPrimary,+ ),+ };++ return Padding(+ padding: const EdgeInsets.symmetric(vertical: 3),+ child: Row(+ children: [+ SizedBox(width: 16, child: Center(child: mark)),+ const SizedBox(width: 9),+ Expanded(+ child: Text(+ label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(color: ink, fontSize: 12.5),+ ),+ ),+ ],+ ),+ );+ }+}++enum _ButtonKind { quiet, ghost, primary }++class _DialogButton extends StatelessWidget {+ const _DialogButton({+ super.key,+ required this.label,+ required this.onPressed,+ this.kind = _ButtonKind.quiet,+ });++ final String label;+ final VoidCallback? onPressed;+ final _ButtonKind kind;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final primary = kind == _ButtonKind.primary;+ return TextButton(+ onPressed: onPressed,+ style: TextButton.styleFrom(+ minimumSize: const Size(0, 28),+ padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 5),+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ visualDensity: VisualDensity.standard,+ backgroundColor: primary+ ? grid.AppPalette.accentOnSurface+ : Colors.transparent,+ foregroundColor: primary+ ? grid.AppPalette.windowBg+ : grid.AppPalette.textSecondary,+ disabledForegroundColor: grid.AppPalette.textFaint,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(7),+ side: kind == _ButtonKind.ghost+ ? BorderSide(color: grid.AppGlass.hair)+ : BorderSide.none,+ ),+ textStyle: TextStyle(+ fontSize: 12,+ fontWeight: primary ? grid.AppFont.semibold : grid.AppFont.regular,+ ),+ ),+ child: Text(label),+ );+ }+}++/// One selectable serial port, when more than one board is plugged in.+class _PortChoice extends StatelessWidget {+ const _PortChoice({+ required this.port,+ required this.selected,+ required this.onTap,+ });++ final String port;+ final bool selected;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final accent = grid.AppPalette.accentOnSurface;+ return InkWell(+ onTap: onTap,+ borderRadius: BorderRadius.circular(7),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),+ child: Row(+ children: [+ Container(+ width: 13,+ height: 13,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ border: Border.all(+ color: selected ? accent : grid.AppPalette.textFaint,+ width: 1.5,+ ),+ ),+ alignment: Alignment.center,+ child: selected+ ? Container(+ width: 6,+ height: 6,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: accent,+ ),+ )+ : null,+ ),+ const SizedBox(width: 9),+ Text(+ port,+ style: TextStyle(+ color: grid.AppPalette.textPrimary,+ fontSize: 12,+ fontFamily: grid.AppFont.mono,+ fontFamilyFallback: grid.AppFont.monoFallback,+ ),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/lib/widgets/layout_palette.dart b/mobile/lib/widgets/layout_palette.dartnew file mode 100644index 000000000..8dfff1d58--- /dev/null+++ b/mobile/lib/widgets/layout_palette.dart@@ -0,0 +1,545 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import '../shortcuts/app_keymap.dart';+import '../shortcuts/keymap.dart';+import '../state/pane_preset.dart';+import '../theme/app_theme.dart';++/// ⌘S — pick the shape of the grid.+///+/// Shapes are DRAWN, not listed. "Two over one" and "one over two" are the same+/// four words in a different order, and nobody reads a layout name twice; the+/// little diagram is the whole interface and the label only confirms it.+///+/// Every card describes a distinct concrete arrangement. Automatic defaults+/// resolve to the matching card, instead of adding a duplicate picture.+/// Set while the palette is up, so a second ⌘S can be answered rather than+/// stacking a route.+///+/// It used to be a bool and a bare return. That stopped the palette fading the+/// window to black under a held key — each press laid another dialog and another+/// 30% barrier over the last — but it left ⌘S meaning "open" once and nothing+/// ever after, which is the one thing a person holding a key does not expect.+///+/// THE SAME KEY WALKS THE STRIP. ⌘S opens it, ⌘S again steps to the next shape,+/// Enter takes it. That is how every cycling chord on this OS behaves, and it+/// means the shape can be chosen without the hand leaving the chord it arrived+/// on.+bool Function()? _layoutPaletteAdvance;++/// Advance the visible palette without opening another route behind a dialog.+bool advanceLayoutPalette() => _layoutPaletteAdvance?.call() ?? false;++Future<void> showLayoutPalette(BuildContext context, AppNotifier notifier) {+ if (advanceLayoutPalette()) {+ return Future<void>.value();+ }+ return showAppDialog<void>(+ context: context,+ builder: (context) => _LayoutPalette(notifier: notifier),+ ).whenComplete(() => _layoutPaletteAdvance = null);+}++/// The strip's geometry, in one place.+///+/// Both the [Wrap] that draws the shapes and the keys that walk them read these.+/// They used to be literals in the build method alone, which is why the arrow+/// keys could not tell a row from a column: nothing outside the layout knew how+/// many shapes fitted on a line.+/// Where [at] lands after one press, on a strip [n] long.+///+/// BOTH AXES WRAP. The strip is short and every shape is on screen, so running+/// off one end and appearing at the other cannot be mistaken for a jump to+/// somewhere unseen — and a key that dies at the edge is one people stop+/// trusting, which is the same argument the window's own pane ring rests on.+///+/// Vertical keeps the COLUMN: down from the second shape lands under it, not+/// at the start of the next line. A last row shorter than the others clamps,+/// because there is no shape under that column to land on.+int layoutPaletteMove(int at, int n, int dx, int dy, int perRow) {+ if (n <= 1) return 0;+ if (dx != 0) return (at + dx + n) % n;+ final rows = (n / perRow).ceil();+ if (rows <= 1) return at; // one line has no up and no down+ final col = at % perRow;+ final row = at ~/ perRow;+ final target = ((row + dy + rows) % rows) * perRow + col;+ return target >= n ? n - 1 : target;+}++class _Strip {+ /// Wide enough that a diagram stays readable — see the note on the Wrap.+ static const shape = 108.0;+ static const diagram = 86.0;+ static const gap = 10.0;+ static const sidePadding = 14.0;++ /// The dialog's own width, which changes with how many shapes there are.+ static double width(int choices) {+ final columns = choices > 4 ? 3 : choices.clamp(1, 4);+ return sidePadding * 2 + shape * columns + gap * (columns - 1);+ }++ /// How many shapes sit on one line. The same arithmetic Wrap does.+ static int perRow(int choices, double width, double shape) {+ final room = width - sidePadding * 2;+ final fits = ((room + gap) / (shape + gap)).floor();+ return fits.clamp(1, choices < 1 ? 1 : choices);+ }+}++class _LayoutPalette extends StatefulWidget {+ const _LayoutPalette({required this.notifier});++ final AppNotifier notifier;++ @override+ State<_LayoutPalette> createState() => _LayoutPaletteState();+}++class _LayoutPaletteState extends State<_LayoutPalette> {+ /// An EXPLICIT node, requested after the first frame.+ ///+ /// `autofocus: true` alone was not enough: it only takes the focus when the+ /// enclosing scope has none to give, and by the time this is laid out the+ /// route that opened it has already settled focus somewhere. The symptom was+ /// precise — ⌘S opened the palette and cycled it, because that chord is a+ /// global binding, while the arrow keys did nothing at all, because those are+ /// read HERE and nothing here was listening.+ final FocusNode _keys = FocusNode(debugLabel: 'layout-palette');+ final _shapeKeys = List.generate(6, (_) => GlobalKey());+ int _perRow = 1;+ bool _revealPending = false;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _keys.requestFocus();+ });+ // Registered here rather than by the opener, so the hook cannot outlive the+ // widget it steps: a stale callback would move a cursor on a palette that+ // is no longer on screen, and the next ⌘S would find the strip already+ // walked.+ _layoutPaletteAdvance = _advance;+ }++ @override+ void dispose() {+ if (_layoutPaletteAdvance == _advance) _layoutPaletteAdvance = null;+ _keys.dispose();+ super.dispose();+ }++ /// Advance one choice with the configured Layout key, without applying it.+ bool _advance() {+ if (!mounted || ModalRoute.isCurrentOf(context) == false) return false;+ final count = widget.notifier.panes.length;+ final choices = PanePreset.forCount(count);+ if (choices.isEmpty) return true;+ // presetFor is keyed on the PANE COUNT, not on how many shapes that count+ // offers — the two are different numbers and only one of them is a key.+ final at = _cursorIn(choices, _currentChoice(count));+ _select((at + 1) % choices.length);+ return true;+ }++ /// Which shape the arrow keys are resting on, which is NOT the same as the+ /// one in use: moving the cursor must not rearrange the grid under someone+ /// still looking at the choices. Applying is Enter, a digit, or a click.+ int? _cursor;++ void _select(int index) {+ if (_cursor == index) return;+ setState(() => _cursor = index);+ if (_revealPending) return;+ _revealPending = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ _revealPending = false;+ if (!mounted || ModalRoute.isCurrentOf(context) == false) return;+ final target = _shapeKeys[_cursor!].currentContext;+ if (target != null) {+ Scrollable.ensureVisible(+ target,+ alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,+ );+ }+ });+ }++ /// Where the cursor is, read from state rather than from a captured local.+ ///+ /// Two keys can land inside one frame — an arrow and the Enter that takes it+ /// — and a value closed over at build time would still hold the position+ /// BEFORE the arrow moved, so the palette would apply the shape the cursor+ /// had just left. Reading it here means the answer is always current.+ ///+ /// It starts on the shape already in use, so the first arrow press steps off+ /// that one rather than jumping to the top of the list.+ int _cursorIn(List<PanePreset> choices, PanePreset? current) {+ if (choices.isEmpty) return 0;+ final start = _cursor ?? choices.indexOf(current ?? choices.first);+ return start.clamp(0, choices.length - 1);+ }++ PanePreset? _currentChoice(int count) {+ final notifier = widget.notifier;+ final preset = notifier.presetFor(count);+ if (preset == null || PanePreset.forCount(count).contains(preset)) {+ return preset;+ }+ final actual = notifier.activeSwarm.arranged?.tiles;+ if (actual != null && actual.length == count) {+ return PanePreset.matchingChoice(count, actual);+ }+ final viewport = MediaQuery.sizeOf(context);+ final resolved =+ preset == PanePreset.splitLong && viewport.height > viewport.width+ ? PanePreset.rows+ : preset;+ return PanePreset.matchingChoice(+ count,+ resolved.tilesFor(count, columns: notifier.gridColumns),+ );+ }++ @override+ Widget build(BuildContext context) {+ final notifier = widget.notifier;+ grid.AppTheme.watch(context);+ final count = notifier.panes.length;+ final choices = PanePreset.forCount(count);+ final current = _currentChoice(count);+ final cursor = _cursorIn(choices, current);+ final textScale = MediaQuery.textScalerOf(context).scale(11.5) / 11.5;+ final shapeWidth = (_Strip.shape * textScale).clamp(_Strip.shape, 216.0);+ final paletteWidth =+ _Strip.width(choices.length) * textScale.clamp(1.0, 2.0);++ return KeymapRegion(+ contextKind: KeymapContext.workspace,+ actions: {+ 'pane.layout': () {+ _advance();+ },+ },+ child: Dialog(+ backgroundColor: grid.AppGlass.surfaceFill,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(13),+ side: BorderSide(color: grid.AppGlass.hair),+ ),+ child: Focus(+ focusNode: _keys,+ autofocus: true,+ onKeyEvent: (node, event) {+ // Repeats count: holding an arrow should walk the list, the way it+ // does in every other list on this OS.+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {+ return KeyEventResult.ignored;+ }+ // The keymap handles configured chords before this local handler.+ // Modified digits/arrows must not fall through as a plain selection.+ final keyboard = HardwareKeyboard.instance;+ if (keyboard.isMetaPressed ||+ keyboard.isControlPressed ||+ keyboard.isAltPressed ||+ keyboard.isShiftPressed) {+ return KeyEventResult.ignored;+ }+ if (choices.isEmpty) return KeyEventResult.ignored;++ void apply(PanePreset preset) {+ notifier.setPreset(count, preset);+ Navigator.of(context).pop();+ }++ final at = _cursorIn(choices, current);+ final direction = _direction(event.logicalKey);+ if (direction != null) {+ _select(+ layoutPaletteMove(+ at,+ choices.length,+ direction.$1,+ direction.$2,+ _perRow,+ ),+ );+ return KeyEventResult.handled;+ }+ if (_isCommit(event.logicalKey)) {+ apply(choices[at]);+ return KeyEventResult.handled;+ }+ final index = _digit(event.logicalKey);+ if (index == null || index > choices.length) {+ return KeyEventResult.ignored;+ }+ apply(choices[index - 1]);+ return KeyEventResult.handled;+ },+ child: ConstrainedBox(+ // Wide enough that four shapes still get a diagram big enough to read+ // and a label that is not ellipsised into a guess.+ constraints: BoxConstraints(maxWidth: paletteWidth),+ child: LayoutBuilder(+ builder: (context, constraints) {+ // Read the same available width the Wrap uses, including text+ // scaling and a window narrower than the preferred palette.+ _perRow = _Strip.perRow(+ choices.length,+ constraints.maxWidth,+ shapeWidth,+ );+ return SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(18, 16, 18, 12),+ child: Text(+ choices.isEmpty ? 'Layout' : 'Layout · $count panes',+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 11.5,+ letterSpacing: 0.9,+ fontWeight: grid.AppFont.medium,+ ),+ ),+ ),+ if (choices.isEmpty)+ Padding(+ padding: const EdgeInsets.fromLTRB(18, 0, 18, 20),+ child: Text(+ 'One tile has no layout to choose. Open another and the '+ 'shapes appear here.',+ style: TextStyle(+ color: grid.AppPalette.textFaint,+ fontSize: 12.5,+ height: 1.45,+ ),+ ),+ )+ else ...[+ Padding(+ padding: const EdgeInsets.fromLTRB(+ _Strip.sidePadding,+ 0,+ _Strip.sidePadding,+ 6,+ ),+ // Wrapped, not a Row: a big grid offers five column counts,+ // and five diagrams squeezed across one line are five things+ // nobody can tell apart. 108px keeps a shape readable.+ child: Wrap(+ spacing: _Strip.gap,+ runSpacing: _Strip.gap,+ children: [+ for (var i = 0; i < choices.length; i++)+ SizedBox(+ key: _shapeKeys[i],+ width: shapeWidth,+ child: _ShapeButton(+ preset: choices[i],+ count: count,+ index: i + 1,+ selected: choices[i] == current,+ cursor: i == cursor,+ onTap: () {+ notifier.setPreset(count, choices[i]);+ Navigator.of(context).pop();+ },+ ),+ ),+ ],+ ),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(18, 6, 18, 14),+ child: Text(+ 'Arrows to move · Enter or 1–${choices.length} to apply.\n'+ 'Changing layout resets pane sizes.',+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 11,+ height: 1.4,+ ),+ ),+ ),+ ],+ ],+ ),+ );+ },+ ),+ ),+ ),+ ),+ );+ }++ /// Which way an arrow moves the cursor.+ /// Which way a key points, as (dx, dy).+ ///+ /// hjkl beside the arrows, unmodified, for the reason the window binds both: a+ /// hand that reaches for one and a hand that reaches for the other are two+ /// hands on the same keyboard. Bare letters are safe HERE and nowhere else in+ /// this app — a dialog is not a pty, and no shell is waiting behind it.+ ///+ /// UP AND DOWN ARE VERTICAL. They used to be a second spelling of left and+ /// right — every key stepped the list by one — on the reasoning that a+ /// vertical key would do nothing on a single-row palette. What that actually+ /// produced was `j` walking sideways, which is worse than a key that waits:+ /// the motion did not match the arrow on the cap.+ static (int, int)? _direction(LogicalKeyboardKey key) => switch (key) {+ LogicalKeyboardKey.arrowLeft || LogicalKeyboardKey.keyH => (-1, 0),+ LogicalKeyboardKey.arrowRight || LogicalKeyboardKey.keyL => (1, 0),+ LogicalKeyboardKey.arrowUp || LogicalKeyboardKey.keyK => (0, -1),+ LogicalKeyboardKey.arrowDown || LogicalKeyboardKey.keyJ => (0, 1),+ _ => null,+ };++ static bool _isCommit(LogicalKeyboardKey key) =>+ key == LogicalKeyboardKey.enter ||+ key == LogicalKeyboardKey.numpadEnter ||+ key == LogicalKeyboardKey.space;++ static int? _digit(LogicalKeyboardKey key) {+ const digits = [+ LogicalKeyboardKey.digit1,+ LogicalKeyboardKey.digit2,+ LogicalKeyboardKey.digit3,+ LogicalKeyboardKey.digit4,+ LogicalKeyboardKey.digit5,+ LogicalKeyboardKey.digit6,+ ];+ final index = digits.indexOf(key);+ return index < 0 ? null : index + 1;+ }+}++class _ShapeButton extends StatelessWidget {+ const _ShapeButton({+ required this.preset,+ required this.count,+ required this.index,+ required this.selected,+ required this.cursor,+ required this.onTap,+ });++ final PanePreset preset;+ final int count;+ final int index;++ /// The shape the grid is in now.+ final bool selected;++ /// Where the arrow keys are resting. Drawn as a ring rather than as the+ /// selected fill, so "what I am about to pick" never looks like "what is+ /// already in use" — the two are different answers and both are on screen.+ final bool cursor;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ return GestureDetector(+ onTap: onTap,+ child: Container(+ padding: const EdgeInsets.fromLTRB(10, 10, 10, 8),+ decoration: BoxDecoration(+ color: selected+ ? grid.AppSurface.accentWash+ : grid.AppSurface.hoverFill,+ borderRadius: BorderRadius.circular(10),+ border: Border.all(+ color: selected ? AppColors.accent : grid.AppGlass.hair,+ ),+ ),+ // Paint focus over the fixed border so moving the highlight does not+ // change the diagram's bounds or the height of the wrapped row.+ foregroundDecoration: cursor+ ? BoxDecoration(+ borderRadius: BorderRadius.circular(10),+ border: Border.all(color: AppColors.accent, width: 2),+ )+ : null,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ SizedBox(+ width: _Strip.diagram,+ height: _Strip.diagram * 3 / 4,+ child: CustomPaint(painter: _ShapePainter(preset, count)),+ ),+ const SizedBox(height: 8),+ Text(+ preset.label,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: selected+ ? grid.AppPalette.textPrimary+ : grid.AppPalette.textSecondary,+ fontSize: 11.5,+ ),+ ),+ const SizedBox(height: 2),+ Text(+ '$index',+ style: TextStyle(+ fontFamily: grid.AppFont.mono,+ fontSize: 9.5,+ color: grid.AppPalette.textSecondary,+ ),+ ),+ ],+ ),+ ),+ );+ }+}++/// The diagram: [PanePreset.tiles], drawn.+///+/// It paints the shape's own description rather than a picture of it, and+/// `pane_preset_test` measures the real grid against the same list — so an+/// illustration that lies about the layout fails a test instead of misleading+/// someone into picking the wrong shape.+class _ShapePainter extends CustomPainter {+ const _ShapePainter(this.preset, this.count);++ final PanePreset preset;+ final int count;++ @override+ void paint(Canvas canvas, Size size) {+ final fill = Paint()..color = AppColors.accent.withValues(alpha: 0.55);+ for (final unit in preset.tilesFor(count)) {+ // Dense layouts must still draw every pane. A fixed 3px inset erased+ // short rows entirely once the diagram contained more than 21 rows.+ final gapX = (unit.width * size.width * .12).clamp(0.0, 1.5);+ final gapY = (unit.height * size.height * .12).clamp(0.0, 1.5);+ final rect = Rect.fromLTRB(+ unit.left * size.width + gapX,+ unit.top * size.height + gapY,+ unit.right * size.width - gapX,+ unit.bottom * size.height - gapY,+ );+ canvas.drawRRect(+ RRect.fromRectAndRadius(rect, const Radius.circular(2)),+ fill,+ );+ }+ }++ @override+ bool shouldRepaint(_ShapePainter old) =>+ old.preset != preset || old.count != count;+}diff --git a/mobile/lib/widgets/link_machine_screen.dart b/mobile/lib/widgets/link_machine_screen.dartnew file mode 100644index 000000000..dcb5b783b--- /dev/null+++ b/mobile/lib/widgets/link_machine_screen.dart@@ -0,0 +1,275 @@+import 'package:flutter/material.dart';++import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import '../theme/app_theme.dart';++/// Opens [LinkMachineScreen] as a modal popup for [machineId], closing itself automatically once+/// linking succeeds or the prompt is dismissed (including a barrier tap/Escape, which counts as an+/// implicit dismiss so the caller's reactive gate doesn't just reopen it next frame).+///+/// This is a deliberate exception to the pane grid's normal "never block other tiles" rule (see+/// `AppNotifier.showMachinePane`'s doc comment) — a machine that still needs linking has nothing+/// else useful to show in its own tile, and a transient blocking prompt reads better here than a+/// permanent docked panel that looks like a second tab.+Future<void> showLinkMachineScreenDialog(+ BuildContext context,+ AppNotifier notifier,+ String machineId,+) async {+ // Opening IS the answer to "was it dismissed?": a Cancel earlier marked the+ // machine so the reactive gates stop insisting, and the gates check that mark+ // before calling here — so anything that reaches this line is a person asking+ // to see it. Clear the mark, or the check inside pops the dialog on its first+ // frame and the row reads as dead.+ notifier.revisitLinkPrompt(machineId);+ await showAppDialog<void>(+ context: context,+ builder: (context) => Dialog(+ backgroundColor: Colors.transparent,+ elevation: 0,+ insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),+ child: ListenableBuilder(+ listenable: notifier,+ builder: (context, _) {+ final state = notifier.stateOf(machineId);+ final stillNeeded =+ state != null &&+ state.needsLink &&+ !notifier.isLinkPromptDismissed(machineId);+ if (!stillNeeded) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (Navigator.of(context).canPop()) Navigator.of(context).pop();+ });+ return const SizedBox.shrink();+ }+ return LinkMachineScreen(notifier: notifier, machineState: state);+ },+ ),+ ),+ );+ // Any close that isn't "linked successfully" (barrier tap, Escape, the in-card Close button)+ // must count as a dismiss, or the caller's reactive gate would just reopen this next rebuild.+ final state = notifier.stateOf(machineId);+ if (state != null && state.needsLink) {+ notifier.dismissLinkPrompt(machineId);+ }+}++/// Shown for a remote machine the local CLI's relay has no linked trust for yet. The CLI now owns+/// E2EE entirely (see the harness CLI's `harness remote-password set`/`harness link connect`, and+/// src/lib/remoteRelay.ts) — this screen holds no crypto state, it just walks the user through+/// entering the remote password set on the OTHER machine.+class LinkMachineScreen extends StatefulWidget {+ final AppNotifier notifier;+ final MachineState machineState;+ const LinkMachineScreen({+ super.key,+ required this.notifier,+ required this.machineState,+ });++ @override+ State<LinkMachineScreen> createState() => _LinkMachineScreenState();+}++class _LinkMachineScreenState extends State<LinkMachineScreen> {+ final _passwordController = TextEditingController();+ bool _obscure = true;+ bool _submitting = false;+ bool _showTroubleshootingDetails = false;+ String? _error;+ String? _stage;++ @override+ void dispose() {+ _passwordController.dispose();+ super.dispose();+ }++ Future<void> _submit() async {+ setState(() {+ _submitting = true;+ _error = null;+ _stage = null;+ });+ final error = await widget.notifier.connectWithPassword(+ widget.machineState.machine.machineId,+ _passwordController.text,+ onProgress: (stage) {+ if (mounted) setState(() => _stage = stage);+ },+ );+ if (!mounted) return;+ setState(() {+ _submitting = false;+ _error = error;+ _stage = null;+ });+ if (error == null) _passwordController.clear();+ }++ @override+ Widget build(BuildContext context) {+ final machineId = widget.machineState.machine.machineId;+ final machineName = widget.machineState.machine.displayName;++ return Container(+ width: 460,+ padding: const EdgeInsets.all(24),+ decoration: BoxDecoration(+ border: Border.all(color: AppColors.border),+ borderRadius: BorderRadius.circular(14),+ color: AppColors.surface,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Icon(Icons.link, size: 32, color: AppColors.accent),+ const SizedBox(height: 6),+ Text(+ 'Link this machine',+ style: TextStyle(+ fontFamily: AppFonts.sans,+ fontFamilyFallback: AppFonts.sansFallback,+ fontSize: 13.5,+ fontWeight: FontWeight.w600,+ color: AppColors.text,+ ),+ ),+ const SizedBox(height: 6),+ Text(+ "This computer isn't linked to $machineName yet. Enter the remote password set "+ 'on that machine to connect.',+ style: TextStyle(+ fontFamily: AppFonts.sans,+ fontFamilyFallback: AppFonts.sansFallback,+ fontSize: 11.2,+ color: AppColors.mutedStrong,+ ),+ ),+ const SizedBox(height: 14),+ TextField(+ key: const Key('remote-password-connect-field'),+ controller: _passwordController,+ obscureText: _obscure,+ style: TextStyle(+ fontFamily: AppFonts.mono,+ fontSize: 12.5,+ color: AppColors.textSoft,+ ),+ decoration: InputDecoration(+ hintText: 'Remote password for $machineName',+ hintStyle: TextStyle(fontFamily: AppFonts.mono, fontSize: 12.5),+ prefixIcon: const Icon(Icons.password, size: 17),+ suffixIcon: IconButton(+ icon: Icon(+ _obscure ? Icons.visibility : Icons.visibility_off,+ size: 17,+ ),+ onPressed: () => setState(() => _obscure = !_obscure),+ ),+ ),+ onSubmitted: (_) => _submit(),+ ),+ if (_error != null) ...[+ const SizedBox(height: 6),+ Text(+ _error!,+ style: TextStyle(+ fontFamily: AppFonts.sans,+ fontFamilyFallback: AppFonts.sansFallback,+ fontSize: 11.2,+ color: AppColors.danger,+ ),+ ),+ ],+ const SizedBox(height: 10),+ Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ if (_submitting && _stage != null) ...[+ Text(+ _stage!,+ style: TextStyle(+ fontFamily: AppFonts.sans,+ fontFamilyFallback: AppFonts.sansFallback,+ fontSize: 11.2,+ color: AppColors.mutedStrong,+ ),+ ),+ const SizedBox(width: 10),+ ],+ FilledButton(+ key: const Key('remote-password-connect-button'),+ onPressed: _submitting ? null : _submit,+ child: _submitting+ ? const SizedBox(+ width: 14,+ height: 14,+ child: CircularProgressIndicator(strokeWidth: 2),+ )+ : const Text('Link machine'),+ ),+ ],+ ),+ const SizedBox(height: 8),+ Text(+ 'Your previous harness will reconnect automatically after linking.',+ style: TextStyle(+ fontFamily: AppFonts.sans,+ fontSize: 11.2,+ color: AppColors.mutedStrong,+ ),+ ),+ const SizedBox(height: 4),+ TextButton.icon(+ key: const Key('link-troubleshooting-details'),+ onPressed: () => setState(+ () => _showTroubleshootingDetails = !_showTroubleshootingDetails,+ ),+ icon: Icon(+ _showTroubleshootingDetails+ ? Icons.expand_less+ : Icons.expand_more,+ size: 16,+ ),+ label: const Text('Troubleshooting details'),+ ),+ if (_showTroubleshootingDetails)+ Padding(+ padding: const EdgeInsets.only(left: 12),+ child: SelectableText(+ 'Machine ID: $machineId',+ style: TextStyle(+ fontFamily: AppFonts.mono,+ fontSize: 11.2,+ color: AppColors.muted,+ ),+ ),+ ),+ // An explicit way out, in addition to the barrier tap/Escape that+ // showLinkMachineScreenDialog already treats as an implicit dismiss. Closing does+ // not pretend the machine is linked: it still cannot be read and the rail still+ // says so. It only stops the popup from insisting, and choosing that machine again+ // brings it straight back. Bottom-right text button, matching every other dialog in+ // the app (see link_machine_dialog.dart's 'Close').+ const SizedBox(height: 6),+ Align(+ alignment: Alignment.centerRight,+ child: TextButton(+ style: TextButton.styleFrom(+ minimumSize: Size.zero,+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ ),+ onPressed: () => widget.notifier.dismissLinkPrompt(machineId),+ child: const Text('Close'),+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/mobile/lib/widgets/login_relay_diagram.dart b/mobile/lib/widgets/login_relay_diagram.dartnew file mode 100644index 000000000..70cb9abda--- /dev/null+++ b/mobile/lib/widgets/login_relay_diagram.dart@@ -0,0 +1,718 @@+import 'dart:math' as math;++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;++/// The sign-in screen's one picture: three machines you own, feeding one+/// window, through a middle that cannot read what it carries.+///+/// **The animation is the explanation, not decoration.** A packet leaves a+/// machine as a bare grey dot — plaintext, on hardware you control — and+/// crosses the hub, where it *becomes* a glowing sealed block and keeps that+/// halo for the rest of the trip. Nothing else in the frame moves on its own:+/// every motion here is a consequence of a packet, which is why the eye is+/// never pulled toward a part of the diagram that has nothing to say. An+/// earlier pass had a rotating rim light on the hub and a sheen sweeping the+/// whole window; both were cut for exactly that reason — they animated a thing+/// that wasn't doing anything, and the sweep reacted across four panes when+/// only one had received anything.+///+/// One clock drives all of it ([_period]), with each lane offset by+/// [_laneStagger]. That is what makes six moving parts read as one instrument+/// rather than six effects arguing; it is also why the aurora's period is an+/// exact multiple of the packet period, so the two never drift into a beat+/// against each other.+class LoginRelayDiagram extends StatefulWidget {+ const LoginRelayDiagram({super.key});++ /// The drawing's own aspect, so the caller can size it without guessing.+ static const double aspectRatio = 440 / 140;++ @override+ State<LoginRelayDiagram> createState() => _LoginRelayDiagramState();+}++/// The shared heartbeat. Every lane, halo and pane flash is a phase of this.+const Duration _period = Duration(milliseconds: 3200);++/// How far apart the three lanes fire: one third of the cycle each, so the+/// three packets are spread evenly around it rather than travelling as a clump.+///+/// **This is not a taste setting.** At the 0.075 it started on, the lanes were+/// so close together that all three were almost always in the same state, and+/// the arithmetic is unforgiving: half of every cycle had NO sealed packet on+/// screen at all, and only 4% of frames showed a grey dot and a glowing block+/// at the same time. The seal is the one beat the whole drawing exists to make,+/// and someone opening the app landed on a frame without it every other time.+///+/// At a third, no frame is ever without a sealed packet, and 76% of them carry+/// both states at once — which is what actually explains the mechanism: plain+/// on one lane, sealed on another, side by side.+const double _laneStagger = 1 / 3;++class _LoginRelayDiagramState extends State<LoginRelayDiagram>+ with SingleTickerProviderStateMixin {+ late final AnimationController _clock = AnimationController(+ vsync: this,+ duration: _period,+ );++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ // Same contract as `Pulse`: Reduce Motion parks the clock rather than+ // slowing it. The value it parks at is deliberate — see [_reducedPhase].+ //+ // `TickerMode` is checked for a second reason, and it is load-bearing: the+ // loop below runs forever, and an endless animation makes `pumpAndSettle`+ // hang for every test that walks through sign-in. The widget test+ // framework disables tickers exactly so that cannot wedge a suite, so+ // honouring it is what lets this screen loop for a real user while staying+ // testable. It is also what stops the clock behind a pushed route.+ final stilled =+ MediaQuery.disableAnimationsOf(context) ||+ !TickerMode.valuesOf(context).enabled;+ if (stilled) {+ _clock+ ..stop()+ ..value = _reducedPhase;+ } else if (!_clock.isAnimating) {+ _clock.repeat();+ }+ }++ /// Where the frame stops for someone who asked for less motion.+ ///+ /// Mid-crossing, *after* the seal: the still frame still shows a grey dot on+ /// one lane and a glowing block on another, so the picture keeps making its+ /// point instead of becoming a diagram of nothing happening. Freezing at 0+ /// would hide the packets entirely, which is the one thing this drawing+ /// exists to show.+ ///+ /// The value is tied to [_laneStagger] and has to be rechecked with it: at a+ /// third-of-a-cycle stagger this frame reads SEALED / RAW / just-landed+ /// across the three lanes, which is the whole story in one picture. Push it+ /// to 0.60 and the second lane is mid-seal rather than plain, so the contrast+ /// the frame is chosen for goes away.+ static const double _reducedPhase = 0.52;++ @override+ void dispose() {+ _clock.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ // Colours are resolved HERE, in build, not inside the painter: the painter+ // is handed plain values so it never reads a theme-dependent getter from a+ // paint callback, which runs outside the element that depends on the theme.+ final palette = _DiagramPalette(+ // `guide`, not `divider`, and the token file draws the line itself: a+ // divider only has to be findable at a seam the eye is already looking+ // at, while a guide is a long thin run the eye has to FOLLOW — which is+ // exactly what these lanes are. It also lands at the same weight in both+ // themes (1.45 light / 1.48 dark, measured with tool/contrast.py), where+ // divider is a step fainter in light (1.14) than dark (1.25) and left+ // the whole diagram looking washed out on the white palette.+ wire: grid.AppPalette.guide,+ nodeFill: grid.AppCard.inset,+ hubFill: grid.AppSurface.accentWash,+ accent: grid.AppPalette.accentOnSurface,+ raw: grid.AppPalette.textFaint,+ ink: grid.AppPalette.textSecondary,+ // ⚠️ NOT `textFaint`. This colour carries "we can't read this" — the+ // privacy claim the whole drawing exists to make — and faint measured+ // 3.33:1 light / 3.18:1 dark against the hub, under the 4.5:1 WCAG 1.4.3+ // asks of body text. `textSecondary` puts it at 6.21 / 6.82. A sentence+ // this load-bearing does not get to be decorative grey.+ faint: grid.AppPalette.textSecondary,+ online: grid.AppPalette.online,+ isDark: grid.AppTheme.isDark,+ );+ final labels = _DiagramLabels(+ nodes: const ['MacBook', 'Server', 'Cloud'],+ // Said the way anyone reads it. The cipher names that used to sit on this+ // screen (Ed25519, ChaCha20-Poly1305) were true and unreadable to almost+ // everyone who saw them; they belong on a security page.+ //+ // "we" is doing real work here and is worth keeping. The headline+ // promises the READER sees everything; this line is about a different+ // subject entirely — us — and without the pronoun the two collapse into+ // one confused claim about who can read what. The card's subhead used to+ // repeat this as "cannot open it" and was cut for that reason: the+ // sentence belongs on the middle of the diagram, pointing at the thing it+ // is about, not four lines below it in prose.+ //+ // Kept short on purpose: at 9.5px this lands ~80px against a 115px budget+ // inside the hub, and the longer "we can't read any of it" spends all but+ // 12px of that — one wider user-chosen font and it ellipsises. A claim+ // that truncates is worse than a shorter claim.+ hub: "we can't read this",+ );++ return RepaintBoundary(+ child: AspectRatio(+ aspectRatio: LoginRelayDiagram.aspectRatio,+ child: AnimatedBuilder(+ animation: _clock,+ builder: (context, _) => CustomPaint(+ painter: _RelayPainter(+ t: _clock.value,+ palette: palette,+ labels: labels,+ ),+ size: Size.infinite,+ ),+ ),+ ),+ );+ }+}++/// Every colour the painter needs, already resolved for the current theme.+class _DiagramPalette {+ const _DiagramPalette({+ required this.wire,+ required this.nodeFill,+ required this.hubFill,+ required this.accent,+ required this.raw,+ required this.ink,+ required this.faint,+ required this.online,+ required this.isDark,+ });++ final Color wire;+ final Color nodeFill;+ final Color hubFill;+ final Color accent;+ final Color raw;+ final Color ink;+ final Color faint;+ final Color online;++ /// Glow has to be tuned per theme rather than scaled from one value: on a+ /// white page it can only ever be a tint before it turns to haze, while on+ /// charcoal it has room to actually emit. One alpha for both either vanishes+ /// in light or blooms in dark.+ ///+ /// The light numbers were raised after measuring rather than after looking:+ /// at the first pass's 0.22/0.55 the halo landed at 1.38:1 and 2.38:1 against+ /// the card, where dark had 2.01 and 4.56 — so the beat the whole diagram is+ /// built around was ~45% fainter on the white palette and read as a flat blue+ /// square. 0.44 now matches dark's ring almost exactly (1.97 vs 2.01).+ ///+ /// The core deliberately does NOT match: 0.78 gives 3.65 against dark's 4.56,+ /// and closing that gap means a nearly opaque accent disc, which stops+ /// reading as light and starts reading as a sticker. White has less headroom+ /// for glow than charcoal does, and pretending otherwise is how a "matched"+ /// pair ends up looking wrong in one theme.+ double get haloAlpha => isDark ? 0.42 : 0.44;+ double get haloCoreAlpha => isDark ? 0.9 : 0.78;+ double get flowAlpha => isDark ? 0.95 : 0.85;++ final bool isDark;+}++class _DiagramLabels {+ const _DiagramLabels({required this.nodes, required this.hub});+ final List<String> nodes;+ final String hub;+}++/// The drawing, in its own 440×140 space; the canvas is scaled to fit so every+/// number below is the one from the layout rather than a fraction to re-derive.+class _RelayPainter extends CustomPainter {+ _RelayPainter({required this.t, required this.palette, required this.labels});++ final double t;+ final _DiagramPalette palette;+ final _DiagramLabels labels;++ static const Size _design = Size(440, 140);++ // Node boxes, hub, and the three lanes between them.+ static const Rect _hub = Rect.fromLTWH(258, 34, 158, 72);+ static const List<Rect> _nodes = [+ Rect.fromLTWH(24, 20, 94, 28),+ Rect.fromLTWH(24, 56, 94, 28),+ Rect.fromLTWH(24, 92, 94, 28),+ ];+ static const List<Rect> _panes = [+ Rect.fromLTWH(270, 46, 64, 14),+ Rect.fromLTWH(340, 46, 64, 14),+ Rect.fromLTWH(270, 64, 64, 14),+ Rect.fromLTWH(340, 64, 64, 14),+ ];++ @override+ void paint(Canvas canvas, Size size) {+ final scale = size.width / _design.width;+ canvas.save();+ canvas.scale(scale);++ final lanes = _lanes();+ _paintWires(canvas, lanes);+ _paintHub(canvas);+ _paintNodes(canvas);+ _paintPackets(canvas, lanes);++ canvas.restore();+ }++ /// The three curves, built once per paint and reused for the wire, the+ /// travelling energy and the packet's position — so all three cannot drift+ /// apart the way three hand-typed copies of the same path would.+ List<Path> _lanes() {+ Path lane(double fromY) {+ final p = Path()..moveTo(118, fromY);+ if (fromY == 70) {+ p.lineTo(258, 70);+ } else {+ p.cubicTo(180, fromY, 200, 70, 258, 70);+ }+ return p;+ }++ return [lane(34), lane(70), lane(106)];+ }++ void _paintWires(Canvas canvas, List<Path> lanes) {+ final wire = Paint()+ ..style = PaintingStyle.stroke+ ..strokeWidth = 1.5+ ..color = palette.wire;+ for (final lane in lanes) {+ canvas.drawPath(lane, wire);+ }++ // Energy running the wire, gated to its own packet so a lane is only lit+ // while something is actually on it.+ for (var i = 0; i < lanes.length; i++) {+ final phase = _phaseFor(i);+ final visible = _flowOpacity(phase);+ if (visible <= 0) continue;++ final metric = lanes[i].computeMetrics().first;+ final head = (phase / _travelEnd).clamp(0.0, 1.0) * metric.length;+ final tail = math.max(0.0, head - 34);+ if (head - tail < 0.5) continue;++ final segment = metric.extractPath(tail, head);+ canvas.drawPath(+ segment,+ Paint()+ ..style = PaintingStyle.stroke+ ..strokeWidth = 2.2+ ..strokeCap = StrokeCap.round+ ..shader = _gradientAlong(+ metric.getTangentForOffset(tail)!.position,+ metric.getTangentForOffset(head)!.position,+ palette.accent,+ palette.flowAlpha * visible,+ ),+ );+ }+ }++ void _paintHub(Canvas canvas) {+ canvas.drawRRect(+ RRect.fromRectAndRadius(_hub, const Radius.circular(10)),+ Paint()..color = palette.hubFill,+ );++ // Four panes — the four terminals the app really runs at once. Each lights+ // when its own packet lands, then settles back; nothing else here moves.+ for (var i = 0; i < _panes.length; i++) {+ final phase = _phaseFor(i);+ final alpha = _paneAlpha(phase);+ canvas.drawRRect(+ RRect.fromRectAndRadius(_panes[i], const Radius.circular(4)),+ Paint()..color = palette.accent.withValues(alpha: alpha),+ );+ }++ // The eye and its caption are laid out as ONE centred group inside the hub+ // rather than at two hand-typed coordinates. Typed positions were wrong+ // twice — first printing the caption left of the hub across the incoming+ // wires, then running it off the right edge with the eye sitting on top of+ // it — because the caption's width is not a number anyone can guess: it+ // changes with the copy, the theme's font and the user's chosen family.+ // Measuring it and centring the pair is the only version that cannot drift.+ const eyeWidth = 17.0;+ const gap = 6.0;+ const padding = 10.0;+ // Bounded by the hub it sits in, not by trust that the string is short:+ // this label is the one piece of prose in the drawing, and prose grows —+ // a longer translation, a wider chosen font, a bigger UI size. Giving the+ // painter a hard ceiling means the worst case is an ellipsis inside the+ // box rather than a sentence printed across the wires outside it.+ final caption = _layOutText(+ labels.hub,+ fontSize: 9.5,+ color: palette.faint,+ maxWidth: _hub.width - eyeWidth - gap - padding * 2,+ );+ final groupWidth = eyeWidth + gap + caption.width;+ final left = _hub.center.dx - groupWidth / 2;+ const centreY = 92.0;++ _paintBlindfold(canvas, Offset(left, centreY));+ caption.paint(+ canvas,+ Offset(left + eyeWidth + gap, centreY - caption.height / 2),+ );+ }++ /// A struck-through eye: the one mark that says "cannot look" without asking+ /// the reader to know a word like *relay* or *zero-knowledge*.+ ///+ /// Drawn from [at], its left edge at that point's x and its centre on its y,+ /// so the caller can place it in a row with the caption beside it.+ void _paintBlindfold(Canvas canvas, Offset at) {+ final stroke = Paint()+ ..style = PaintingStyle.stroke+ // Thinner as well as smaller: at 1.6 the strike-through read as heavy as+ // the hub's own panes, which made a supporting mark compete with the+ // thing it annotates.+ ..strokeWidth = 1.25+ ..strokeCap = StrokeCap.round+ ..strokeJoin = StrokeJoin.round+ ..color = palette.accent;++ final x = at.dx;+ final y = at.dy;+ final eye = Path()+ ..moveTo(x, y)+ ..relativeCubicTo(3, -3.7, 9.5, -3.7, 12.5, 0)+ ..relativeCubicTo(-3, 3.7, -9.5, 3.7, -12.5, 0)+ ..close();+ canvas.drawPath(eye, stroke);+ canvas.drawCircle(Offset(x + 6.25, y), 1.7, stroke);+ canvas.drawLine(Offset(x - 2, y + 5), Offset(x + 14.5, y - 5), stroke);+ }++ void _paintNodes(Canvas canvas) {+ for (var i = 0; i < _nodes.length; i++) {+ final r = _nodes[i];+ canvas.drawRRect(+ RRect.fromRectAndRadius(r, const Radius.circular(8)),+ Paint()..color = palette.nodeFill,+ );+ // The "this machine is up" dot. It breathes on the shared clock and+ // lands at full strength when the drawing comes to rest — a dot held at+ // half alpha reads as *offline*, which is the opposite of what it means.+ final breath = 0.5 + 0.5 * math.sin(t * 2 * math.pi);+ canvas.drawCircle(+ Offset(r.left + 14, r.center.dy),+ 3,+ Paint()..color = palette.online.withValues(alpha: 0.55 + 0.45 * breath),+ );+ _paintText(+ canvas,+ labels.nodes[i],+ Offset(r.left + 26, r.center.dy),+ fontSize: 10.5,+ color: palette.ink,+ );+ }+ }++ /// Where a packet is at phase 1.0 — it arrives before the cycle ends so the+ /// pane it lit has time to settle before the next one leaves.+ static const double _travelEnd = 0.72;++ /// The stretch of the crossing where a packet turns from plaintext into a+ /// sealed block. Centred on the hub's left edge, so the change happens at+ /// the boundary it is about.+ static const double _sealStart = 0.26;+ static const double _sealEnd = 0.38;++ void _paintPackets(Canvas canvas, List<Path> lanes) {+ for (var i = 0; i < lanes.length; i++) {+ final phase = _phaseFor(i);+ if (phase <= 0 || phase >= 1) continue;++ final travel = (phase / _travelEnd).clamp(0.0, 1.0);+ final metric = lanes[i].computeMetrics().first;+ final pos = metric.getTangentForOffset(travel * metric.length)!.position;++ final sealed = ((phase - _sealStart) / (_sealEnd - _sealStart)).clamp(+ 0.0,+ 1.0,+ );+ final fade = _packetOpacity(phase);+ if (fade <= 0) continue;++ // The halo: ignites at the seal, overshoots, then rides along. This is+ // the beat the whole picture is built around — encryption drawn as a+ // light source rather than written as a word.+ if (sealed > 0) {+ final overshoot = sealed < 1 ? 1 + 0.5 * math.sin(sealed * math.pi) : 1;+ final r = 13.0 * overshoot;+ canvas.drawCircle(+ pos,+ r,+ Paint()+ ..shader = RadialGradient(+ colors: [+ palette.accent.withValues(+ alpha: palette.haloCoreAlpha * sealed * fade,+ ),+ palette.accent.withValues(+ alpha: palette.haloAlpha * sealed * fade,+ ),+ palette.accent.withValues(alpha: 0),+ ],+ stops: const [0, 0.45, 1],+ ).createShader(Rect.fromCircle(center: pos, radius: r)),+ );+ }++ if (sealed < 1) {+ // Plaintext: a bare, unremarkable grey dot.+ canvas.drawCircle(+ pos,+ 4,+ Paint()..color = palette.raw.withValues(alpha: (1 - sealed) * fade),+ );+ }+ if (sealed > 0) {+ // Ciphertext: a hard-edged block, rotating into place as it forms.+ canvas.save();+ canvas.translate(pos.dx, pos.dy);+ canvas.rotate((1 - sealed) * -math.pi / 4);+ final s = 4.5 * (0.6 + 0.4 * sealed);+ canvas.drawRRect(+ RRect.fromRectAndRadius(+ Rect.fromCenter(center: Offset.zero, width: s * 2, height: s * 2),+ const Radius.circular(1.5),+ ),+ Paint()..color = palette.accent.withValues(alpha: sealed * fade),+ );+ canvas.restore();+ }+ }+ }++ /// This lane's position in the cycle, wrapped into `[0, 1)`.+ double _phaseFor(int lane) => (t - lane * _laneStagger) % 1.0;++ /// Packets fade in as they leave and out once they have landed, so nothing+ /// pops at the seam of the loop.+ double _packetOpacity(double phase) {+ if (phase < 0.06) return phase / 0.06;+ if (phase < _travelEnd) return 1;+ if (phase < 0.88) return 1 - (phase - _travelEnd) / (0.88 - _travelEnd);+ return 0;+ }++ double _flowOpacity(double phase) {+ if (phase < 0.04) return 0;+ if (phase < 0.12) return (phase - 0.04) / 0.08;+ if (phase < 0.66) return 1;+ if (phase < 0.78) return 1 - (phase - 0.66) / 0.12;+ return 0;+ }++ /// A pane rests low, spikes as its packet lands, then settles a step above+ /// where it started — the window keeps what it received.+ double _paneAlpha(double phase) {+ const rest = 0.16;+ const peak = 0.72;+ const settled = 0.30;+ if (phase < 0.66) return rest;+ if (phase < 0.74) {+ return rest + (peak - rest) * ((phase - 0.66) / 0.08);+ }+ if (phase < 1) {+ return peak + (settled - peak) * ((phase - 0.74) / 0.26);+ }+ return rest;+ }++ /// Lay a label out once, so a caller can both measure and place it.+ ///+ /// Anything positioned relative to text has to know its width, and a width+ /// guessed from a character count is wrong the moment the copy, the theme+ /// font, or the user's chosen family changes.+ TextPainter _layOutText(+ String text, {+ required double fontSize,+ required Color color,+ double? maxWidth,+ }) {+ return TextPainter(+ text: TextSpan(+ text: text,+ style: TextStyle(+ fontFamily: grid.AppFont.sans,+ fontFamilyFallback: grid.AppFont.sansFallback,+ fontSize: fontSize,+ color: color,+ letterSpacing: grid.AppFont.trackingFor(fontSize),+ height: 1.0,+ ),+ ),+ textDirection: TextDirection.ltr,+ // The drawing is scaled as a unit, so text inside it must not also take+ // the platform's scaler — that would grow the labels past the boxes they+ // sit in while the boxes stayed put.+ textScaler: TextScaler.noScaling,+ maxLines: 1,+ ellipsis: '…',+ )..layout(maxWidth: maxWidth ?? double.infinity);+ }++ void _paintText(+ Canvas canvas,+ String text,+ Offset at, {+ required double fontSize,+ required Color color,+ }) {+ final painter = _layOutText(text, fontSize: fontSize, color: color);+ painter.paint(canvas, Offset(at.dx, at.dy - painter.height / 2));+ }++ @override+ bool shouldRepaint(covariant _RelayPainter old) =>+ old.t != t ||+ old.palette.accent != palette.accent ||+ old.palette.isDark != palette.isDark;+}++/// A left-to-right gradient between two points on the canvas, used to give the+/// travelling energy a lit head and a dark tail.+Shader _gradientAlong(Offset from, Offset to, Color color, double alpha) {+ return LinearGradient(+ colors: [+ color.withValues(alpha: 0),+ color.withValues(alpha: alpha),+ ],+ ).createShader(Rect.fromPoints(from, to));+}++/// The atmosphere behind the sign-in card: two very low-alpha blobs drifting+/// on a multiple of the diagram's own clock.+///+/// It is what makes the window read as *lit* rather than printed, and it is+/// the piece that carries the design into the corners of a 1280×800 window+/// that the card itself leaves empty. Alphas are tuned per theme for the same+/// reason the packet halo is: on a near-white panel this can only ever be a+/// tint before it turns to haze, while charcoal has room for it to glow.+///+/// The period is an exact multiple of [_period] so the two never drift into a+/// beat against each other — the whole screen stays one instrument.+class LoginAurora extends StatefulWidget {+ const LoginAurora({super.key});++ @override+ State<LoginAurora> createState() => _LoginAuroraState();+}++class _LoginAuroraState extends State<LoginAurora>+ with SingleTickerProviderStateMixin {+ late final AnimationController _drift = AnimationController(+ vsync: this,+ duration: _period * 4,+ );++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final stilled =+ MediaQuery.disableAnimationsOf(context) ||+ !TickerMode.valuesOf(context).enabled;+ if (stilled) {+ _drift+ ..stop()+ ..value = 0.5;+ } else if (!_drift.isAnimating) {+ _drift.repeat();+ }+ }++ @override+ void dispose() {+ _drift.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final dark = grid.AppTheme.isDark;+ final a = grid.AppPalette.accentOnSurface.withValues(+ alpha: dark ? 0.10 : 0.055,+ );+ final b = grid.AppPalette.teal.withValues(alpha: dark ? 0.07 : 0.045);++ return IgnorePointer(+ child: RepaintBoundary(+ child: AnimatedBuilder(+ animation: _drift,+ builder: (context, _) => CustomPaint(+ painter: _AuroraPainter(t: _drift.value, a: a, b: b),+ size: Size.infinite,+ ),+ ),+ ),+ );+ }+}++class _AuroraPainter extends CustomPainter {+ _AuroraPainter({required this.t, required this.a, required this.b});++ final double t;+ final Color a;+ final Color b;++ @override+ void paint(Canvas canvas, Size size) {+ // A full sine over the cycle, so the loop closes on itself with no jump.+ final phase = math.sin(t * 2 * math.pi);+ _blob(+ canvas,+ Offset(+ size.width * (0.28 + 0.04 * phase),+ size.height * (0.30 + 0.05 * phase),+ ),+ size.shortestSide * (0.62 + 0.05 * phase),+ a,+ );+ _blob(+ canvas,+ Offset(+ size.width * (0.74 - 0.04 * phase),+ size.height * (0.72 - 0.05 * phase),+ ),+ size.shortestSide * (0.56 - 0.05 * phase),+ b,+ );+ }++ /// A soft radial pool. Drawn as a gradient rather than a blurred circle:+ /// `MaskFilter.blur` at this radius is a real per-frame cost on a surface+ /// that covers the whole window, and a gradient gets the same falloff free.+ void _blob(Canvas canvas, Offset centre, double radius, Color color) {+ canvas.drawCircle(+ centre,+ radius,+ Paint()+ ..shader = RadialGradient(+ colors: [color, color.withValues(alpha: 0)],+ stops: const [0, 1],+ ).createShader(Rect.fromCircle(center: centre, radius: radius)),+ );+ }++ @override+ bool shouldRepaint(covariant _AuroraPainter old) =>+ old.t != t || old.a != a || old.b != b;+}diff --git a/mobile/lib/widgets/pane_header_actions.dart b/mobile/lib/widgets/pane_header_actions.dartnew file mode 100644index 000000000..8e3f18762--- /dev/null+++ b/mobile/lib/widgets/pane_header_actions.dart@@ -0,0 +1,155 @@+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../theme/app_theme.dart';++/// Direct pane controls, in a stable order even when an action is unavailable.+class PaneHeaderActions extends StatelessWidget {+ const PaneHeaderActions({+ super.key,+ required this.name,+ required this.zoomed,+ this.onZoom,+ this.onDelete,+ this.onClose,+ this.onToggleComposer,+ this.composerVisible = false,+ this.details,+ });++ final String name;+ final bool zoomed, composerVisible;+ final VoidCallback? onZoom, onDelete, onClose, onToggleComposer;++ /// Folder, branch and machine share the controls' space while idle. Both+ /// layers keep their size so hovering never changes the title's width.+ final Widget? details;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);++ Widget action(String tooltip, IconData icon, VoidCallback? callback) =>+ IconButton(+ tooltip: tooltip,+ onPressed: callback,+ icon: Icon(icon, size: 16),+ style: ButtonStyle(+ fixedSize: const WidgetStatePropertyAll(Size(28, 28)),+ minimumSize: const WidgetStatePropertyAll(Size(28, 28)),+ padding: const WidgetStatePropertyAll(EdgeInsets.zero),+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ visualDensity: VisualDensity.standard,+ shape: WidgetStatePropertyAll(+ RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),+ ),+ foregroundColor: WidgetStateProperty.resolveWith((states) {+ if (states.contains(WidgetState.disabled)) {+ return grid.AppPalette.textFaint;+ }+ if (states.contains(WidgetState.hovered) ||+ states.contains(WidgetState.focused)) {+ return AppColors.text;+ }+ return AppColors.mutedStrong.withValues(alpha: .8);+ }),+ overlayColor: WidgetStatePropertyAll(grid.AppSurface.hoverFill),+ ),+ );++ final visible = _PaneHeaderVisibility.of(context);+ final controls = IgnorePointer(+ ignoring: !visible,+ child: AnimatedOpacity(+ opacity: visible ? 1 : 0,+ alwaysIncludeSemantics: true,+ duration: MediaQuery.disableAnimationsOf(context)+ ? Duration.zero+ : const Duration(milliseconds: 100),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (onToggleComposer != null) ...[+ action(+ composerVisible+ ? 'Hide message composer'+ : 'Show message composer',+ LucideIcons.keyboard,+ onToggleComposer,+ ),+ const SizedBox(width: 2),+ ],+ action(+ zoomed ? 'Restore panes' : 'Zoom $name',+ zoomed ? LucideIcons.minimize : LucideIcons.maximize,+ onZoom,+ ),+ const SizedBox(width: 2),+ action('Delete Harness', LucideIcons.trash2, onDelete),+ const SizedBox(width: 2),+ action('Close pane', LucideIcons.x, onClose),+ ],+ ),+ ),+ );+ if (details == null) return controls;+ return Stack(+ alignment: Alignment.centerRight,+ children: [+ IgnorePointer(+ ignoring: visible,+ child: AnimatedOpacity(+ key: const ValueKey('pane-header-details'),+ opacity: visible ? 0 : 1,+ duration: MediaQuery.disableAnimationsOf(context)+ ? Duration.zero+ : const Duration(milliseconds: 100),+ child: ExcludeSemantics(excluding: visible, child: details!),+ ),+ ),+ controls,+ ],+ );+ }+}++/// Only header controls depend on this hover state, so the terminal and title+/// are retained as the pointer crosses the bar. Keyboard focus reveals them too.+class PaneHeaderHover extends StatefulWidget {+ const PaneHeaderHover({super.key, required this.child});+ final Widget child;+ @override+ State<PaneHeaderHover> createState() => _PaneHeaderHoverState();+}++class _PaneHeaderHoverState extends State<PaneHeaderHover> {+ bool _hovered = false, _focused = false;+ @override+ Widget build(BuildContext context) => MouseRegion(+ onEnter: (_) => setState(() => _hovered = true),+ onExit: (_) => setState(() => _hovered = false),+ child: Focus(+ canRequestFocus: false,+ includeSemantics: false,+ onFocusChange: (value) => setState(() => _focused = value),+ child: _PaneHeaderVisibility(+ visible: _hovered || _focused,+ child: widget.child,+ ),+ ),+ );+}++class _PaneHeaderVisibility extends InheritedWidget {+ const _PaneHeaderVisibility({required this.visible, required super.child});+ final bool visible;+ static bool of(BuildContext context) =>+ context+ .dependOnInheritedWidgetOfExactType<_PaneHeaderVisibility>()+ ?.visible ??+ true;+ @override+ bool updateShouldNotify(_PaneHeaderVisibility oldWidget) =>+ visible != oldWidget.visible;+}diff --git a/mobile/lib/widgets/remote_folder_picker.dart b/mobile/lib/widgets/remote_folder_picker.dartnew file mode 100644index 000000000..3512f8a8e--- /dev/null+++ b/mobile/lib/widgets/remote_folder_picker.dart@@ -0,0 +1,560 @@+import 'dart:math' as math;++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:path/path.dart' as p;++import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import '../theme/app_theme.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/skeleton.dart';++/// Browses the selected machine through fs_list_dir. The native folder chooser+/// would return a path on this computer instead of the agent's machine.+Future<String?> showRemoteFolderPicker(+ BuildContext context, {+ required AppNotifier notifier,+ required String machineId,+ String? initialPath,+}) => showAppDialog<String>(+ context: context,+ builder: (context) => _RemoteFolderPickerDialog(+ notifier: notifier,+ machineId: machineId,+ initialPath: initialPath,+ ),+);++class _RemoteFolderPickerDialog extends StatefulWidget {+ const _RemoteFolderPickerDialog({+ required this.notifier,+ required this.machineId,+ this.initialPath,+ });++ final AppNotifier notifier;+ final String machineId;+ final String? initialPath;++ @override+ State<_RemoteFolderPickerDialog> createState() =>+ _RemoteFolderPickerDialogState();+}++class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {+ final _location = TextEditingController();+ final _locationFocus = FocusNode(debugLabel: 'Remote folder path');+ final _foldersFocus = FocusNode(debugLabel: 'Remote folders');+ final _scroll = ScrollController();+ String? _path, _requestedPath, _error;+ List<String> _entries = [];+ bool _loading = true, _truncated = false;+ int _request = 0, _edit = 0, _selected = -1;+ double _rowHeight = 36;++ bool get _canSelect =>+ !_loading &&+ _error == null &&+ _path != null &&+ _location.text.trim() == _path;++ // The remote machine may use different path separators than this desktop.+ p.Context get _paths => p.Context(+ style:+ (_path?.startsWith(r'\\') ?? false) ||+ RegExp(r'^[A-Za-z]:[/\\]').hasMatch(_path ?? '')+ ? p.Style.windows+ : p.Style.posix,+ );++ String? get _parentPath {+ if (_path == null) return null;+ final parent = _paths.dirname(_path!);+ return parent == _path ? null : parent;+ }++ @override+ void initState() {+ super.initState();+ _load(widget.initialPath);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _locationFocus.requestFocus();+ });+ }++ @override+ void dispose() {+ _location.dispose();+ _locationFocus.dispose();+ _foldersFocus.dispose();+ _scroll.dispose();+ super.dispose();+ }++ Future<void> _load(String? path, {String? highlight}) async {+ if (_loading && _request > 0 && path == _requestedPath) return;+ final request = ++_request;+ final edit = _edit;+ setState(() {+ _loading = true;+ _error = null;+ _requestedPath = path;+ if (_location.text != (path ?? '')) {+ _location.text = path ?? '';+ _location.selection = TextSelection.collapsed(+ offset: _location.text.length,+ );+ }+ });+ Map<String, dynamic> result;+ try {+ result = await widget.notifier.listRemoteFolder(widget.machineId, path);+ } catch (_) {+ result = {'error': 'UNREACHABLE'};+ }+ if (!mounted || request != _request) return;+ final resolved = result['path'];+ final error = result['error'];+ if (error != null || resolved is! String || resolved.isEmpty) {+ setState(() {+ _loading = false;+ _error = edit != _edit+ ? null+ : error is String+ ? error+ : 'UNAVAILABLE';+ });+ return;+ }+ setState(() {+ _loading = false;+ _path = resolved;+ _entries = [+ for (final entry in result['entries'] as List? ?? const [])+ if (entry is Map &&+ entry['isDir'] != false &&+ entry['name'] is String &&+ (entry['name'] as String).isNotEmpty)+ entry['name'] as String,+ ];+ _truncated = result['truncated'] == true;+ _selected = _entries.isEmpty+ ? -1+ : math.max(0, _entries.indexOf(highlight ?? ''));+ // A reply may canonicalize a path, but must not replace a newer draft or+ // disturb a selection/caret when the field already contains that path.+ if (edit == _edit && _location.text != resolved) {+ _location.value = TextEditingValue(+ text: resolved,+ selection: TextSelection(+ baseOffset: 0,+ extentOffset: resolved.length,+ ),+ );+ }+ });+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && request == _request) _revealSelection();+ });+ }++ void _openPath() {+ final path = _location.text.trim();+ if (path.isEmpty || (_loading && path == _requestedPath)) return;+ _load(path);+ }++ void _up() {+ if (_loading) return;+ final parent = _parentPath;+ if (parent != null) _load(parent, highlight: _paths.basename(_path!));+ }++ void _select() {+ if (_canSelect) Navigator.of(context).pop(_path);+ }++ void _openSelected() {+ if (!_loading && _selected >= 0 && _selected < _entries.length) {+ _load(_paths.join(_path!, _entries[_selected]));+ }+ }++ void _revealSelection() {+ if (!_scroll.hasClients || _selected < 0) return;+ final top = _selected * _rowHeight;+ final bottom = top + _rowHeight;+ final position = _scroll.position;+ final target = top < position.pixels+ ? top+ : bottom > position.pixels + position.viewportDimension+ ? bottom - position.viewportDimension+ : position.pixels;+ _scroll.jumpTo(target.clamp(0.0, position.maxScrollExtent));+ }++ KeyEventResult _folderKey(FocusNode node, KeyEvent event) {+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {+ return KeyEventResult.ignored;+ }+ final keyboard = HardwareKeyboard.instance;+ if (keyboard.isControlPressed ||+ keyboard.isMetaPressed ||+ keyboard.isAltPressed ||+ keyboard.isShiftPressed) {+ return KeyEventResult.ignored;+ }+ final key = event.logicalKey;+ if (key == LogicalKeyboardKey.arrowLeft) {+ _up();+ } else if (key == LogicalKeyboardKey.enter ||+ key == LogicalKeyboardKey.numpadEnter ||+ key == LogicalKeyboardKey.arrowRight) {+ _openSelected();+ } else if (key == LogicalKeyboardKey.arrowDown ||+ key == LogicalKeyboardKey.arrowUp ||+ key == LogicalKeyboardKey.home ||+ key == LogicalKeyboardKey.end) {+ if (!_loading && _entries.isNotEmpty) {+ setState(() {+ _selected = switch (key) {+ LogicalKeyboardKey.home => 0,+ LogicalKeyboardKey.end => _entries.length - 1,+ LogicalKeyboardKey.arrowUp => (_selected - 1).clamp(+ 0,+ _entries.length - 1,+ ),+ _ => (_selected + 1).clamp(0, _entries.length - 1),+ };+ });+ _revealSelection();+ }+ } else {+ return KeyEventResult.ignored;+ }+ return KeyEventResult.handled;+ }++ String _errorMessage(String code) => switch (code) {+ 'FORBIDDEN' =>+ 'Choose a folder inside your home directory on this machine.',+ 'PERMISSION_DENIED' => 'You don’t have permission to open this folder.',+ 'NOT_A_DIRECTORY' => 'That path is not a folder.',+ 'NOT_FOUND' =>+ 'This folder could not be found. Check the path and try again.',+ 'INVALID_PATH' => 'Enter a full folder path on this machine.',+ 'UNREACHABLE' =>+ 'Couldn’t reach this machine. Check its connection and retry.',+ _ => 'Couldn’t open this folder. Try again.',+ };++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final scale = MediaQuery.textScalerOf(context);+ _rowHeight = math.max(36, scale.scale(14) * 1.35 + 16);+ final listHeight =+ (MediaQuery.sizeOf(context).height - 320 - scale.scale(50)).clamp(+ 120.0,+ 280.0,+ );+ final machine = widget.notifier+ .stateOf(widget.machineId)+ ?.machine+ .displayName;+ final mac = Theme.of(context).platform == TargetPlatform.macOS;+ final actionStyle = ButtonStyle(+ minimumSize: WidgetStatePropertyAll(+ Size(+ 0,+ math.max(+ grid.AppControl.heightScaled,+ scale.scale(grid.AppControl.fontSize) * 1.25 + 16,+ ),+ ),+ ),+ );+ return IconButtonTheme(+ data: IconButtonThemeData(+ style: ButtonStyle(+ minimumSize: const WidgetStatePropertyAll(Size(32, 32)),+ padding: const WidgetStatePropertyAll(EdgeInsets.all(6)),+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ shape: WidgetStatePropertyAll(+ RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(grid.AppControl.radius),+ ),+ ),+ overlayColor: WidgetStatePropertyAll(grid.AppSurface.hoverFill),+ foregroundColor: WidgetStateProperty.resolveWith(+ (states) => states.contains(WidgetState.disabled)+ ? AppColors.muted+ : states.contains(WidgetState.hovered) ||+ states.contains(WidgetState.focused)+ ? AppColors.text+ : AppColors.textSoft,+ ),+ ),+ ),+ child: CallbackShortcuts(+ bindings: {+ SingleActivator(+ LogicalKeyboardKey.enter,+ meta: mac,+ control: !mac,+ includeRepeats: false,+ ): _select,+ const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): _up,+ },+ child: AlertDialog(+ title: const Text('Choose a folder'),+ scrollable: true,+ content: SizedBox(+ width: 520,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ 'On ${machine ?? 'the remote machine'}',+ style: Theme.of(context).textTheme.bodySmall,+ ),+ const SizedBox(height: 12),+ Focus(+ onKeyEvent: (node, event) {+ if (event is KeyDownEvent &&+ event.logicalKey == LogicalKeyboardKey.arrowDown &&+ !HardwareKeyboard.instance.isAltPressed &&+ !HardwareKeyboard.instance.isControlPressed &&+ !HardwareKeyboard.instance.isMetaPressed &&+ !HardwareKeyboard.instance.isShiftPressed &&+ _location.value.composing.isCollapsed &&+ !_loading &&+ _entries.isNotEmpty) {+ _foldersFocus.requestFocus();+ _revealSelection();+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ },+ child: TextField(+ key: const Key('remote-folder-path'),+ controller: _location,+ focusNode: _locationFocus,+ autofocus: true,+ style: grid.kFieldTextStyle,+ decoration: InputDecoration(+ labelText: 'Folder path',+ hintText: 'Enter a full folder path…',+ suffixIcon: IconButton(+ tooltip: 'Open path',+ onPressed:+ _location.text.trim().isEmpty ||+ (_loading &&+ _location.text.trim() == _requestedPath)+ ? null+ : _openPath,+ icon: const Icon(Icons.arrow_forward, size: 18),+ ),+ ),+ onChanged: (_) => setState(() {+ _edit++;+ _error = null;+ }),+ onEditingComplete: () {},+ onSubmitted: (_) => _openPath(),+ ),+ ),+ const SizedBox(height: 8),+ Row(+ children: [+ Expanded(+ child: Text(+ _path != null && _location.text.trim() != _path+ ? 'Showing $_path'+ : 'Folders',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: Theme.of(context).textTheme.labelMedium,+ ),+ ),+ IconButton(+ key: const Key('remote-folder-home'),+ tooltip: 'Home folder on this machine',+ onPressed: () => _load(null),+ icon: const Icon(Icons.home_outlined, size: 18),+ ),+ IconButton(+ tooltip: mac+ ? 'Up one folder (⌥↑)'+ : 'Up one folder (Alt+↑)',+ onPressed: _loading || _parentPath == null ? null : _up,+ icon: const Icon(Icons.arrow_upward, size: 18),+ ),+ ],+ ),+ Focus(+ focusNode: _foldersFocus,+ onKeyEvent: _folderKey,+ onFocusChange: (_) => setState(() {}),+ child: Container(+ key: const Key('remote-folder-list'),+ height: listHeight,+ decoration: BoxDecoration(+ color: AppColors.background,+ border: Border.all(+ color: _foldersFocus.hasFocus+ ? AppColors.accent+ : AppColors.border,+ ),+ borderRadius: BorderRadius.circular(+ grid.AppCard.insetRadius,+ ),+ ),+ clipBehavior: Clip.antiAlias,+ child: _loading+ ? const _FolderRowsSkeleton()+ : _entries.isEmpty+ ? Center(+ child: Padding(+ padding: const EdgeInsets.all(16),+ child: Text(+ _path == null+ ? 'Enter a path or open your home folder.'+ : 'No subfolders here.',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodySmall,+ ),+ ),+ )+ : ListView.builder(+ controller: _scroll,+ itemExtent: _rowHeight,+ itemCount: _entries.length,+ itemBuilder: (context, index) => Semantics(+ selected: index == _selected,+ child: Material(+ color:+ index == _selected && _foldersFocus.hasFocus+ ? AppColors.selected+ : Colors.transparent,+ child: InkWell(+ canRequestFocus: false,+ onTap: () {+ _foldersFocus.requestFocus();+ setState(() => _selected = index);+ _openSelected();+ },+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 12,+ ),+ child: Row(+ children: [+ Icon(+ Icons.folder_outlined,+ size: 18,+ color: AppColors.mutedStrong,+ ),+ const SizedBox(width: 10),+ Expanded(+ child: Text(+ _entries[index],+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ Icon(+ Icons.chevron_right,+ size: 16,+ color: AppColors.mutedStrong,+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ if (_error != null) ...[+ const SizedBox(height: 8),+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Expanded(+ child: Semantics(+ liveRegion: true,+ child: Text(+ _errorMessage(_error!),+ style: Theme.of(context).textTheme.bodySmall+ ?.copyWith(color: AppColors.danger),+ ),+ ),+ ),+ const SizedBox(width: 8),+ TextButton(+ onPressed: () => _load(_requestedPath),+ child: const Text('Retry'),+ ),+ ],+ ),+ ] else if (_truncated && !_loading) ...[+ const SizedBox(height: 8),+ Text(+ 'More folders are available. Enter their full path to open them.',+ style: Theme.of(context).textTheme.bodySmall,+ ),+ ],+ ],+ ),+ ),+ actions: [+ TextButton(+ style: actionStyle,+ onPressed: () => Navigator.of(context).pop(),+ child: const Text('Cancel'),+ ),+ Tooltip(+ message: mac+ ? 'Select this folder (⌘↩)'+ : 'Select this folder (Ctrl+Enter)',+ child: FilledButton(+ style: actionStyle,+ onPressed: _canSelect ? _select : null,+ child: const Text('Select this folder'),+ ),+ ),+ ],+ ),+ ),+ );+ }+}++class _FolderRowsSkeleton extends StatelessWidget {+ const _FolderRowsSkeleton();++ @override+ Widget build(BuildContext context) => SkeletonList(+ rows: 5,+ semanticsLabel: 'Loading folders',+ itemBuilder: (context, i) => Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ child: Row(+ children: [+ const Skeleton(width: 18, height: 18, radius: 3),+ const SizedBox(width: 10),+ Expanded(+ child: SkeletonText(+ style: Theme.of(context).textTheme.bodyMedium!,+ widthFactor: const [0.42, 0.28, 0.56, 0.34, 0.48][i],+ ),+ ),+ ],+ ),+ ),+ );+}diff --git a/mobile/lib/widgets/rename_agent_dialog.dart b/mobile/lib/widgets/rename_agent_dialog.dartnew file mode 100644index 000000000..4ac8bb194--- /dev/null+++ b/mobile/lib/widgets/rename_agent_dialog.dart@@ -0,0 +1,127 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';++/// The one "Edit name" dialog, opened from every place a name is shown.+///+/// Pulled out of the rail so the pane header could use it too: two copies would+/// have been two sets of error handling for one rename, and the second is the+/// one that quietly stops matching.+///+/// Keyboard-complete on purpose — autofocus, Enter submits, Escape closes —+/// because the way in is a double click but the way through should never need+/// the mouse again.+Future<void> showAgentRenameDialog(+ BuildContext context,+ AppNotifier notifier,+ String machineId,+ String agentId,+ String currentName,+) => showAppDialog<void>(+ context: context,+ builder: (_) => _RenameAgentDialog(+ notifier: notifier,+ machineId: machineId,+ agentId: agentId,+ currentName: currentName,+ ),+);++/// ⚠️ A widget that OWNS its controller, not a `StatefulBuilder` over one made+/// beside `showDialog`.+///+/// That is what this file used to be, and it crashed the app on Escape: the+/// controller was disposed the moment `showDialog`'s future resolved, which is+/// when the route STARTS animating out — the dialog is still on screen and+/// still rebuilding for the length of that transition, and the first rebuild+/// after the dispose threw "A TextEditingController was used after being+/// disposed" and took the window to a red screen.+///+/// A `State` disposes on unmount instead, which happens after the transition+/// has finished and the route is gone, so there is nothing left to rebuild.+class _RenameAgentDialog extends StatefulWidget {+ const _RenameAgentDialog({+ required this.notifier,+ required this.machineId,+ required this.agentId,+ required this.currentName,+ });++ final AppNotifier notifier;+ final String machineId;+ final String agentId;+ final String currentName;++ @override+ State<_RenameAgentDialog> createState() => _RenameAgentDialogState();+}++class _RenameAgentDialogState extends State<_RenameAgentDialog> {+ late final _controller = TextEditingController(text: widget.currentName);++ /// The CLI's refusal, shown under the field. Null until one arrives.+ String? _error;++ @override+ void dispose() {+ _controller.dispose();+ super.dispose();+ }++ Future<void> _submit() async {+ final result = await widget.notifier.renameAgent(+ widget.machineId,+ widget.agentId,+ _controller.text,+ );+ if (!mounted) return;+ if (result == null) {+ Navigator.of(context).pop();+ return;+ }+ setState(() => _error = result);+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return AlertDialog(+ title: const Text('Rename Harness'),+ content: SizedBox(+ width: 360,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ TextField(+ controller: _controller,+ autofocus: true,+ style: grid.kFieldTextStyle,+ onSubmitted: (_) => _submit(),+ ),+ if (_error case final error?) ...[+ const SizedBox(height: 10),+ Text(+ error,+ style: TextStyle(+ color: grid.AppPalette.dangerFill,+ fontFamily: grid.AppFont.sans,+ fontSize: 11.2,+ ),+ ),+ ],+ ],+ ),+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.of(context).pop(),+ child: const Text('Cancel'),+ ),+ FilledButton(onPressed: _submit, child: const Text('Save')),+ ],+ );+ }+}diff --git a/mobile/lib/widgets/shortcuts_sheet.dart b/mobile/lib/widgets/shortcuts_sheet.dartnew file mode 100644index 000000000..3ea5b1c1f--- /dev/null+++ b/mobile/lib/widgets/shortcuts_sheet.dart@@ -0,0 +1,93 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../shortcuts/shortcuts_list.dart';+import '../shortcuts/keymap.dart';+import '../shortcuts/keymap_settings.dart';++/// The ⌘/ sheet — [ShortcutsList] in a dialog.+///+/// The list itself is shared with Settings ▸ Keyboard shortcuts, so the two can+/// never disagree about what a key does.+Future<void> showShortcutsSheet(BuildContext context) {+ return showAppDialog<void>(+ context: context,+ builder: (context) => const _ShortcutsSheet(),+ );+}++class _ShortcutsSheet extends StatefulWidget {+ const _ShortcutsSheet();++ @override+ State<_ShortcutsSheet> createState() => _ShortcutsSheetState();+}++class _ShortcutsSheetState extends State<_ShortcutsSheet> {+ KeymapContext _contextKind = KeymapContext.workspace;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Dialog(+ // No backgroundColor, no shape: `dialogTheme` supplies both, at+ // AppGlass.surfaceFill and AppCard.radius (12). The rim this used to+ // carry is gone with them — §1 allows exactly one border in the app and+ // it belongs to the menu panel, not to a dialog.+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 420),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(18, 17, 18, 4),+ child: Text(+ 'Keyboard shortcuts',+ style: TextStyle(+ color: grid.AppPalette.textPrimary,+ fontSize: 15,+ fontWeight: grid.AppFont.semibold,+ ),+ ),+ ),+ Flexible(+ child: SingleChildScrollView(+ padding: const EdgeInsets.fromLTRB(18, 8, 18, 16),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ KeymapSettings(+ contextKind: _contextKind,+ onContextChanged: (value) =>+ setState(() => _contextKind = value),+ ),+ ShortcutsList(contextKind: _contextKind),+ ],+ ),+ ),+ ),+ Container(+ width: double.infinity,+ padding: const EdgeInsets.fromLTRB(18, 12, 18, 12),+ decoration: BoxDecoration(+ border: Border(top: BorderSide(color: grid.AppGlass.hair)),+ ),+ child: Align(+ alignment: Alignment.centerRight,+ child: TextButton(+ onPressed: () => Navigator.of(context).pop(),+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ ),+ child: const Text('Close'),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/lib/widgets/swarm_icon.dart b/mobile/lib/widgets/swarm_icon.dartnew file mode 100644index 000000000..9028036ec--- /dev/null+++ b/mobile/lib/widgets/swarm_icon.dart@@ -0,0 +1,14 @@+import 'package:flutter/cupertino.dart';++/// Four agents sharing one workspace. Native menus use the corresponding+/// `square.grid.2x2` symbol in SwarmTitlebar.swift.+class SwarmIcon extends StatelessWidget {+ const SwarmIcon({super.key, this.size = 19, this.color});++ final double size;+ final Color? color;++ @override+ Widget build(BuildContext context) =>+ Icon(CupertinoIcons.square_grid_2x2, size: size, color: color);+}diff --git a/mobile/lib/widgets/terminal_composer.dart b/mobile/lib/widgets/terminal_composer.dartnew file mode 100644index 000000000..ff075eefe--- /dev/null+++ b/mobile/lib/widgets/terminal_composer.dart@@ -0,0 +1,360 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../theme/app_theme.dart';+import '../terminal/terminal_font_store.dart';+import '../terminal/terminal_session.dart';++/// A textbox under a terminal that sends its whole contents at once.+///+/// It exists for remote machines, where typing straight into the pane charges a network round trip+/// per keystroke. Here the typing is local and free; only the finished message crosses the wire —+/// as one batch, followed by Enter.+///+/// Focusing the terminal itself is untouched: that path stays per-keystroke, which is what anyone+/// driving a full-screen TUI needs.+class TerminalComposer extends StatefulWidget {+ const TerminalComposer({+ super.key,+ required this.session,+ required this.focusNode,+ this.inputEnabled = true,+ });++ final TerminalSession session;+ final FocusNode focusNode;+ final bool inputEnabled;++ @override+ State<TerminalComposer> createState() => _TerminalComposerState();+}++class _TerminalComposerState extends State<TerminalComposer> {+ final TextEditingController _controller = TextEditingController();++ @override+ void initState() {+ super.initState();+ widget.session.addListener(_onSessionChanged);+ widget.focusNode.addListener(_onFocusChanged);+ terminalFontStore.addListener(_onFontChanged);+ }++ @override+ void didUpdateWidget(TerminalComposer oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (!identical(oldWidget.session, widget.session)) {+ oldWidget.session.removeListener(_onSessionChanged);+ widget.session.addListener(_onSessionChanged);+ // The tile was pointed at another agent. Whatever was half-typed was meant for the previous+ // one, and silently sending it to its replacement would be worse than losing it.+ _controller.clear();+ }+ if (!identical(oldWidget.focusNode, widget.focusNode)) {+ oldWidget.focusNode.removeListener(_onFocusChanged);+ widget.focusNode.addListener(_onFocusChanged);+ }+ }++ @override+ void dispose() {+ widget.session.removeListener(_onSessionChanged);+ widget.focusNode.removeListener(_onFocusChanged);+ terminalFontStore.removeListener(_onFontChanged);+ _controller.dispose();+ super.dispose();+ }++ /// Enabled-ness follows the stream's status, so a rebuild is needed when it moves.+ void _onSessionChanged() {+ if (mounted) setState(() {});+ }++ /// Keeps this box's face in step with the terminal above it — see the `style:` comment below.+ void _onFontChanged() {+ if (mounted) setState(() {});+ }++ /// The composer is the primary input on a remote terminal. Its surface stays+ /// visible at rest, then the rim and prompt glyph take the accent when the+ /// keyboard lands here so the destination of typing is unmistakable.+ void _onFocusChanged() {+ if (mounted) setState(() {});+ }++ /// Guards the settle window inside [TerminalSession.sendComposerText]: the body is already in+ /// the pane while we wait to submit it, so a second Enter arriving in that window would type+ /// the next message into the middle of the one being sent.+ bool _sending = false;++ Future<void> _submit() async {+ if (_sending || !widget.inputEnabled || !widget.session.acceptsInput) {+ return;+ }+ final text = _controller.text;+ if (text.isEmpty) return;+ _sending = true;+ try {+ if (!await widget.session.sendComposerText(text)) return;+ _controller.clear();+ } finally {+ _sending = false;+ }+ }++ /// Breaks the line at the caret, for ⌥⏎.+ ///+ /// Written into the controller rather than left to the field, which is what Shift+Enter does:+ /// AppKit turns ⌥⏎ into `insertNewlineIgnoringFieldEditor:`, a selector Flutter's text input+ /// client does not answer, so passing the key through would drop it on the floor. Doing it here+ /// also makes the behaviour the same on every platform the app builds for.+ void _insertNewline() {+ final value = _controller.value;+ final selection = value.selection;+ if (!selection.isValid) {+ // No caret to speak of (the field has never been placed in). Append.+ _controller.value = TextEditingValue(+ text: '${value.text}\n',+ selection: TextSelection.collapsed(offset: value.text.length + 1),+ );+ return;+ }+ _controller.value = TextEditingValue(+ text:+ '${selection.textBefore(value.text)}\n'+ '${selection.textAfter(value.text)}',+ selection: TextSelection.collapsed(offset: selection.start + 1),+ );+ }++ /// Enter sends; ⌥⏎ and Shift+Enter compose another line.+ ///+ /// ⌥⏎ is the one the muscle memory comes with — it is how Claude Code and Codex take a second+ /// line at their own prompts, and it is what the shortcuts sheet promises for a pane+ /// (`kTerminalOwnedKeys`). The composer is the same prompt wearing a Flutter field, so it has to+ /// answer the same key. Shift+Enter is left to the field, which inserts for it natively.+ ///+ /// `TextField.onSubmitted` cannot do this — it never fires for a multi-line field.+ KeyEventResult _onKeyEvent(FocusNode node, KeyEvent event) {+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {+ return KeyEventResult.ignored;+ }+ final isEnter =+ event.logicalKey == LogicalKeyboardKey.enter ||+ event.logicalKey == LogicalKeyboardKey.numpadEnter;+ if (!isEnter) return KeyEventResult.ignored;+ if (HardwareKeyboard.instance.isAltPressed) {+ _insertNewline();+ return KeyEventResult.handled;+ }+ if (HardwareKeyboard.instance.isShiftPressed) return KeyEventResult.ignored;+ unawaited(_submit());+ return KeyEventResult.handled;+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final enabled = widget.inputEnabled && widget.session.acceptsInput;+ final focused = widget.focusNode.hasFocus;+ final terminalStyle = terminalFontStore.value;+ // No top border of its own: [ComposerGrip] is the line between this and the terminal.+ return Padding(+ padding: const EdgeInsets.fromLTRB(12, 6, 12, 12),+ // ⚠️ The composer belongs to the TERMINAL, not to the app's chrome, so it is held out of+ // the app-wide UI text scale twice over — once for its TYPE here, and once for its BOX+ // below. Both are needed, and for different reasons.+ //+ // This half keeps everything inside the surface at the terminal's own size: the typed text,+ // the hint, and the `›`. What is typed here lands over there, so it has to look like it.+ child: MediaQuery.withNoTextScaling(+ child: AnimatedContainer(+ key: const ValueKey('terminal-composer-surface'),+ duration: const Duration(milliseconds: 140),+ curve: Curves.easeOut,+ constraints: const BoxConstraints(minHeight: 48),+ decoration: BoxDecoration(+ color: enabled+ ? grid.AppGlass.surfaceFill+ : grid.AppGlass.surfaceFill.withValues(alpha: 0.66),+ borderRadius: BorderRadius.circular(10),+ border: Border.all(+ color: focused+ ? grid.AppPalette.accentOnSurface+ : grid.AppGlass.lift,+ width: focused ? 1.5 : 1,+ ),+ boxShadow: focused+ ? grid.AppSurface.composerShadow+ : grid.AppGlass.shadow,+ ),+ child: Focus(+ onKeyEvent: _onKeyEvent,+ child: Row(+ children: [+ Padding(+ padding: const EdgeInsets.only(left: 14, right: 10),+ child: AnimatedDefaultTextStyle(+ key: const ValueKey('terminal-composer-prompt-style'),+ duration: const Duration(milliseconds: 140),+ curve: Curves.easeOut,+ style: terminalStyle+ .toTextStyle(+ color: focused+ ? grid.AppPalette.accentOnSurface+ : grid.AppPalette.textSecondary,+ bold: true,+ )+ .copyWith(letterSpacing: 0),+ child: const Text(+ '›',+ key: ValueKey('terminal-composer-prompt'),+ ),+ ),+ ),+ Expanded(+ child: Shortcuts(+ // Terminal-style line editing: readline's Ctrl+W/Ctrl+U are missing from+ // Flutter's own default text-editing shortcuts on every platform, unlike+ // Option/Cmd+Backspace and Ctrl+A/E, which the field already gets for free.+ shortcuts: const <ShortcutActivator, Intent>{+ SingleActivator(LogicalKeyboardKey.keyW, control: true):+ DeleteToNextWordBoundaryIntent(forward: false),+ SingleActivator(LogicalKeyboardKey.keyU, control: true):+ DeleteToLineBreakIntent(forward: false),+ },+ child: TextField(+ controller: _controller,+ focusNode: widget.focusNode,+ enabled: enabled,+ minLines: 1,+ maxLines: 6,+ // The message is going to a terminal, so it is shown in the terminal's own face:+ // what is typed here should look like what will land over there.+ style: terminalStyle+ .toTextStyle(color: grid.AppPalette.textPrimary)+ .copyWith(letterSpacing: 0),+ textInputAction: TextInputAction.newline,+ keyboardType: TextInputType.multiline,+ decoration: InputDecoration(+ isDense: true,+ filled: false,+ // ⚠️ THE BOX, unpinned from the theme — and `withNoTextScaling` above does+ // NOT reach it. `inputDecorationTheme` gives every field a minimum of+ // `AppControl.heightFieldScaled` and a padding multiplied by+ // `AppFont.uiScale` — a plain static, not a MediaQuery, so no scaling scope+ // can hold it back. Left inherited, raising the UI size grows this field+ // (36 → 48.9 at the top of the range) past the surface's own 48, which+ // shrinks the Expanded holding the terminal, which drops a row, which sends a+ // `terminal_resize` to the remote agent. The composer only appears for REMOTE+ // machines, so that is the only case where it would ever have bitten.+ //+ // The surface above owns this box's height now, so the field asks for no+ // minimum of its own — and `contentPadding` below is stated rather than+ // inherited for the same reason. Measured by+ // `terminal_ui_scale_isolation_test.dart`.+ constraints: const BoxConstraints(minHeight: 0),+ hintText: enabled+ ? 'Message agent… · ↵ send'+ : 'Connecting to terminal…',+ // InputDecorator merges this with the app-wide field hint+ // style. Set tracking explicitly so the UI-control font's+ // letter spacing cannot leak into terminal typography.+ hintStyle: terminalStyle+ .toTextStyle(+ color: enabled+ ? grid.AppPalette.textSecondary+ : grid.AppPalette.textFaint,+ )+ .copyWith(letterSpacing: 0),+ contentPadding: const EdgeInsets.fromLTRB(+ 0,+ 12,+ 14,+ 12,+ ),+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ disabledBorder: InputBorder.none,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }+}++/// The handle that opens and closes the composer, sitting on the line between the terminal and the+/// box it controls.+///+/// It deliberately lives OUTSIDE [TerminalComposer]: a control kept inside would vanish along with+/// the thing it hides, leaving no way back. On the divider it also keeps ONE fixed position in both+/// states — the target never moves, so closing and reopening is the same click twice.+class ComposerGrip extends StatelessWidget {+ const ComposerGrip({+ super.key,+ required this.expanded,+ required this.onPressed,+ });++ final bool expanded;+ final VoidCallback onPressed;++ /// Tall enough to take a click, short enough that a collapsed pane gives the terminal back+ /// essentially every row the box was using.+ static const double height = 16;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return SizedBox(+ height: height,+ child: Stack(+ alignment: Alignment.center,+ children: [+ Container(height: 1, color: AppColors.border),+ Tooltip(+ message: expanded ? 'Hide the send box' : 'Show the send box',+ child: Material(+ color: grid.AppPalette.windowBg,+ // `borderStrong`, not `border`: the faint one is a SEPARATOR token, sized to be+ // findable at a seam the eye is already on. This rim has to hold a shape against+ // terminal output, which is what the stronger hairline exists for.+ shape: StadiumBorder(+ side: BorderSide(color: AppColors.borderStrong),+ ),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: onPressed,+ child: SizedBox(+ width: 40,+ height: height,+ child: Icon(+ expanded+ ? LucideIcons.chevronDown300+ : LucideIcons.chevronUp300,+ size: 12,+ // One step up from the faint ink this started on, in both directions at once:+ // the token resolves lighter on dark and darker on light, so the glyph gains+ // contrast against the pane either way instead of only one of them.+ color: AppColors.mutedStrong,+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/mobile/lib/widgets/terminal_find_bar.dart b/mobile/lib/widgets/terminal_find_bar.dartnew file mode 100644index 000000000..c155dbde3--- /dev/null+++ b/mobile/lib/widgets/terminal_find_bar.dart@@ -0,0 +1,312 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../terminal/terminal_search.dart';++class TerminalFindBar extends StatefulWidget {+ const TerminalFindBar({+ super.key,+ required this.search,+ required this.onQuery,+ required this.onStep,+ required this.onClose,+ required this.onFocus,+ this.initialQuery = '',+ this.initialCaseSensitive = false,+ this.readOnly = false,+ });++ /// Null while the focused pane keeps its input ready without a search index.+ final TerminalSearch? search;+ final String initialQuery;+ final bool initialCaseSensitive;+ final void Function(String query, bool caseSensitive) onQuery;+ final ValueChanged<int> onStep;+ final VoidCallback onClose;+ final VoidCallback onFocus;+ final bool readOnly;++ @override+ State<TerminalFindBar> createState() => TerminalFindBarState();+}++class TerminalFindBarState extends State<TerminalFindBar> {+ static final _idle = Listenable.merge(const []);+ final _scope = FocusScopeNode(debugLabel: 'Terminal Find');+ final _focus = FocusNode(debugLabel: 'Find in terminal');+ late final _text = TextEditingController(+ text: widget.search?.query ?? widget.initialQuery,+ );+ // Keys can arrive before the widget receives the newly opened search.+ TerminalSearch? _activeSearch;++ @override+ void initState() {+ super.initState();+ _activeSearch = widget.search;+ _setActive(widget.search != null);+ _focus.addListener(_onFocus);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && widget.search != null) focusSearch();+ });+ }++ @override+ void didUpdateWidget(TerminalFindBar oldWidget) {+ super.didUpdateWidget(oldWidget);+ _activeSearch = widget.search;+ _setActive(widget.search != null);+ if (widget.search == null && _text.text != widget.initialQuery) {+ _text.text = widget.initialQuery;+ }+ }++ void _setActive(bool active) {+ _scope.canRequestFocus = active;+ _scope.descendantsAreFocusable = active;+ _scope.descendantsAreTraversable = active;+ }++ void releaseSearchFocus() {+ _activeSearch = null;+ _setActive(false);+ }++ void _onFocus() {+ if (_focus.hasFocus) widget.onFocus();+ }++ void focusSearch({bool selectAll = true, TerminalSearch? search}) {+ _activeSearch = search ?? widget.search ?? _activeSearch;+ _setActive(true);+ _focus.requestFocus();+ if (selectAll) {+ _text.selection = TextSelection(+ baseOffset: 0,+ extentOffset: _text.text.length,+ );+ }+ }++ KeyEventResult _onKeyEvent(FocusNode node, KeyEvent event) {+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {+ return KeyEventResult.ignored;+ }+ final keyboard = HardwareKeyboard.instance;+ if (keyboard.isMetaPressed ||+ keyboard.isControlPressed ||+ keyboard.isAltPressed) {+ return KeyEventResult.ignored;+ }+ final enter =+ event.logicalKey == LogicalKeyboardKey.enter ||+ event.logicalKey == LogicalKeyboardKey.numpadEnter;+ final escape =+ event.logicalKey == LogicalKeyboardKey.escape &&+ !keyboard.isShiftPressed;+ if (!enter && !escape) return KeyEventResult.ignored;+ final composing = _text.value.composing;+ if (composing.isValid && !composing.isCollapsed) {+ // Let the platform commit/cancel composition without a later shortcut+ // submitting the editor or closing Find instead.+ return KeyEventResult.skipRemainingHandlers;+ }+ if (escape) {+ widget.onClose();+ } else {+ widget.onStep(keyboard.isShiftPressed ? -1 : 1);+ }+ return KeyEventResult.handled;+ }++ @override+ void dispose() {+ _focus.removeListener(_onFocus);+ _focus.dispose();+ _scope.dispose();+ _text.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => FocusScope(+ node: _scope,+ onKeyEvent: _onKeyEvent,+ child: Material(+ color: const Color(0xff272727),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(8),+ side: const BorderSide(color: Colors.white24),+ ),+ child: Padding(+ padding: const EdgeInsets.only(left: 10, right: 4, top: 2, bottom: 2),+ child: ListenableBuilder(+ listenable: widget.search ?? _idle,+ // Live output and result navigation update the controls, not the+ // editor. Keep its widget stable while the search index refreshes.+ child: Expanded(+ key: const ValueKey('terminal-find-editor'),+ child: TextField(+ controller: _text,+ focusNode: _focus,+ autofocus: widget.search != null,+ textAlignVertical: TextAlignVertical.center,+ style: const TextStyle(+ fontSize: 13,+ height: 1,+ color: Colors.white,+ ),+ decoration: const InputDecoration(+ hintText: 'Find in terminal…',+ hintStyle: TextStyle(color: Colors.white54),+ isDense: true,+ isCollapsed: true,+ constraints: BoxConstraints(),+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ filled: false,+ contentPadding: EdgeInsets.zero,+ ),+ onChanged: (value) => widget.onQuery(+ value,+ _activeSearch?.caseSensitive ?? widget.initialCaseSensitive,+ ),+ ),+ ),+ builder: (context, editor) {+ final search = widget.search;+ final query = search?.query ?? '';+ final searching = search?.searching ?? false;+ final hasSnapshot = search?.hasSnapshot ?? false;+ final count = search?.count ?? 0;+ final selected = (search?.selected ?? -1) + 1;+ final sensitive =+ search?.caseSensitive ?? widget.initialCaseSensitive;+ final status = query.isEmpty+ ? ''+ : searching && !hasSnapshot+ ? '…'+ : '$selected/$count';+ Widget button(+ String label,+ Widget icon,+ VoidCallback? action, {+ bool selected = false,+ }) => SizedBox(+ width: 28,+ height: 30,+ child: IconButton(+ tooltip: label,+ onPressed: action,+ isSelected: selected,+ constraints: const BoxConstraints.tightFor(+ width: 28,+ height: 30,+ ),+ padding: EdgeInsets.zero,+ visualDensity: VisualDensity.compact,+ iconSize: 17,+ color: selected ? Colors.white : Colors.white60,+ icon: icon,+ ),+ );+ return Row(+ children: [+ if (widget.readOnly) ...[+ const Tooltip(+ message: 'This terminal is read only',+ child: Icon(+ Icons.lock_outline,+ size: 14,+ color: Colors.white54,+ ),+ ),+ const SizedBox(width: 6),+ ],+ editor!,+ const SizedBox(width: 6),+ Semantics(+ liveRegion: true,+ label: searching && !hasSnapshot+ ? 'Searching terminal'+ : query.isEmpty+ ? 'Find in terminal'+ : count == 0+ ? 'No matches'+ : 'Match $selected of $count',+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 56),+ child: ExcludeSemantics(+ child: Text(+ status,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontSize: 11,+ height: 1,+ color: count == 0 && query.isNotEmpty && !searching+ ? const Color(0xffffb4a9)+ : Colors.white54,+ ),+ ),+ ),+ ),+ ),+ const SizedBox(width: 4),+ button(+ 'Match case',+ Text(+ 'Aa',+ style: TextStyle(+ fontSize: 12,+ height: 1,+ color: sensitive ? Colors.white : Colors.white54,+ fontWeight: sensitive+ ? FontWeight.w700+ : FontWeight.normal,+ ),+ ),+ () {+ widget.onQuery(+ _text.text,+ !(_activeSearch?.caseSensitive ??+ widget.initialCaseSensitive),+ );+ _focus.requestFocus();+ },+ selected: sensitive,+ ),+ button(+ 'Previous match (⇧⌘G)',+ const Icon(Icons.keyboard_arrow_up),+ count > 0+ ? () {+ widget.onStep(-1);+ _focus.requestFocus();+ }+ : null,+ ),+ button(+ 'Next match (⌘G)',+ const Icon(Icons.keyboard_arrow_down),+ count > 0+ ? () {+ widget.onStep(1);+ _focus.requestFocus();+ }+ : null,+ ),+ button(+ 'Close find (Esc)',+ const Icon(Icons.close),+ widget.onClose,+ ),+ ],+ );+ },+ ),+ ),+ ),+ );+}diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dartnew file mode 100644index 000000000..13ec9f1c0--- /dev/null+++ b/mobile/lib/widgets/terminal_panel.dart@@ -0,0 +1,1918 @@+import 'dart:async';+import 'dart:math' as math;++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:flutter/services.dart';+import 'package:xterm/xterm.dart';++import '../clipboard/native_clipboard.dart';+import '../state/app_state.dart';++import 'agent_drag.dart';+import 'rename_agent_dialog.dart';+import 'terminal_composer.dart';+import '../shortcuts/app_keymap.dart';+import '../shortcuts/keymap.dart';+import 'terminal_find_bar.dart';+import '../terminal/terminal_search.dart';+import '../terminal/terminal_snapshot.dart';+import '../terminal/terminal_binary.dart';+import '../terminal/terminal_font_store.dart';+import '../terminal/terminal_link_opener.dart';+import '../terminal/remote_media_download.dart';+import '../terminal/terminal_links.dart';+import '../terminal/terminal_session.dart';+import '../terminal/terminal_theme.dart';+import '../terminal/terminal_theme_store.dart';+import '../terminal/terminal_viewport.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../theme/app_theme.dart';+import 'engine_identity.dart';+import 'pane_header_actions.dart';++/// The pane header's own horizontal inset.+const double _stripPadding = 14;++typedef TerminalNotice = ({String label, String detail, IconData icon});++class TerminalPanel extends StatefulWidget {+ final AppNotifier notifier;+ final TerminalSession session;++ /// Takes this tile off the grid. Null when the terminal is the whole window,+ /// where there is nothing to close it back to.+ final VoidCallback? onClose;+ final VoidCallback? onDelete;++ final VoidCallback? onToggleZoom;+ final bool zoomed;++ /// This native terminal took the keyboard, so its grid tile becomes focused.+ final VoidCallback? onRendererFocus;++ /// Only the focused grid tile may claim keyboard focus on mount/rebuild.+ final bool focused;+ final bool visible;+ final Size? viewportSize;++ /// A shared terminal can move to another harness without being remounted.+ final (String, int)? paneLocation;+ final (int, int, int?)? layoutRequest;+ final bool compactHeader;++ /// The tile's own header strip — engine, title, status, pin, close. Off on a+ /// phone, whose page draws its own header and has no tile to pin, close or+ /// drag (`phone/terminal_page.dart` in the mobile package).+ final bool showHeader;+ final int focusRequest;++ /// Whether this tile's composer textbox is showing. Only consulted for a remote machine.+ final bool composerVisible;+ final bool readOnly;+ final TerminalNotice? notice;++ /// Flips [composerVisible]. Null where there is no composer to toggle.+ final VoidCallback? onToggleComposer;++ /// Lets the header be dragged to trade places with another tile. Null when+ /// this is the only tile — see [_TerminalHeader.paneDrag].+ final PaneDragHandle? paneDrag;++ /// Test seam for OS actions; normal panes use the platform launcher.+ final TerminalLinkOpener? linkOpener;+ final RemoteMediaDownloader? mediaDownloader;++ const TerminalPanel({+ super.key,+ required this.notifier,+ required this.session,+ required this.focused,+ this.visible = true,+ this.viewportSize,+ this.paneLocation,+ this.layoutRequest,+ this.compactHeader = false,+ this.showHeader = true,+ this.focusRequest = 0,+ this.composerVisible = false,+ this.readOnly = false,+ this.notice,+ this.onToggleComposer,+ this.onClose,+ this.onDelete,+ this.onToggleZoom,+ this.zoomed = false,+ this.onRendererFocus,+ this.paneDrag,+ this.linkOpener,+ this.mediaDownloader,+ });++ @override+ State<TerminalPanel> createState() => _TerminalPanelState();+}++class _TerminalPanelState extends State<TerminalPanel>+ with WidgetsBindingObserver+ implements TerminalViewport {+ static const _dialScale = 2.5;+ static const _dialStopVelocity = 40.0;+ static const _dialDecayPerSecond = 0.002;++ final TerminalController _controller = TerminalController();+ final ScrollController _scrollController = ScrollController(+ keepScrollOffset: false,+ );+ final FocusNode _focusNode = FocusNode();+ final FocusNode _composerFocus = FocusNode();+ final _findBarKey = GlobalKey<TerminalFindBarState>();+ TerminalSearch? _find;+ String _lastFindQuery = '';+ bool _lastFindCaseSensitive = false;+ CellAnchor? _lastFindAnchor;+ Buffer? _lastFindBuffer;+ TerminalHighlight? _findHighlight;+ Buffer? _findPaintedBuffer;+ BufferRangeLine? _findPaintedRange;+ Buffer? _findOriginBuffer;+ CellAnchor? _findOriginLine;+ double _findOriginFraction = 0;+ bool _findOriginAtEnd = false;+ bool _findRevealPending = false;+ late Terminal _viewTerminal;+ late GlobalKey<TerminalViewState> _terminalViewKey;+ Timer? _dialInertiaTimer;+ Timer? _cursorBlinkTimer;+ ValueListenable<TickerModeData>? _tickerMode;+ double _dialVelocity = 0;+ bool _cursorBlinkVisible = true;+ double _alternateScrollRemainder = 0;+ int? _lastInertiaMicros;+ late final TerminalLinkOpener _linkOpener;+ Offset? _linkPointerPosition;+ String? _hoveredLink;+ String? _pressedLink;+ bool _openingLink = false;+ bool _linkRefreshPending = false;+ bool _followTail = true;+ TerminalStyle _terminalFont = terminalFontStore.value;+ bool _observingLinkModifiers = false;+ late final RemoteMediaDownloader _mediaDownloader;+ MediaDownloadCancellation? _previewCancellation;+ RemoteMediaProgress? _previewProgress;+ Object? _headerPresentation;+ Widget? _header;++ @override+ void initState() {+ super.initState();+ _viewTerminal = widget.session.terminal;+ _viewTerminal.addListener(_scheduleLinkRefresh);+ _scrollController.addListener(_onScrollChanged);+ _terminalViewKey = GlobalKey<TerminalViewState>();+ _linkOpener = widget.linkOpener ?? TerminalLinkOpener();+ _mediaDownloader = widget.mediaDownloader ?? RemoteMediaDownloader();+ _focusNode.addListener(_handleFocusChange);+ _composerFocus.addListener(_handleComposerFocusChange);+ WidgetsBinding.instance.addObserver(this);+ widget.session.attachViewport(this);+ widget.session.addListener(_onSessionChanged);+ terminalFontStore.addListener(_onFontChanged);+ // Colours repaint the view in place — no relayout, no resize frame — but+ // they still need a rebuild to reach it, and this widget reads the store+ // directly rather than through a builder.+ terminalThemeStore.addListener(_onFontChanged);+ _afterTerminalMounted();+ }++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _updateTickerMode();+ }++ @override+ void activate() {+ super.activate();+ _updateTickerMode();+ }++ @override+ void deactivate() {+ _stopCursorBlink();+ super.deactivate();+ }++ void _updateTickerMode() {+ final mode = TickerMode.getValuesNotifier(context);+ if (!identical(mode, _tickerMode)) {+ _tickerMode?.removeListener(_syncCursorBlink);+ _tickerMode = mode..addListener(_syncCursorBlink);+ }+ _syncCursorBlink();+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) =>+ _syncCursorBlink();++ @override+ void didUpdateWidget(TerminalPanel oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (!identical(oldWidget.session, widget.session)) {+ _closeFind(restore: false, focus: false, rebuild: false);+ _clearLastFind();+ _lastFindQuery = '';+ _previewCancellation?.cancel();+ _previewProgress = null;+ oldWidget.session.setCursorBlinkPhase(true);+ oldWidget.session.removeListener(_onSessionChanged);+ oldWidget.session.detachViewport(this);+ widget.session.attachViewport(this);+ widget.session.addListener(_onSessionChanged);+ _composerFocusPending = false;+ _cancelDialInertia();+ _controller.clearSelection();+ _viewTerminal.removeListener(_scheduleLinkRefresh);+ _viewTerminal = widget.session.terminal;+ _viewTerminal.addListener(_scheduleLinkRefresh);+ _pressedLink = null;+ _hoveredLink = null;+ _observeLinkModifiers(false);+ _terminalViewKey = GlobalKey<TerminalViewState>();+ _followTail = true;+ _cursorBlinkVisible = true;+ widget.session.setCursorBlinkPhase(true);+ _afterTerminalMounted();+ }+ if (oldWidget.visible && !widget.visible) {+ _rememberFollowTail();+ _focusNode.unfocus();+ _composerFocus.unfocus();+ _cancelDialInertia();+ _linkPointerPosition = null;+ _hoveredLink = null;+ _pressedLink = null;+ _observeLinkModifiers(false);+ }+ if (widget.visible &&+ (!oldWidget.visible || oldWidget.paneLocation != widget.paneLocation)) {+ _afterTerminalMounted();+ }+ if (oldWidget.viewportSize != widget.viewportSize ||+ oldWidget.layoutRequest != widget.layoutRequest) {+ // Geometry can change while a resize handle or another control owns+ // the keyboard. Refresh the viewport without claiming input ownership.+ _afterTerminalMounted(claimFocus: false);+ }+ if (widget.focused &&+ (!oldWidget.focused || oldWidget.focusRequest != widget.focusRequest)) {+ _claimFocusAfterFrame();+ }+ // Showing or hiding the box changes how many rows the terminal has. Re-measure so the remote+ // grid is resized to what is actually on screen.+ if (oldWidget.composerVisible != widget.composerVisible) {+ _afterTerminalMounted();+ }+ _syncCursorBlink();+ }++ @override+ void dispose() {+ _closeFind(restore: false, focus: false, rebuild: false);+ _clearLastFind();+ WidgetsBinding.instance.removeObserver(this);+ _tickerMode?.removeListener(_syncCursorBlink);+ _previewCancellation?.cancel();+ _viewTerminal.removeListener(_scheduleLinkRefresh);+ _scrollController.removeListener(_onScrollChanged);+ _observeLinkModifiers(false);+ widget.session.setCursorBlinkPhase(true);+ widget.session.removeListener(_onSessionChanged);+ widget.session.detachViewport(this);+ terminalFontStore.removeListener(_onFontChanged);+ terminalThemeStore.removeListener(_onFontChanged);+ _cancelDialInertia();+ _cursorBlinkTimer?.cancel();+ _focusNode.removeListener(_handleFocusChange);+ _composerFocus.removeListener(_handleComposerFocusChange);+ _controller.dispose();+ _scrollController.dispose();+ _focusNode.dispose();+ _composerFocus.dispose();+ super.dispose();+ }++ /// Whether this pane shows the composer.+ ///+ /// Only a machine reached over the network charges a round trip per keystroke, so only it gets+ /// the box — typing into a local pane already costs well under a millisecond and it would be+ /// dead weight across the bottom.+ ///+ /// The test is `isLocalMachine`, NOT `isRemote`: the app only ever lists machines whose authMode+ /// is `remote` (see the filter in `_loadMachines`), so `isRemote` is true for every pane,+ /// including this very computer. What separates them is whether the machine's computerId is this+ /// one, which is what puts it on the loopback transport.+ bool get _showsComposer {+ final machineState = widget.notifier.stateOf(widget.session.machineId);+ return machineState?.isLocalMachine != true && widget.composerVisible;+ }++ /// The composer refuses focus while it is disabled, which it is until the stream goes live. When+ /// a selection lands on a still-attaching agent, the claim is parked here and made again from+ /// [_onSessionChanged] the moment it starts accepting input.+ bool _composerFocusPending = false;++ void _onSessionChanged() {+ if (!mounted) return;+ _syncCursorBlink();+ // A pane can open BEFORE its screen exists: over the relay it mounts empty+ // and the retained scrollback is replayed a moment later, so the jump in+ // `_afterTerminalMounted` lands on nothing and the screen then fills in+ // above the reader. xterm does not close this — its own `_scrollToBottom`+ // answers typing and the keyboard opening, never new output.+ //+ // Gated on [_followTail], which is kept as "the view is showing its end",+ // so a pane the reader has scrolled up in — or one restored to a saved+ // position — is not at the end, and is never followed.+ // Visible only. A parked pane holds the offset it was left at while output+ // arrives behind it — `swarm_screen_test` pins that — and comes back to the+ // end through `_afterTerminalMounted`, which is where returning is handled.+ if (_followTail && widget.visible) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || !widget.visible) return;+ if (!_followTail || !_scrollController.hasClients) return;+ final position = _scrollController.position;+ if (position.pixels != position.maxScrollExtent) {+ position.jumpTo(position.maxScrollExtent);+ }+ });+ }+ if (!_composerFocusPending) return;+ if (!widget.focused || !_showsComposer) {+ _composerFocusPending = false;+ return;+ }+ if (widget.readOnly || !widget.session.acceptsInput) return;+ _composerFocusPending = false;+ // Deferred a frame on purpose. This panel registers its session listener before the composer+ // registers its own (a parent's initState runs first), so at this instant the field is still+ // built as disabled — and a disabled field REFUSES focus. Claiming after the frame the+ // composer rebuilds in is what makes the claim actually land.+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!_canClaimInput || !widget.focused || !_showsComposer) return;+ if (widget.readOnly || !widget.session.acceptsInput) return;+ _composerFocus.requestFocus();+ });+ }++ /// The vendored renderer already treats a changed `textStyle` as a full re-layout — see+ /// `RenderTerminal.textStyle`'s setter — which recomputes cols/rows from the new cell size and+ /// resizes the remote session automatically. This just needs to get the new value into `build()`.+ void _onFontChanged() {+ if (!mounted) return;+ if (_terminalFont != terminalFontStore.value) {+ _terminalFont = terminalFontStore.value;+ _afterTerminalMounted(claimFocus: false);+ }+ setState(() {});+ }++ void _syncTerminal(Terminal terminal) {+ if (identical(_viewTerminal, terminal)) return;++ final previous = _viewTerminal.buffer;+ final next = terminal.buffer;+ final render = _laidOutTerminalView()?.renderTerminal;+ final lineHeight = render?.lineHeight;+ final position = _scrollController.hasClients+ ? _scrollController.position+ : null;+ final viewportRow = position != null && lineHeight != null+ ? (position.pixels / lineHeight).floor()+ : null;+ final viewportFraction = position != null && lineHeight != null+ ? position.pixels / lineHeight - viewportRow!+ : 0.0;+ final atEnd = _followTail || position == null;+ final originRow = _findOriginLine?.attached == true+ ? _findOriginLine!.y+ : null;+ final originFraction = _findOriginFraction;+ final originAtEnd = _findOriginAtEnd;+ final match =+ _find?.match?.begin ??+ (_lastFindAnchor?.attached == true ? _lastFindAnchor!.offset : null);+ final selection = _controller.selection;+ final selectedText = selection == null ? null : previous.getText(selection);+ final locations = remapTerminalRows(previous, next, [+ if (!atEnd) ?viewportRow,+ ?originRow,+ ?match?.y,+ ?selection?.begin.y,+ ?selection?.end.y,+ ]);+ int row(int old) => locations[old] ?? old.clamp(0, next.lines.length - 1);+ CellOffset location(CellOffset old) =>+ CellOffset(old.x.clamp(0, terminal.viewWidth - 1), row(old.y));+ final wasFinding = _find != null;+ _closeFind(restore: false, focus: false, rebuild: false);+ _clearLastFind();+ // Selection anchors belong to a specific circular buffer. Detach them+ // before the TerminalView starts laying out the replacement terminal.+ _controller.clearSelection();+ _viewTerminal.removeListener(_scheduleLinkRefresh);+ _viewTerminal = terminal;+ _viewTerminal.addListener(_scheduleLinkRefresh);+ _pressedLink = null;+ _hoveredLink = null;+ _observeLinkModifiers(false);+ _cancelDialInertia();+ _alternateScrollRemainder = 0;+ _cursorBlinkVisible = true;+ widget.session.setCursorBlinkPhase(true);+ if (position != null &&+ lineHeight != null &&+ !atEnd &&+ viewportRow != null) {+ // Correct before the retained renderer lays out the replacement, so its+ // first frame already shows the reader's location without a scroll flash.+ position.correctPixels(+ (row(viewportRow) + viewportFraction) * lineHeight,+ );+ }+ if (match != null) {+ _lastFindBuffer = next;+ _lastFindAnchor = next.createAnchorFromOffset(location(match));+ }+ if (selection != null &&+ locations.containsKey(selection.begin.y) &&+ locations.containsKey(selection.end.y)) {+ final range = selection is BufferRangeBlock+ ? BufferRangeBlock(location(selection.begin), location(selection.end))+ : BufferRangeLine(location(selection.begin), location(selection.end));+ if (next.getText(range) == selectedText) {+ _controller.setSelection(+ next.createAnchorFromOffset(range.begin),+ next.createAnchorFromOffset(range.end),+ );+ }+ }+ if (wasFinding) {+ _findOriginBuffer = next;+ _findOriginAtEnd = originAtEnd;+ _findOriginFraction = originFraction;+ if (originRow != null) {+ _findOriginLine = next.createAnchor(0, row(originRow));+ }+ _findRevealPending = true;+ _find = TerminalSearch(+ terminal,+ origin: match == null ? null : location(match),+ )..addListener(_onFindChanged);+ _find!.setQuery(_lastFindQuery, caseSensitive: _lastFindCaseSensitive);+ }+ _followTail = atEnd;+ _afterTerminalMounted(scrollToEnd: atEnd);+ }++ /// Typing in the composer focuses the tile, exactly like clicking into the terminal does.+ void _handleComposerFocusChange() {+ if (_composerFocus.hasFocus) widget.onRendererFocus?.call();+ }++ void _handleFocusChange() {+ _syncCursorBlink();+ if (_focusNode.hasFocus) {+ widget.onRendererFocus?.call();+ }+ }++ /// Re-establishes the native text-input connection on pane activation.+ ///+ /// Replacing an agent remounts TerminalView but deliberately keeps this+ /// FocusNode. A plain requestFocus is a no-op when that node already owns+ /// focus, leaving macOS without a TextInputConnection until the user clicks+ /// the terminal. TerminalView.requestKeyboard handles both cases: it moves+ /// focus when needed, or opens the connection immediately when focus stayed+ /// on this tile. That is essential for ordinary keys and IMEs alike.+ bool _claimFocus(TerminalViewState view, {bool navigating = false}) {+ if (!_canClaimInput ||+ (!navigating && (!widget.focused || !widget.visible))) {+ return false;+ }+ if (_find != null) {+ final bar = _findBarKey.currentState;+ if (bar == null) return false;+ bar.focusSearch(selectAll: false);+ return true;+ }+ if (_composerFocus.hasFocus) return true;+ // On a remote pane the box gets the caret, not the terminal. Landing in the terminal would+ // hand the user the per-keystroke path by default — the exact cost the box exists to avoid.+ if (_showsComposer && !widget.readOnly) {+ if (widget.session.acceptsInput && _composerFocus.canRequestFocus) {+ _composerFocus.requestFocus();+ return true;+ }+ _composerFocusPending = true;+ return false;+ }+ view.requestKeyboard();+ return true;+ }++ bool get _canClaimInput =>+ mounted &&+ _focusNode.canRequestFocus &&+ ModalRoute.of(context)?.isCurrent != false;++ @override+ bool focusInput() {+ // The model has already selected this retained view, but widget visibility+ // and focus flags will not catch up until the canvas's next frame.+ if (!_canClaimInput ||+ !identical(widget.notifier.focusedPane?.session, widget.session)) {+ return false;+ }+ final view = _laidOutTerminalView();+ if (view == null) return false;+ return _claimFocus(view, navigating: true);+ }++ void _claimFocusAfterFrame() {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ final view = _laidOutTerminalView();+ if (view != null) _claimFocus(view);+ });+ }++ /// Retaining a renderer must not retain a polling loop. Only the focused,+ /// interactive terminal in the active window needs a cursor clock. Observe+ /// ticker mode without rebuilding the subtree when a route covers it.+ void _syncCursorBlink() {+ final lifecycle = WidgetsBinding.instance.lifecycleState;+ final findEnabled =+ mounted &&+ widget.visible &&+ (_tickerMode?.value.enabled ?? false) &&+ (lifecycle == null || lifecycle == AppLifecycleState.resumed);+ _find?.setEnabled(findEnabled);+ if (!findEnabled) _clearFindHighlight();+ final enabled =+ mounted &&+ widget.visible &&+ !widget.readOnly &&+ _focusNode.hasFocus &&+ widget.session.acceptsInput &&+ (_tickerMode?.value.enabled ?? false) &&+ (lifecycle == null || lifecycle == AppLifecycleState.resumed);+ if (!enabled) {+ _stopCursorBlink();+ return;+ }+ _cursorBlinkTimer ??= Timer.periodic(+ const Duration(milliseconds: 500),+ (_) => _setCursorBlinkVisible(!_cursorBlinkVisible),+ );+ }++ void _stopCursorBlink() {+ _cursorBlinkTimer?.cancel();+ _cursorBlinkTimer = null;+ _setCursorBlinkVisible(true);+ }++ void _setCursorBlinkVisible(bool visible) {+ if (visible == _cursorBlinkVisible) return;+ _cursorBlinkVisible = visible;+ widget.session.setCursorBlinkPhase(visible);+ _repaintTerminalCursor();+ }++ void _repaintTerminalCursor() {+ _laidOutTerminalView()?.renderTerminal.markNeedsPaint();+ }++ /// The terminal view, but only once its render object can be read.+ ///+ /// `currentState?.renderTerminal` reads as null-safe and is not: the `?.`+ /// answers "is the State there", while the getter behind it is+ /// `_viewportKey.currentContext!.findRenderObject()`. Three call sites here+ /// relied on that misreading, one of them a timer that keeps ticking while a+ /// keyframe swaps the emulator underneath it.+ ///+ /// Insurance, NOT a diagnosis. The app has been crashing with exactly the+ /// error this bang produces, and the obvious theory — that the viewport is+ /// built during layout, leaving a window where the State exists and the+ /// context does not — was tested and is FALSE: the library builds it inside+ /// `Scrollable.viewportBuilder`, which runs during build, so the context is+ /// there as soon as the State is. Whatever is actually throwing has not been+ /// found yet; see the trace written by TerminalSession on a renderer fault.+ /// This only makes sure these three sites are not the ones that do it.+ TerminalViewState? _laidOutTerminalView() {+ final state = _terminalViewKey.currentState;+ if (state == null) return null;+ try {+ state.renderTerminal;+ return state;+ } catch (_) {+ return null;+ }+ }++ void _afterTerminalMounted({+ bool clearSelection = false,+ bool scrollToEnd = true,+ bool claimFocus = true,+ int retries = 2,+ }) {+ // Request alignment before this frame's layout, so even a retained pane's+ // first visible paint uses its new size. Keep Find's explicit location.+ if (scrollToEnd && _find == null) {+ _cancelDialInertia();+ _followTail = true;+ _laidOutTerminalView()?.scrollToBottom();+ }+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || !widget.visible) return;+ if (clearSelection) _controller.clearSelection();+ final view = _laidOutTerminalView();+ if (view == null) {+ if (retries > 0) {+ _afterTerminalMounted(+ clearSelection: clearSelection,+ scrollToEnd: scrollToEnd,+ claimFocus: claimFocus,+ retries: retries - 1,+ );+ }+ return;+ }+ final renderTerminal = view.renderTerminal;+ final cellSize = renderTerminal.cellSize;+ final renderSize = renderTerminal.size;+ if (cellSize.width > 0 && cellSize.height > 0) {+ widget.session.reportViewport(+ renderSize.width ~/ cellSize.width,+ renderSize.height ~/ cellSize.height,+ );+ }+ if (scrollToEnd && _followTail && _find == null) {+ view.scrollToBottom();+ }+ // Never over the composer: a rebuild that re-focuses this tile while someone is typing into+ // the box would pull the caret out from under them mid-sentence.+ if (claimFocus) _claimFocus(view);+ if (_find != null) _onFindChanged();+ if (_linkPointerPosition != null) _hoverLink(_linkPointerPosition);+ });+ }++ @override+ void find(TerminalFindAction action) {+ if (!mounted || !widget.visible || !widget.focused) return;+ final wasClosed = _find == null;+ if (wasClosed) {+ final view = _laidOutTerminalView();+ if (view == null || !_scrollController.hasClients) return;+ final position = _scrollController.position;+ final height = view.renderTerminal.lineHeight;+ final row = (position.pixels / height).floor().clamp(+ 0,+ _viewTerminal.buffer.lines.length - 1,+ );+ _findOriginBuffer = _viewTerminal.buffer;+ _findOriginLine = _findOriginBuffer!.createAnchor(0, row);+ _findOriginFraction = position.pixels / height - row;+ _findOriginAtEnd = position.maxScrollExtent - position.pixels < 1;+ var origin = CellOffset(0, row);+ if (action != TerminalFindAction.open &&+ _lastFindAnchor?.attached == true &&+ identical(_lastFindBuffer, _viewTerminal.buffer)) {+ final last = _lastFindAnchor!.offset;+ origin = CellOffset(+ last.x + (action == TerminalFindAction.next ? 1 : 0),+ last.y,+ );+ }+ _find = TerminalSearch(_viewTerminal, origin: origin)+ ..addListener(_onFindChanged);+ _findRevealPending = true;+ _find!.setQuery(_lastFindQuery, caseSensitive: _lastFindCaseSensitive);+ _findBarKey.currentState?.focusSearch(search: _find);+ setState(() {});+ } else if (action == TerminalFindAction.open) {+ _findBarKey.currentState?.focusSearch();+ }+ if (action != TerminalFindAction.open &&+ !(wasClosed && action == TerminalFindAction.next)) {+ _stepFind(action == TerminalFindAction.next ? 1 : -1);+ }+ }++ void _queryFind(String query, bool caseSensitive) {+ _lastFindQuery = query;+ _lastFindCaseSensitive = caseSensitive;+ _findRevealPending = true;+ _find?.setQuery(query, caseSensitive: caseSensitive);+ }++ void _stepFind(int delta) {+ _findRevealPending = true;+ _find?.step(delta);+ }++ void _onFindChanged() {+ final search = _find;+ if (!mounted || search == null || !widget.visible) return;+ final range = search.match;+ if (range != _findPaintedRange ||+ !identical(_findPaintedBuffer, _viewTerminal.buffer)) {+ _clearFindHighlight();+ if (range != null) {+ _findPaintedBuffer = _viewTerminal.buffer;+ _findPaintedRange = range;+ _findHighlight = _controller.highlight(+ p1: _viewTerminal.buffer.createAnchorFromOffset(range.begin),+ p2: _viewTerminal.buffer.createAnchorFromOffset(range.end),+ color: const Color(0x99cf8e25),+ );+ }+ }+ if (_findRevealPending && search.hasSnapshot && range != null) {+ final render = _laidOutTerminalView()?.renderTerminal;+ if (render == null || !_scrollController.hasClients) return;+ _findRevealPending = false;+ final position = _scrollController.position;+ final top = range.begin.y * render.lineHeight + 10;+ final bottom = (range.end.y + 1) * render.lineHeight + 10;+ final safeTop = position.pixels + 10;+ final safeBottom = position.pixels + position.viewportDimension - 10;+ final offset = top < safeTop+ ? top - 10+ : bottom > safeBottom+ ? bottom - position.viewportDimension + 10+ : position.pixels;+ final target = offset.clamp(+ position.minScrollExtent,+ position.maxScrollExtent,+ );+ if (target != position.pixels) position.jumpTo(target);+ }+ }++ void _clearFindHighlight() {+ final highlight = _findHighlight;+ _findHighlight = null;+ _findPaintedBuffer = null;+ _findPaintedRange = null;+ if (highlight == null) return;+ highlight.dispose();+ highlight.p1.dispose();+ highlight.p2.dispose();+ }++ void _clearLastFind() {+ _lastFindAnchor?.dispose();+ _lastFindAnchor = null;+ _lastFindBuffer = null;+ }++ void _closeFind({+ bool restore = true,+ bool focus = true,+ bool rebuild = true,+ }) {+ final search = _find;+ if (search == null) return;+ final match = search.match;+ if (match != null) {+ _clearLastFind();+ _lastFindAnchor = _viewTerminal.buffer.createAnchorFromOffset(+ match.begin,+ );+ _lastFindBuffer = _viewTerminal.buffer;+ }+ _find = null;+ _findBarKey.currentState?.releaseSearchFocus();+ search.removeListener(_onFindChanged);+ search.dispose();+ _clearFindHighlight();+ if (restore &&+ identical(_findOriginBuffer, _viewTerminal.buffer) &&+ _scrollController.hasClients) {+ final height = _laidOutTerminalView()?.renderTerminal.lineHeight;+ final position = _scrollController.position;+ if (height != null) {+ final offset = _findOriginAtEnd+ ? position.maxScrollExtent+ : _findOriginLine?.attached == true+ ? (_findOriginLine!.y + _findOriginFraction) * height+ : 0.0;+ position.jumpTo(+ offset.clamp(position.minScrollExtent, position.maxScrollExtent),+ );+ }+ }+ _findOriginLine?.dispose();+ _findOriginLine = null;+ _findOriginBuffer = null;+ if (rebuild && mounted) setState(() {});+ if (focus) {+ // The retained terminal is already mounted. Return its input connection+ // now: the next key can arrive before Find's removal is painted.+ final view = _laidOutTerminalView();+ if (view != null) {+ _claimFocus(view);+ } else {+ _claimFocusAfterFrame();+ }+ }+ }++ @override+ void scroll(int phase, int dy, int velocity) {+ if (phase == 0) _cancelDialInertia();+ if (dy != 0) _applyDialDelta(-dy * _dialScale);+ if (phase == 2) _startDialInertia(velocity.toDouble());+ }++ void _applyDialDelta(double delta) {+ final terminal = widget.session.terminal;+ if (terminal.isUsingAltBuffer) {+ final lineHeight =+ _laidOutTerminalView()?.renderTerminal.lineHeight ?? 16.0;+ _alternateScrollRemainder += delta;+ while (_alternateScrollRemainder.abs() >= lineHeight) {+ final up = _alternateScrollRemainder < 0;+ if (widget.session.scrollViaTmuxCopyMode) {+ widget.session.sendScrollCommand(up, 1);+ } else {+ final handled = terminal.mouseInput(+ up ? TerminalMouseButton.wheelUp : TerminalMouseButton.wheelDown,+ TerminalMouseButtonState.down,+ CellOffset(terminal.viewWidth ~/ 2, terminal.viewHeight ~/ 2),+ );+ if (!handled) {+ terminal.keyInput(up ? TerminalKey.arrowUp : TerminalKey.arrowDown);+ }+ }+ _alternateScrollRemainder += up ? lineHeight : -lineHeight;+ }+ return;+ }++ if (!_scrollController.hasClients) return;+ final position = _scrollController.position;+ final target = (position.pixels + delta)+ .clamp(position.minScrollExtent, position.maxScrollExtent)+ .toDouble();+ position.jumpTo(target);+ }++ void _startDialInertia(double velocity) {+ _cancelDialInertia();+ if (velocity.abs() < _dialStopVelocity) return;+ _dialVelocity = velocity;+ _lastInertiaMicros = DateTime.now().microsecondsSinceEpoch;+ _dialInertiaTimer = Timer.periodic(const Duration(milliseconds: 16), (_) {+ if (!mounted) {+ _cancelDialInertia();+ return;+ }+ final now = DateTime.now().microsecondsSinceEpoch;+ final previous = _lastInertiaMicros ?? now;+ final elapsedSeconds = math.min((now - previous) / 1000000, 0.05);+ _lastInertiaMicros = now;+ _applyDialDelta(-_dialVelocity * elapsedSeconds * _dialScale);+ _dialVelocity *= math.pow(_dialDecayPerSecond, elapsedSeconds).toDouble();+ if (_dialVelocity.abs() < _dialStopVelocity) _cancelDialInertia();+ });+ }++ void _cancelDialInertia() {+ _dialInertiaTimer?.cancel();+ _dialInertiaTimer = null;+ _dialVelocity = 0;+ _lastInertiaMicros = null;+ }++ Future<void> _copyOrPaste() async {+ final terminal = widget.session.terminal;+ final selection = _controller.selection;+ if (selection != null) {+ final text = terminal.buffer.getText(selection);+ _controller.clearSelection();+ await Clipboard.setData(ClipboardData(text: text));+ return;+ }+ await _paste();+ }++ /// Paste — including the kinds of clipboard this app cannot fully read.+ ///+ /// ⚠️ FLUTTER'S OWN `Clipboard` API ONLY SEES `text/plain`. A screenshot has no+ /// text at all, so a naive body finds `null` and returns, silently: the single+ /// most common thing anyone pastes into a coding agent did nothing, with no+ /// error and nothing in a log. [NativeClipboard] closes that gap with a native+ /// platform-channel read for an actual image (macOS/Linux only; see its doc).+ ///+ /// The engines running in these panes read the system clipboard THEMSELVES —+ /// Claude Code attaches an image on Ctrl+V — so on a LOCAL pane that is already+ /// true with zero help from us: a bare Ctrl+V is all that ever ran here, before+ /// native image paste existed, and it still works because the engine and this+ /// app share the exact same OS clipboard. The wire-based `pasteImage` (chunked+ /// upload, daemon writes the far side's OS clipboard, daemon replays Ctrl+V) is+ /// reserved for a genuinely REMOTE pane, whose engine reads a DIFFERENT+ /// clipboard than this one — see `MachineState.isLocalMachine`.+ Future<void> _paste() async {+ if (widget.readOnly || !widget.session.acceptsInput) return;+ final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text;+ if (text != null && text.isNotEmpty) {+ // A binary TerminalBinaryKind.paste frame rides the same AEAD channel as every other terminal+ // byte, so this works identically for a local or a relayed machine — see pasteText's doc. Only+ // the CLI's own version gates it: an older daemon never advertises the capability.+ final machine = widget.notifier.stateOf(widget.session.machineId);+ if (machine != null && machine.terminalPasteRawAvailable) {+ await widget.session.pasteText(text);+ } else {+ widget.session.terminal.paste(text);+ }+ return;+ }+ final machine = widget.notifier.stateOf(widget.session.machineId);+ if (machine != null &&+ !machine.isLocalMachine &&+ machine.terminalImagePasteAvailable) {+ final imageBytes = await NativeClipboard.readImagePng();+ if (imageBytes != null &&+ imageBytes.isNotEmpty &&+ imageBytes.length <= terminalLocalImagePasteMaxPayloadBytes) {+ await widget.session.pasteImage(imageBytes);+ return;+ }+ }+ widget.session.terminal.keyInput(TerminalKey.keyV, ctrl: true);+ }++ /// ⌘V (Ctrl+V off Apple) — taken from xterm so the fallthrough above applies.+ ///+ /// xterm binds paste itself, but only ever to its text-only action. `onKeyEvent`+ /// is the one hook that runs BEFORE its shortcut map (terminal_view.dart), so+ /// this is where the binding has to be replaced rather than added.+ KeyEventResult _onTerminalKey(FocusNode node, KeyEvent event) {+ if (event is! KeyDownEvent) return KeyEventResult.ignored;+ if (event.logicalKey != LogicalKeyboardKey.keyV) {+ return KeyEventResult.ignored;+ }+ final keyboard = HardwareKeyboard.instance;+ if (keyboard.isShiftPressed) {+ return KeyEventResult.ignored; // ⇧⌘V is a different verb+ }++ final apple =+ defaultTargetPlatform == TargetPlatform.macOS ||+ defaultTargetPlatform == TargetPlatform.iOS;+ final pasting = apple ? keyboard.isMetaPressed : keyboard.isControlPressed;+ if (!pasting) return KeyEventResult.ignored;+ unawaited(_paste());+ return KeyEventResult.handled;+ }++ bool get _linkModifierPressed {+ final keyboard = HardwareKeyboard.instance;+ if (keyboard.isAltPressed || keyboard.isShiftPressed) return false;+ return defaultTargetPlatform == TargetPlatform.macOS+ ? keyboard.isMetaPressed && !keyboard.isControlPressed+ : keyboard.isControlPressed && !keyboard.isMetaPressed;+ }++ bool _onLinkModifierChanged(KeyEvent event) {+ const modifiers = [+ LogicalKeyboardKey.metaLeft,+ LogicalKeyboardKey.metaRight,+ LogicalKeyboardKey.controlLeft,+ LogicalKeyboardKey.controlRight,+ LogicalKeyboardKey.altLeft,+ LogicalKeyboardKey.altRight,+ LogicalKeyboardKey.shiftLeft,+ LogicalKeyboardKey.shiftRight,+ ];+ if (_linkPointerPosition != null &&+ mounted &&+ modifiers.contains(event.logicalKey)) {+ setState(() {}); // Refresh the cursor even when the mouse has not moved.+ }+ return false; // Modifier observation never consumes a terminal key.+ }++ /// Modifier keys only change the pointer over a link. Do not fan every key+ /// out to the retained terminal pool when no pointer feedback can change.+ void _observeLinkModifiers(bool enabled) {+ if (_observingLinkModifiers == enabled) return;+ _observingLinkModifiers = enabled;+ final keyboard = HardwareKeyboard.instance;+ if (enabled) {+ keyboard.addHandler(_onLinkModifierChanged);+ } else {+ keyboard.removeHandler(_onLinkModifierChanged);+ }+ }++ void _scheduleLinkRefresh() {+ if (!widget.visible ||+ _linkPointerPosition == null ||+ _linkRefreshPending) {+ return;+ }+ _linkRefreshPending = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ _linkRefreshPending = false;+ if (mounted && widget.visible) _hoverLink(_linkPointerPosition);+ });+ }++ void _rememberFollowTail() {+ if (!_scrollController.hasClients) return;+ final position = _scrollController.position;+ _followTail = position.maxScrollExtent - position.pixels < 1;+ }++ void _onScrollChanged() {+ _rememberFollowTail();+ _scheduleLinkRefresh();+ }++ String? _linkAtPointer(Offset globalPosition) {+ final view = _laidOutTerminalView();+ if (view == null) return null;+ final render = view.renderTerminal;+ final local = render.globalToLocal(globalPosition);+ if (!(Offset.zero & render.size).contains(local)) return null;+ return terminalLinkAt(_viewTerminal, render.getCellOffset(local));+ }++ void _hoverLink(Offset? globalPosition) {+ _linkPointerPosition = widget.visible ? globalPosition : null;+ final target = _linkPointerPosition == null+ ? null+ : _linkAtPointer(_linkPointerPosition!);+ _observeLinkModifiers(target != null);+ if (target != _hoveredLink) setState(() => _hoveredLink = target);+ }++ bool _onLinkTapDown(TapDownDetails details, CellOffset cell) {+ _pressedLink = _linkModifierPressed+ ? _linkAtPointer(details.globalPosition)+ : null;+ return _pressedLink != null;+ }++ void _onLinkTapUp(TapUpDetails details, CellOffset cell) {+ final target = _pressedLink;+ _pressedLink = null;+ // Read the current buffer again: streamed output may have replaced the+ // text between press and release, or this pane may now show another agent.+ if (target == null ||+ !_linkModifierPressed ||+ target != _linkAtPointer(details.globalPosition)) {+ return;+ }+ unawaited(_openLink(target));+ }++ Future<void> _openLink(String target) async {+ if (_openingLink) return;+ _openingLink = true;+ final session = widget.session;+ final notifier = widget.notifier;+ final cancellation = MediaDownloadCancellation();+ _previewCancellation = cancellation;+ try {+ final message = await _linkOpener.open(+ target,+ isLocalMachine:+ notifier.stateOf(session.machineId)?.isLocalMachine == true,+ isCancelled: () =>+ cancellation.isCancelled ||+ !mounted ||+ !identical(session, widget.session),+ downloadRemote: (path) async {+ setState(+ () => _previewProgress = const RemoteMediaProgress('', 0, null),+ );+ return _mediaDownloader.download(+ readChunk: ({required offset, revision}) =>+ notifier.readRemoteMediaChunk(+ session.machineId,+ session.agentId,+ path,+ offset: offset,+ revision: revision,+ ),+ cancellation: cancellation,+ onProgress: (progress) {+ if (mounted &&+ !cancellation.isCancelled &&+ identical(session, widget.session)) {+ setState(() => _previewProgress = progress);+ }+ },+ );+ },+ );+ if (!mounted || !identical(session, widget.session) || message == null) {+ return;+ }+ ScaffoldMessenger.maybeOf(context)+ ?.showSnackBar(SnackBar(content: Text(message)));+ } finally {+ _openingLink = false;+ if (identical(_previewCancellation, cancellation)) {+ _previewCancellation = null;+ if (mounted) setState(() => _previewProgress = null);+ }+ }+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final session = widget.session;+ _syncTerminal(session.terminal);+ final machineState = widget.notifier.stateOf(session.machineId);+ final remote = machineState != null && !machineState.isLocalMachine;+ final showComposer = _showsComposer;+ return KeymapRegion(+ contextKind: KeymapContext.terminal,+ composing: () =>+ _focusNode.hasFocus &&+ _terminalViewKey.currentState?.isComposing == true,+ child: ColoredBox(+ color: grid.AppPalette.windowBg,+ child: Column(+ children: [+ Stack(+ children: [+ Visibility(+ visible: _find == null,+ maintainSize: true,+ maintainAnimation: true,+ maintainState: true,+ child: widget.showHeader+ ? _buildHeader(context)+ : const SizedBox.shrink(),+ ),+ // Attach the focused pane's input before Find is requested.+ // Hidden/unfocused panes need no dormant editor or index.+ if (_find != null || (widget.visible && widget.focused))+ Positioned.fill(+ child: Offstage(+ offstage: _find == null,+ child: LayoutBuilder(+ builder: (context, constraints) => Row(+ children: [+ if (constraints.maxWidth > 520)+ Expanded(+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: _stripPadding,+ ),+ child: Text(+ session.agentName,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(+ fontSize: 13,+ color: Colors.white70,+ ),+ ),+ ),+ )+ else+ const Spacer(),+ SizedBox(+ width: math.min(constraints.maxWidth, 380),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 6,+ vertical: 4,+ ),+ child: TerminalFindBar(+ key: _findBarKey,+ search: _find,+ initialQuery: _lastFindQuery,+ initialCaseSensitive: _lastFindCaseSensitive,+ readOnly:+ widget.readOnly || !session.acceptsInput,+ onQuery: _queryFind,+ onStep: _stepFind,+ onClose: _closeFind,+ onFocus: () => widget.onRendererFocus?.call(),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ],+ ),++ Divider(height: 1, color: AppColors.border),+ Expanded(+ child: Stack(+ children: [+ Positioned.fill(+ child: MouseRegion(+ onEnter: (event) => _hoverLink(event.position),+ onHover: (event) => _hoverLink(event.position),+ onExit: (_) => _hoverLink(null),+ child: Tooltip(+ message: _hoveredLink == null+ ? ''+ : '${defaultTargetPlatform == TargetPlatform.macOS ? '⌘' : 'Ctrl'}-click to open\n$_hoveredLink',+ child: TerminalView(+ session.terminal,+ key: _terminalViewKey,+ controller: _controller,+ autoResize: widget.visible,+ resizeBuffer: false,+ renderingEnabled: widget.visible,+ scrollController: _scrollController,+ focusNode: _focusNode,+ autofocus: widget.focused && !showComposer,+ readOnly: widget.readOnly || !session.acceptsInput,+ theme: terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ ),+ padding: const EdgeInsets.all(10),+ textStyle: terminalFontStore.value,+ // ⚠️ The terminal is NOT app chrome, and the user said so:+ // it carries its own font settings (Settings ▸ Terminal,+ // [terminalFontStore]) precisely because its type is a grid+ // a remote program is drawing into, not a label.+ //+ // Without this, `TerminalView` falls back to+ // `MediaQuery.textScalerOf(context)` (xterm's+ // terminal_view.dart:257), so the app-wide UI size would+ // change the cell size — and a changed cell size is not+ // cosmetic here: it re-derives `rows`, which fires+ // `Terminal.resize` → `session.resize` → a `terminal_resize`+ // frame on the wire and a real SIGWINCH at the far end.+ //+ // Read in `createRenderObject`, not only on update, so this+ // holds from the very first frame — no scaled first paint+ // and no startup resize.+ textScaler: TextScaler.noScaling,+ onKeyEvent: _onTerminalKey,+ onTapDown: _onLinkTapDown,+ onTapUp: _onLinkTapUp,+ mouseCursor:+ _hoveredLink != null && _linkModifierPressed+ ? SystemMouseCursors.click+ : SystemMouseCursors.text,+ onSecondaryTapDown: (_, _) => _copyOrPaste(),++ onAltBufferScroll: session.scrollViaTmuxCopyMode+ ? (up) => session.sendScrollCommand(up, 1)+ : null,+ ),+ ),+ ),+ ),+ if (session.uploadProgress != null ||+ _previewProgress != null)+ Positioned(+ left: 14,+ right: 14,+ bottom: 12,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (session.uploadProgress != null)+ _TransferProgressBadge(+ label:+ 'Uploading ${session.uploadProgress!.label}',+ fraction: session.uploadProgress!.percent,+ onCancel: () => unawaited(session.cancelUpload()),+ ),+ if (session.uploadProgress != null &&+ _previewProgress != null)+ const SizedBox(height: 8),+ if (_previewProgress != null)+ _TransferProgressBadge(+ label: _previewProgress!.totalBytes == null+ ? 'Preparing preview…'+ : 'Downloading ${_previewProgress!.filename}',+ fraction: _previewProgress!.fraction,+ onCancel: () => _previewCancellation?.cancel(),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ // The grip is shown whether or not the box is: collapsed, it is the only way back.+ if (!widget.compactHeader &&+ remote &&+ widget.onToggleComposer != null)+ ComposerGrip(+ expanded: widget.composerVisible,+ onPressed: widget.onToggleComposer!,+ ),+ if (showComposer)+ TerminalComposer(+ session: session,+ focusNode: _composerFocus,+ inputEnabled: !widget.readOnly,+ ),+ ],+ ),+ ),+ );+ }++ /// Visibility and focus affect the renderer, not its title and controls.+ /// Retain that subtree until its presentation changes. Callback wrappers+ /// resolve the current widget so cached controls never retain an old action.+ Widget _buildHeader(BuildContext context) {+ final session = widget.session;+ final machine = widget.notifier.stateOf(session.machineId);+ final agent = machine?.agents+ .where((a) => a.id == session.agentId)+ .firstOrNull;+ final presentation = (+ theme: Theme.of(context),+ brightness: grid.AppTheme.brightness.value,+ fontFamily: AppFonts.sans,+ notifier: widget.notifier,+ session: session,+ name: session.agentName,+ status: session.status,+ notice: widget.notice,+ readOnly: widget.readOnly,+ error: session.errorMessage ?? session.errorCode,+ link: session.linkMode,+ machine: machine?.machine,+ local: machine?.isLocalMachine,+ agent: agent,+ project: agent == null ? null : machine?.projectOf(agent),+ compact: widget.compactHeader,+ close: widget.onClose != null,+ delete: widget.onDelete != null,+ composer: widget.composerVisible,+ toggleComposer: widget.onToggleComposer != null,+ zoomed: widget.zoomed,+ zoom: widget.onToggleZoom != null,+ dragId: widget.paneDrag?.ref.paneId,+ dragSize: widget.paneDrag?.size,+ );+ if (_headerPresentation != presentation) {+ _headerPresentation = presentation;+ _header = _TerminalHeader(+ notifier: widget.notifier,+ session: session,+ notice: widget.notice,+ readOnly: widget.readOnly,+ compact: widget.compactHeader,+ zoomed: widget.zoomed,+ onToggleZoom: widget.onToggleZoom == null+ ? null+ : () => widget.onToggleZoom?.call(),+ onClose: widget.onClose == null ? null : () => widget.onClose?.call(),+ onDelete: widget.onDelete == null+ ? null+ : () => widget.onDelete?.call(),+ composerVisible: widget.composerVisible,+ onToggleComposer: widget.onToggleComposer == null+ ? null+ : () => widget.onToggleComposer?.call(),+ paneDrag: widget.paneDrag,+ );+ }+ return _header!;+ }+}++class _TerminalHeader extends StatelessWidget {+ final AppNotifier notifier;+ final TerminalSession session;+ final TerminalNotice? notice;+ final bool readOnly;+ final VoidCallback? onClose;++ /// Ends the agent (with a confirmation), as the rail's row menu does. Null+ /// where the pane cannot name a live agent to end.+ final VoidCallback? onDelete;+ final bool compact;+ final VoidCallback? onToggleZoom;+ final bool zoomed;+ final VoidCallback? onToggleComposer;+ final bool composerVisible;++ /// This strip's drag gesture, or null when there is nothing to drag.+ ///+ /// Null with a SINGLE pane, and then the strip is inert on purpose: there is+ /// no other tile to trade places with, so a drag would have no meaning to+ /// give it. It used to move the WINDOW here (window_manager's+ /// DragToMoveArea, left over from hiding the title bar) — but once AppKit's+ /// `startDragging` takes a gesture it keeps it, so the two meanings cannot+ /// share one drag. The window is moved from HarnessTopBar now.+ final PaneDragHandle? paneDrag;++ const _TerminalHeader({+ required this.notifier,+ required this.session,+ this.notice,+ this.readOnly = false,+ this.onClose,+ this.onDelete,+ this.compact = false,+ this.onToggleZoom,+ this.zoomed = false,+ this.paneDrag,+ this.onToggleComposer,+ this.composerVisible = false,+ });++ @override+ Widget build(BuildContext context) {+ final color = switch (session.status) {+ TerminalSessionStatus.controlling => AppColors.success,+ TerminalSessionStatus.opening ||+ TerminalSessionStatus.resyncing => AppColors.warning,+ TerminalSessionStatus.takenOver => AppColors.warning,+ TerminalSessionStatus.error => AppColors.danger,+ TerminalSessionStatus.closed => AppColors.mutedStrong,+ };+ final profile = notifier+ .stateOf(session.machineId)+ ?.agents+ .where((agent) => agent.id == session.agentId)+ .firstOrNull+ ?.codexHome;+ final status =+ notice ??+ switch (session.status) {+ TerminalSessionStatus.controlling => null,+ TerminalSessionStatus.opening => (+ label: 'Connecting',+ icon: Icons.sync,+ detail:+ 'Connecting to this terminal. Retained output is read only.',+ ),+ TerminalSessionStatus.resyncing => (+ label: 'Restoring',+ icon: Icons.sync,+ detail: 'Restoring this terminal. Retained output is read only.',+ ),+ TerminalSessionStatus.takenOver => (+ label: 'Take control',+ icon: Icons.lock_outline,+ detail: 'Read only: another app controls this terminal. Take control moves input ownership to this app.',+ ),+ TerminalSessionStatus.error || TerminalSessionStatus.closed => (+ label: 'Reconnect',+ icon: Icons.refresh,+ detail:+ session.errorMessage ??+ session.errorCode ??+ 'This stream is closed. Retained output is read only.',+ ),+ };+ final canReconnect =+ notice == null &&+ !readOnly &&+ (session.status == TerminalSessionStatus.error ||+ session.status == TerminalSessionStatus.closed ||+ session.status == TerminalSessionStatus.takenOver);+ final machine = notifier.stateOf(session.machineId);+ final agent = machine?.agents+ .where((a) => a.id == session.agentId)+ .firstOrNull;+ final project = agent == null ? null : machine?.projectOf(agent);+ final machineName = machine?.machine.displayName ?? session.machineId;+ final identityDetail = [+ session.agentName,+ machineName,+ if (project != null) project.cwd,+ if (project?.branch != null) 'Branch: ${project!.branch}',+ if (profile != null) 'Codex profile: $profile',+ 'Double-click to rename',+ ].join('\n');+ final remoteComposer = machine != null && !machine.isLocalMachine+ ? onToggleComposer+ : null;+ final actionsWidth = remoteComposer == null ? 88.0 : 118.0;+ final folder =+ project?.cwd+ .split(RegExp(r'[/\\]'))+ .where((part) => part.isNotEmpty)+ .lastOrNull ??+ project?.name;+ final details = [+ if (folder?.isNotEmpty == true) folder!,+ if (project?.branch?.trim().isNotEmpty == true) project!.branch!,+ machineName,+ ];+ final branchIndex = project?.branch?.trim().isNotEmpty == true+ ? (folder?.isNotEmpty == true ? 1 : 0)+ : null;+ final strip = PaneHeaderHover(+ child: SizedBox(+ height: compact ? 38 : 46,+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: _stripPadding),+ child: LayoutBuilder(+ builder: (context, constraints) => Row(+ children: [+ EngineMark(engine: session.engineId, size: 17),+ const SizedBox(width: 10),+ Expanded(+ child: Tooltip(+ message: identityDetail,+ waitDuration: const Duration(milliseconds: 700),+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onDoubleTap: () => unawaited(+ showAgentRenameDialog(+ context,+ notifier,+ session.machineId,+ session.agentId,+ session.agentName,+ ),+ ),+ child: Text(+ session.agentName,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: AppColors.text,+ fontFamily: AppFonts.sans,+ fontSize: 13,+ fontWeight: FontWeight.w600,+ ),+ ),+ ),+ ),+ ),+ const SizedBox(width: 8),+ if (status != null)+ ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth: math.max(+ 0,+ math.min(+ constraints.maxWidth * .3,+ constraints.maxWidth - actionsWidth - 110,+ ),+ ),+ ),+ child: Align(+ alignment: Alignment.centerRight,+ child: Tooltip(+ message: status.detail,+ child: TextButton(+ onPressed: canReconnect+ ? () => notifier.selectAgent(+ session.machineId,+ session.agentId,+ )+ : null,+ style: TextButton.styleFrom(+ foregroundColor: color,+ disabledForegroundColor: AppColors.textSoft,+ minimumSize: Size.zero,+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ padding: const EdgeInsets.symmetric(+ horizontal: 6,+ vertical: 4,+ ),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(status.icon, size: 14),+ const SizedBox(width: 6),+ Flexible(+ child: Text(+ status.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 11),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ )+ else if (!compact)+ Padding(+ padding: const EdgeInsets.all(4),+ child: Icon(Icons.circle, size: 8, color: color),+ ),+ // Which of the three paths carries this pane's bytes. Absent for a local machine's own+ // terminal, which has no such distinction and so gets no badge.+ //+ // The wire word and the word a person reads differ for the middle state, deliberately:+ // the CLI sends 'turn' (it is a TURN allocation) but both middle and last are relays to+ // a reader, so they read as "relay" and "ws". 'relay' on the wire kept its original+ // meaning — the backend WebSocket — so an older CLI is never mislabelled.+ if (!compact && session.linkMode != null)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 2),+ child: _LinkModeMark(mode: session.linkMode!),+ ),+ ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth: math.max(+ actionsWidth,+ constraints.maxWidth * (status == null ? .55 : .3),+ ),+ ),+ child: PaneHeaderActions(+ name: session.agentName,+ zoomed: zoomed,+ onZoom: onToggleZoom,+ onDelete: onDelete,+ onClose: onClose,+ onToggleComposer: remoteComposer,+ composerVisible: composerVisible,+ details: Tooltip(+ message: [+ if (project != null) project.cwd,+ if (project?.branch?.isNotEmpty == true)+ 'Branch: ${project!.branch}',+ machineName,+ ].join('\n'),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ for (var i = 0; i < details.length; i++) ...[+ if (i > 0)+ Text(+ ' • ',+ style: TextStyle(+ fontSize: 10,+ color: AppColors.mutedStrong,+ ),+ ),+ Flexible(+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (i == branchIndex) ...[+ Icon(+ LucideIcons.gitBranch300,+ size: 12,+ color: AppColors.mutedStrong,+ ),+ const SizedBox(width: 4),+ ],+ Flexible(+ child: Text(+ details[i],+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontFamily: AppFonts.sans,+ fontSize: 12,+ color: AppColors.mutedStrong,+ ),+ ),+ ),+ ],+ ),+ ),+ ],+ ],+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ final handle = paneDrag;+ if (handle == null) return strip;++ return Draggable<PaneDragRef>(+ data: handle.ref,+ // The grip is kept where the hand took it, so the ghost stays under the+ // cursor at the same spot on the header it was picked up by.+ dragAnchorStrategy: childDragAnchorStrategy,+ onDragStarted: () => paneDragging.value = handle.ref,+ onDragEnd: (_) => paneDragging.value = null,+ onDraggableCanceled: (_, _) => paneDragging.value = null,+ feedback: _PaneGhost(session: session, size: handle.size, header: strip),++ // The header itself does NOT change — the whole tile fades instead, in+ // _PaneCell, so what dims is the thing that is moving rather than one+ // strip of it.+ child: strip,+ );+ }+}++/// The pane header's transport badge: a compact topology for the path carrying terminal bytes.+///+/// The three shapes describe one hop, an intermediate hop, and a central server respectively. That+/// makes the modes distinguishable without colour while keeping the badge small enough for a four-pane+/// layout. The wire name `relay` still means the backend WebSocket; only its human-facing label is WS.+class _LinkModeMark extends StatelessWidget {+ final String mode;++ const _LinkModeMark({required this.mode});++ @override+ Widget build(BuildContext context) {+ final (icon, color, label) = switch (mode) {+ 'p2p' => (+ LucideIcons.link2,+ AppColors.success,+ 'P2P · Direct peer connection',+ ),+ 'turn' => (+ LucideIcons.waypoints,+ AppColors.warning,+ 'TURN · Via Cloudflare relay',+ ),+ _ => (+ LucideIcons.server,+ AppColors.mutedStrong,+ 'WS · Via Harness WebSocket relay',+ ),+ };+ return Tooltip(+ message: label,+ child: Icon(icon, size: 14, color: color, semanticLabel: label),+ );+ }+}++/// Image/file transfer progress with a cancel action, kept in the pane's corner.+class _TransferProgressBadge extends StatelessWidget {+ final String label;+ final double? fraction;+ final VoidCallback onCancel;+ const _TransferProgressBadge({+ required this.label,+ required this.fraction,+ required this.onCancel,+ });++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final percentLabel = fraction == null+ ? ''+ : ' · ${(fraction! * 100).round()}%';+ return Container(+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),+ decoration: BoxDecoration(+ color: grid.AppPalette.panelBg.withValues(alpha: 0.93),+ border: Border.all(color: AppColors.borderStrong),+ borderRadius: BorderRadius.circular(4),+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ '$label$percentLabel',+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: AppColors.textSoft,+ fontFamily: AppFonts.sans,+ fontSize: 10,+ fontWeight: FontWeight.w700,+ ),+ ),+ ),+ const SizedBox(width: 8),+ InkWell(+ onTap: onCancel,+ child: Text(+ 'CANCEL',+ style: TextStyle(+ color: AppColors.textSoft,+ fontFamily: AppFonts.sans,+ fontSize: 10,+ fontWeight: FontWeight.w700,+ ),+ ),+ ),+ ],+ ),+ const SizedBox(height: 6),+ ClipRRect(+ borderRadius: BorderRadius.circular(3),+ child: LinearProgressIndicator(+ minHeight: 4,+ value: fraction,+ backgroundColor: AppColors.border,+ color: AppColors.accent,+ ),+ ),+ ],+ ),+ );+ }+}++/// The whole tile, carried under the cursor.+///+/// ⚠️ THIS IS DRAWN, NOT PHOTOGRAPHED, AND THE PHOTOGRAPH IS WHY. The obvious+/// way to carry "the whole pane" is RepaintBoundary.toImage() on press — and it+/// FROZE THE APP. That call is a GPU readback on the raster thread, and the+/// raster thread in this app is never idle: every pane holds a terminal that+/// repaints on its own, so asking it to stop and hand a surface back on every+/// pointer-down deadlocked the window. It is not a tuning problem; there is+/// nothing to tune down to.+///+/// So the ghost is built from what is already known — the pane's measured size+/// and its own header — and the body is a plain surface rather than a copy of+/// the scrollback. It reads as the tile because it is tile-SHAPED and carries+/// the tile's name, which is what the eye is following.+///+/// See-through on purpose: a full-size opaque copy sits exactly over the tile+/// being aimed at and hides the "Swap with this pane" highlight that says the+/// drop will land.+class _PaneGhost extends StatelessWidget {+ const _PaneGhost({+ required this.session,+ required this.size,+ required this.header,+ });++ final TerminalSession session;++ /// The tile's size, handed down from the grid's LayoutBuilder.+ final Size size;++ final Widget header;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final tile = size;+ return Material(+ color: Colors.transparent,+ child: Opacity(+ opacity: 0.75,+ child: Container(+ width: tile.width,+ height: tile.height,+ decoration: BoxDecoration(+ color: grid.AppPalette.windowBg,+ border: Border.all(color: AppColors.accent, width: 1.5),+ boxShadow: [+ BoxShadow(+ color: Colors.black.withValues(alpha: 0.45),+ blurRadius: 24,+ offset: const Offset(0, 10),+ ),+ ],+ ),+ child: Column(+ children: [+ header,+ Divider(height: 1, color: AppColors.border),+ Expanded(+ child: Center(+ child: Text(+ session.agentName,+ style: TextStyle(+ color: AppColors.mutedStrong,+ fontFamily: AppFonts.sans,+ fontSize: 15,+ fontWeight: FontWeight.w600,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/lib/widgets/update_notice.dart b/mobile/lib/widgets/update_notice.dartnew file mode 100644index 000000000..85f9d49fc--- /dev/null+++ b/mobile/lib/widgets/update_notice.dart@@ -0,0 +1,534 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../core/app_version.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../shared/widgets/skeleton.dart';+import '../state/app_state.dart';+import '../update/desktop_updater.dart';+import '../update/manual_update_check.dart';++/// "18.4 MB" — a download the user is about to authorise, in the unit they+/// think in. Bytes are what the manifest carries; nobody reads 19293798.+String formatDownloadSize(int bytes) {+ if (bytes <= 0) return '';+ const mb = 1024 * 1024;+ if (bytes >= mb) return '${(bytes / mb).toStringAsFixed(1)} MB';+ return '${(bytes / 1024).round()} KB';+}++/// The band across the top of the app when a newer build is out.+///+/// It carries three states off one flag pair on [AppNotifier]: an offer, the+/// install running, and a failed install. The failure keeps the offer alive —+/// nothing was changed on disk, so the only honest thing to show is a way to+/// try again.+class UpdateNotice extends StatelessWidget {+ final AppNotifier notifier;++ const UpdateNotice({super.key, required this.notifier});++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final update = notifier.availableUpdate;+ if (update == null) return const SizedBox.shrink();++ final installing = notifier.isInstallingUpdate;+ final error = notifier.updateError;+ final failed = error != null && !installing;++ // Amber for a failure, the accent wash otherwise. Deliberately NOT green:+ // green is "machine online" everywhere else in this window, and a second+ // meaning for it here would make the rail's dots ambiguous.+ // ⚠️ COMPOSITED OVER THE WINDOW, NOT LEFT TRANSLUCENT. Both tints below are+ // washes — 8% and 10% — and this band is the one strip of the app that does+ // NOT sit inside a Scaffold: it takes a row of its own directly under+ // MaterialApp's home, so there is no surface behind it to tint. Left as-is+ // the wash lands on the bare window, which is still the platform's dark+ // ground, and the banner stays black while the whole app around it goes+ // light. Blending against the window colour keeps the designed tint and+ // gives it something to be a tint OF.+ final wash = failed+ ? grid.AppPalette.warn.withValues(alpha: 0.10)+ : grid.AppSurface.accentWash;+ final tint = Color.alphaBlend(wash, grid.AppPalette.windowBg);+ final rule = failed+ ? grid.AppPalette.warn.withValues(alpha: 0.28)+ : grid.AppPalette.accentOnSurface.withValues(alpha: 0.24);+ final markColor = failed+ ? grid.AppPalette.warn+ : grid.AppPalette.accentOnSurface;++ final String message;+ if (failed) {+ message = error;+ } else if (installing) {+ message = 'Installing Harness ${update.version}…';+ } else {+ message = 'Harness ${update.version} is available';+ }++ return Material(+ color: Colors.transparent,+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: tint,+ border: Border(bottom: BorderSide(color: rule)),+ ),+ child: Stack(+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(14, 7, 10, 7),+ child: Row(+ children: [+ SizedBox(+ width: 16,+ height: 16,+ child: installing+ ? CircularProgressIndicator(+ strokeWidth: 2,+ color: grid.AppPalette.accentOnSurface,+ )+ : Icon(+ failed+ ? LucideIcons.triangleAlert300+ : LucideIcons.arrowDownToLine300,+ size: 16,+ color: markColor,+ ),+ ),+ const SizedBox(width: 10),+ // ONE expanding child, holding the whole message. A+ // Flexible text beside a Spacer splits the free space+ // between them, which leaves the actions stranded+ // mid-band instead of anchored to the right edge.+ //+ // Inside it the sentence yields before the size does: a+ // truncated sentence still leaves both readable, whereas+ // wrapping one would push the buttons out of the band.+ Expanded(+ child: Row(+ children: [+ Flexible(+ child: Text(+ message,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: grid.AppPalette.textPrimary,+ fontSize: 12.5,+ ),+ ),+ ),+ if (!installing && !failed && update.size > 0) ...[+ const SizedBox(width: 8),+ Text(+ '· ${formatDownloadSize(update.size)}',+ style: TextStyle(+ color: grid.AppPalette.textFaint,+ fontSize: 11.5,+ ),+ ),+ ],+ ],+ ),+ ),+ const SizedBox(width: 12),+ if (failed) ...[+ _NoticeAction(+ label: 'Dismiss',+ onPressed: notifier.dismissUpdateError,+ ),+ const SizedBox(width: 6),+ _NoticeAction(+ key: const Key('retry-update-button'),+ label: 'Try again',+ kind: _ActionKind.ghost,+ onPressed: () =>+ unawaited(notifier.installAvailableUpdate()),+ ),+ ] else ...[+ _NoticeAction(+ key: const Key('skip-update-button'),+ label: 'Skip this version',+ onPressed: installing+ ? null+ : notifier.skipAvailableUpdate,+ ),+ const SizedBox(width: 6),+ _NoticeAction(+ key: const Key('install-update-button'),+ label: 'Update',+ kind: _ActionKind.primary,+ onPressed: installing+ ? null+ : () => unawaited(notifier.installAvailableUpdate()),+ ),+ ],+ ],+ ),+ ),+ // Indeterminate on purpose: downloadAndStage() resolves once, with+ // no byte counter to read, so a percentage here would be invented.+ if (installing)+ Positioned(+ left: 0,+ right: 0,+ bottom: 0,+ child: LinearProgressIndicator(+ minHeight: 2,+ backgroundColor: Colors.transparent,+ color: grid.AppPalette.accentOnSurface,+ ),+ ),+ ],+ ),+ ),+ );+ }+}++enum _ActionKind { quiet, ghost, primary }++class _NoticeAction extends StatelessWidget {+ final String label;+ final VoidCallback? onPressed;+ final _ActionKind kind;++ const _NoticeAction({+ super.key,+ required this.label,+ required this.onPressed,+ this.kind = _ActionKind.quiet,+ });++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final primary = kind == _ActionKind.primary;+ return TextButton(+ onPressed: onPressed,+ style: TextButton.styleFrom(+ minimumSize: const Size(0, 26),+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ visualDensity: VisualDensity.standard,+ backgroundColor: primary+ ? grid.AppPalette.accentOnSurface+ : Colors.transparent,+ foregroundColor: primary+ ? grid.AppPalette.windowBg+ : grid.AppPalette.textSecondary,+ disabledForegroundColor: grid.AppPalette.textFaint,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(7),+ side: kind == _ActionKind.ghost+ ? BorderSide(color: grid.AppGlass.hair)+ : BorderSide.none,+ ),+ textStyle: TextStyle(+ fontSize: 12,+ fontWeight: primary ? grid.AppFont.semibold : grid.AppFont.regular,+ ),+ ),+ child: Text(label),+ );+ }+}++/// Opens the result of a manual check from the Harness menu. It never downloads+/// a release until the user chooses the primary action.+Future<void> showUpdateCheckDialog(+ BuildContext context,+ AppNotifier notifier,+ ManualUpdateCheck result,+) {+ final update = result.update;+ if (update == null) {+ return showAppDialog<void>(+ context: context,+ builder: (context) => const _UpdateDialog(+ icon: LucideIcons.circleCheck300,+ tone: _DialogTone.ok,+ title: 'You’re up to date',+ body: 'This copy of Harness already has the latest version.',+ ),+ );+ }+ return showAppDialog<void>(+ context: context,+ barrierDismissible: false,+ builder: (dialogContext) {+ var installing = false;+ return StatefulBuilder(+ builder: (context, setState) => _UpdateDialog(+ icon: LucideIcons.arrowDownToLine300,+ title: installing+ ? 'Installing Harness ${update.version}…'+ : 'Harness ${update.version} is available',+ body: installing+ ? 'Don’t quit Harness. It will restart on its own.'+ : result.isSkipped+ ? 'You skipped this version earlier. You can still install it.'+ : 'Download and install it now? Harness will restart when it '+ 'finishes.',+ busy: installing,+ update: installing ? null : update,+ actions: installing+ ? const []+ : [+ _DialogAction(+ key: const Key('close-update-dialog-button'),+ label: 'Close',+ onPressed: () async {+ Navigator.of(dialogContext).pop();+ },+ ),+ _DialogAction(+ label: result.isSkipped+ ? 'Not now'+ : 'Skip ${update.version}',+ onPressed: () async {+ if (!result.isSkipped) {+ await notifier.skipAvailableUpdate();+ }+ if (dialogContext.mounted) {+ Navigator.of(dialogContext).pop();+ }+ },+ ),+ _DialogAction(+ label: 'Update',+ primary: true,+ onPressed: () async {+ setState(() => installing = true);+ final installed = await notifier.installAvailableUpdate();+ // A successful install never returns — the process is+ // replaced. Reaching here means it failed, and the banner+ // behind this dialog is already showing why.+ if (!dialogContext.mounted || installed) return;+ Navigator.of(dialogContext).pop();+ },+ ),+ ],+ ),+ );+ },+ );+}++enum _DialogTone { accent, ok }++class _DialogAction {+ final Key? key;+ final String label;+ final bool primary;+ final Future<void> Function() onPressed;++ const _DialogAction({+ this.key,+ required this.label,+ required this.onPressed,+ this.primary = false,+ });+}++class _UpdateDialog extends StatelessWidget {+ final IconData icon;+ final String title;+ final String body;+ final _DialogTone tone;+ final bool busy;+ final UpdateInfo? update;+ final List<_DialogAction> actions;++ const _UpdateDialog({+ required this.icon,+ required this.title,+ required this.body,+ this.tone = _DialogTone.accent,+ this.busy = false,+ this.update,+ this.actions = const [],+ });++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final mark = tone == _DialogTone.ok+ ? grid.AppPalette.online+ : grid.AppPalette.accentOnSurface;++ return Dialog(+ // No backgroundColor, no shape: `dialogTheme` supplies both, at+ // AppGlass.surfaceFill and AppCard.radius (12). The rim this used to+ // carry is gone with them — §1 allows exactly one border in the app and+ // it belongs to the menu panel, not to a dialog.+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 372),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(18, 18, 18, 14),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Container(+ width: 34,+ height: 34,+ decoration: BoxDecoration(+ color: mark.withValues(alpha: 0.13),+ borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),+ ),+ alignment: Alignment.center,+ child: busy+ ? SizedBox(+ width: 17,+ height: 17,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ color: mark,+ ),+ )+ : Icon(icon, size: 18, color: mark),+ ),+ const SizedBox(height: 12),+ Text(+ title,+ style: TextStyle(+ color: grid.AppPalette.textPrimary,+ fontSize: 15,+ fontWeight: grid.AppFont.semibold,+ ),+ ),+ const SizedBox(height: 5),+ Text(+ body,+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 12.5,+ height: 1.5,+ ),+ ),+ if (update != null) ...[+ const SizedBox(height: 12),+ Divider(height: 1, color: grid.AppGlass.hair),+ const SizedBox(height: 10),+ _Fact(label: 'Installed', value: _InstalledVersion()),+ const SizedBox(height: 6),+ _Fact(label: 'New version', value: Text(update!.version)),+ if (update!.size > 0) ...[+ const SizedBox(height: 6),+ _Fact(+ label: 'Download',+ value: Text(formatDownloadSize(update!.size)),+ ),+ ],+ ],+ if (actions.isNotEmpty) ...[+ const SizedBox(height: 15),+ Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ for (final action in actions) ...[+ if (action != actions.first) const SizedBox(width: 8),+ _NoticeAction(+ key: action.key,+ label: action.label,+ kind: action.primary+ ? _ActionKind.primary+ : _ActionKind.quiet,+ onPressed: () => unawaited(action.onPressed()),+ ),+ ],+ ],+ ),+ ],+ if (actions.isEmpty && !busy) ...[+ const SizedBox(height: 15),+ Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ _NoticeAction(+ label: 'Close',+ kind: _ActionKind.ghost,+ onPressed: () => Navigator.of(context).pop(),+ ),+ ],+ ),+ ],+ ],+ ),+ ),+ ),+ );+ }+}++/// One `label · value` line in the dialog's fact block.+class _Fact extends StatelessWidget {+ final String label;+ final Widget value;++ const _Fact({required this.label, required this.value});++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(+ width: 96,+ child: Text(+ label,+ style: TextStyle(color: grid.AppPalette.textFaint, fontSize: 11.5),+ ),+ ),+ DefaultTextStyle(+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ fontSize: 11.5,+ fontFamily: grid.AppFont.mono,+ fontFamilyFallback: grid.AppFont.monoFallback,+ ),+ child: value,+ ),+ ],+ );+ }+}++class _InstalledVersion extends StatefulWidget {+ @override+ State<_InstalledVersion> createState() => _InstalledVersionState();+}++class _InstalledVersionState extends State<_InstalledVersion> {+ // Built once, not in `build`: `runningAppVersion` reads a file on Linux, and+ // a future rebuilt per frame would put the placeholder back each time.+ late final Future<String> _info = runningAppVersion();++ @override+ Widget build(BuildContext context) => FutureBuilder<String>(+ future: _info,+ builder: (context, snapshot) {+ final version = snapshot.data;+ if (version == null) {+ // Still reading: a blank measured against the ambient mono style the+ // row sets, so it and the version it becomes are the same line.+ // Answered with nothing: the dash, which is a value.+ return snapshot.connectionState == ConnectionState.done+ ? const Text('—')+ : SkeletonText(+ style: DefaultTextStyle.of(context).style,+ width: 44,+ );+ }+ return Text(version);+ },+ );+}diff --git a/mobile/lib/widgets/welcome_workspace_preview.dart b/mobile/lib/widgets/welcome_workspace_preview.dartnew file mode 100644index 000000000..a34b2d7a7--- /dev/null+++ b/mobile/lib/widgets/welcome_workspace_preview.dart@@ -0,0 +1,134 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import 'engine_identity.dart';+import 'swarm_icon.dart';++/// A static example of the workspace. It never creates or contacts an agent.+class WelcomeWorkspacePreview extends StatelessWidget {+ const WelcomeWorkspacePreview({super.key});++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final palette = grid.AppTheme.palette.value;+ return Semantics(+ image: true,+ label: 'Example agent group: Claude Code and Codex working side by side.',+ child: ExcludeSemantics(+ child: Container(+ decoration: BoxDecoration(+ color: palette.workspace,+ borderRadius: BorderRadius.circular(10),+ border: Border.all(color: Colors.white12),+ ),+ clipBehavior: Clip.antiAlias,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Container(+ color: palette.tabBar,+ padding: const EdgeInsets.symmetric(+ horizontal: 12,+ vertical: 10,+ ),+ child: const Row(+ children: [+ SwarmIcon(size: 14, color: Colors.white70),+ SizedBox(width: 8),+ Text(+ 'Your project',+ style: TextStyle(fontSize: 12, color: Colors.white),+ ),+ Spacer(),+ Text(+ '2 agents',+ style: TextStyle(fontSize: 11, color: Colors.white70),+ ),+ ],+ ),+ ),+ Padding(+ padding: const EdgeInsets.all(8),+ child: Row(+ children: [+ Expanded(+ child: _AgentExample(+ engine: 'claude',+ title: 'Claude Code',+ task: 'Build the feature',+ color: palette.background,+ ),+ ),+ const SizedBox(width: 8),+ Expanded(+ child: _AgentExample(+ engine: 'codex',+ title: 'Codex',+ task: 'Review the changes',+ color: palette.background,+ ),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}++class _AgentExample extends StatelessWidget {+ const _AgentExample({+ required this.engine,+ required this.title,+ required this.task,+ required this.color,+ });+ final String engine, title, task;+ final Color color;++ @override+ Widget build(BuildContext context) => Container(+ padding: const EdgeInsets.all(12),+ decoration: BoxDecoration(+ color: color,+ borderRadius: BorderRadius.circular(6),+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ EngineMark(engine: engine, size: 17),+ const SizedBox(width: 7),+ Expanded(+ child: Text(+ title,+ style: const TextStyle(+ fontSize: 12,+ color: Colors.white,+ fontWeight: FontWeight.w500,+ ),+ ),+ ),+ ],+ ),+ const SizedBox(height: 14),+ Text(task, style: const TextStyle(fontSize: 11, color: Colors.white70)),+ const SizedBox(height: 10),+ for (final width in [0.9, 0.65])+ FractionallySizedBox(+ widthFactor: width,+ child: Container(+ height: 3,+ margin: const EdgeInsets.only(bottom: 5),+ color: Colors.white24,+ ),+ ),+ ],+ ),+ );+}diff --git a/mobile/lib/ws/local_cli_discovery.dart b/mobile/lib/ws/local_cli_discovery.dartnew file mode 100644index 000000000..988187963--- /dev/null+++ b/mobile/lib/ws/local_cli_discovery.dart@@ -0,0 +1,567 @@+import 'dart:async';+import 'dart:io';++import 'package:dio/dio.dart';+import 'package:flutter/foundation.dart';++import '../core/serial_port_lease.dart';+import '../core/config.dart';+import '../core/harness_cli_runner.dart';+import '../core/harness_file_store.dart';+import '../core/models.dart';++const localWsProtocolVersion = 1;+const localTerminalProtocolVersion = 3;++class LocalCliEndpoint {+ final String computerId;+ final Uri wsUri;+ final int protocolVersion;+ final int terminalProtocolVersion;++ /// Older daemons report local working folders in status before they support+ /// project metadata in agent frames. This snapshot never describes a peer.+ final Map<String, AgentProject> agentProjects;++ const LocalCliEndpoint({+ required this.computerId,+ required this.wsUri,+ required this.protocolVersion,+ required this.terminalProtocolVersion,+ this.agentProjects = const {},+ });+}++/// Reads the stable identity shared by the Harness CLI and backend machine record.+class LocalMachineIdentity {+ final File computerIdFile;+ final Map<String, String> environment;++ LocalMachineIdentity({File? computerIdFile, Map<String, String>? environment})+ : environment = environment ?? Platform.environment,+ computerIdFile =+ computerIdFile ??+ File(defaultComputerIdPath(environment: environment));++ static String defaultComputerIdPath({Map<String, String>? environment}) {+ final desktopDirectory = HarnessFileStore.defaultDirectoryPath(+ environment: environment,+ );+ final harnessHome = Directory(desktopDirectory).parent.path;+ return _joinPath(harnessHome, 'computer-id');+ }++ Future<String?> computerId() async {+ final pinned = _normalizeComputerId(environment['ADAPTER_COMPUTER_ID']);+ if (pinned != null) return pinned;+ try {+ final id = (await computerIdFile.readAsString()).trim();+ return _normalizeComputerId(id);+ } catch (_) {+ return null;+ }+ }+}++String _joinPath(String parent, String child) =>+ '$parent${Platform.pathSeparator}$child';++/// Discovers only the CLI bound to the fixed loopback address. The response+/// advertises capabilities but never contains the machine API key.+/// Starts the owned CLI directly. Finder does not need a shell/PATH in order+/// to locate the managed Node runtime and CLI bundle.+///+/// A non-zero exit is a FAILED spawn and must read as one: the CLI exits 1+/// when it could not start (a port clash, a spawn lock it gave up waiting on)+/// and 0 for every "fine, nothing to do" (already running, still connecting,+/// busy elsewhere) — which is exactly the signal the supervisor's backoff+/// wants. It used to swallow the code, so a `harness start` that failed+/// outright looked like one that worked.+Future<void> runHarnessStart(HarnessCliRunner runner) async {+ final result = await runner.run(['start']);+ if (result.exitCode != 0) {+ throw ProcessException(+ 'harness',+ const ['start'],+ '${result.stderr}'.trim().isEmpty+ ? '${result.stdout}'.trim()+ : '${result.stderr}'.trim(),+ result.exitCode,+ );+ }+}++Future<void> _defaultSpawnCommand() => runHarnessStart(HarnessCliRunner());++/// What one look at the daemon's control port found.+///+/// THREE answers, not two, and the middle one is the point. A port that+/// nobody answers on means the daemon is down and spawning it is the fix. A+/// port that answers but is not yet ready — a daemon that just came up after+/// a self-update and has not finished its backend handshake, or one still+/// scanning for agents — means a daemon is RUNNING, and spawning another can+/// only fail on the port it already holds. Collapsing the two into "not+/// ready" had the supervisor re-running `harness start` every few seconds+/// for the whole length of every update, and the boot path calling a daemon+/// that was busy connecting "did not start".+enum LocalCliProbeState { down, notReady, ready }++class LocalCliProbe {+ final LocalCliProbeState state;++ /// Non-null exactly when [state] is [LocalCliProbeState.ready].+ final LocalCliEndpoint? endpoint;++ /// Why it is not ready, for a log line or an error strip. Null when ready.+ final String? reason;++ /// What the daemon said about itself, when it answered at all.+ final int? pid;+ final String? version;++ const LocalCliProbe._({+ required this.state,+ this.endpoint,+ this.reason,+ this.pid,+ this.version,+ });++ const LocalCliProbe.down(String reason)+ : this._(state: LocalCliProbeState.down, reason: reason);++ const LocalCliProbe.notReady(String reason, {int? pid, String? version})+ : this._(+ state: LocalCliProbeState.notReady,+ reason: reason,+ pid: pid,+ version: version,+ );++ const LocalCliProbe.ready(+ LocalCliEndpoint endpoint, {+ int? pid,+ String? version,+ }) : this._(+ state: LocalCliProbeState.ready,+ endpoint: endpoint,+ pid: pid,+ version: version,+ );++ /// Something owns the port and answers on it — whether or not it is ready.+ bool get alive => state != LocalCliProbeState.down;+ bool get ready => state == LocalCliProbeState.ready;++ @override+ String toString() =>+ 'LocalCliProbe(${state.name}${reason == null ? '' : ': $reason'})';+}++class LocalCliDiscovery {+ final AppConfig config;+ final Dio _dio;+ final LocalMachineIdentity identity;+ final Future<void> Function() _spawnCommand;++ LocalCliDiscovery({+ required this.config,+ Dio? dio,+ LocalMachineIdentity? identity,+ Future<void> Function()? spawnCommand,+ }) : identity = identity ?? LocalMachineIdentity(),+ _spawnCommand = spawnCommand ?? _defaultSpawnCommand,+ _dio =+ dio ??+ Dio(+ BaseOptions(+ connectTimeout: const Duration(milliseconds: 400),+ receiveTimeout: const Duration(milliseconds: 400),+ sendTimeout: const Duration(milliseconds: 400),+ ),+ );++ Future<String?> computerId() => identity.computerId();++ /// How long a daemon that ANSWERS is given to become ready before+ /// [ensureRunning] gives up waiting on it. Long, because the common reason+ /// is a backend handshake after a self-update restart, and the daemon keeps+ /// retrying that on its own — there is nothing to do here but wait.+ static const Duration defaultReadyTimeout = Duration(seconds: 45);++ /// Makes sure the local `harness` daemon is up and answering `/api/status`, spawning `harness+ /// start` ONLY if a probe finds nobody on the port — every local REST/WS call needs this daemon+ /// running, and unlike `harness login` it does not start on its own. A daemon that answers but is+ /// not ready yet is waited on (up to [readyTimeout]) rather than spawned over: it is already+ /// running, and a second one can only fail on the port. Returns the last probe, so a caller can+ /// tell "never came up" from "up, still connecting" — the two call for different words.+ Future<LocalCliProbe> ensureRunning({+ Duration timeout = const Duration(seconds: 15),+ Duration readyTimeout = defaultReadyTimeout,+ }) async {+ var last = await probe();+ if (last.ready) return last;+ if (!last.alive) {+ // Same reason as the supervisor: while the dial is being flashed the daemon is down on purpose+ // and its port belongs to esptool. Down is the honest answer here — it really is not running.+ if (SerialPortLease.held || SerialPortLease.heldByAnotherProcess()) {+ return last;+ }+ try {+ await _spawnCommand();+ } catch (_) {+ return last;+ }+ final deadline = DateTime.now().add(timeout);+ while (!last.alive && DateTime.now().isBefore(deadline)) {+ await Future.delayed(const Duration(milliseconds: 500));+ last = await probe();+ }+ if (last.ready || !last.alive) return last;+ }+ // Alive, not ready. Wait for it — and if it goes DOWN meanwhile (it was a daemon on its way+ // out, say), fall back to one spawn rather than sitting on a port that just went quiet.+ final deadline = DateTime.now().add(readyTimeout);+ var spawned = false;+ while (DateTime.now().isBefore(deadline)) {+ await Future.delayed(const Duration(milliseconds: 500));+ last = await probe();+ if (last.ready) return last;+ if (!last.alive) {+ if (spawned ||+ SerialPortLease.held ||+ SerialPortLease.heldByAnotherProcess()) {+ return last;+ }+ spawned = true;+ try {+ await _spawnCommand();+ } catch (_) {+ return last;+ }+ }+ }+ return last;+ }++ /// Keeps the local daemon alive for as long as the returned [Timer] runs: polls [probe] every+ /// [checkInterval] and, when the port has gone quiet, spawns `harness start` and gives it a short+ /// grace window to bind its port before concluding the attempt failed. Failed spawn attempts back+ /// off exponentially (capped) so a persistently broken environment doesn't spin — the poll itself+ /// keeps going at [checkInterval] regardless, since backoff only gates the next SPAWN, not the next+ /// probe.+ ///+ /// A daemon that ANSWERS but is not ready is left alone, however long that lasts: it is running,+ /// it is the one that has to finish, and a `harness start` beside it can only fail. That is the+ /// state a daemon sits in for the length of every self-update's backend handshake, and it is what+ /// this loop used to spawn into every few seconds.+ ///+ /// Spawning waits for [spawnAfter] consecutive quiet ticks rather than one: a self-update leaves+ /// the port unowned for a second or two between the old daemon closing it and the new one binding,+ /// and a spawn into that gap is a wasted process (the CLI's own lock refuses it), not a fix.+ ///+ /// Never surfaces ORDINARY failures to the caller (no exceptions, no+ /// [AppNotifier]-visible error); [onSignedOut] is the single exception, for the one state no+ /// amount of respawning can recover from —+ /// this runs unattended in the background for the app's whole lifetime; callers that need a+ /// one-shot "start now and tell me if it worked" should use [ensureRunning] instead. Cancel the+ /// timer to stop supervising — this never touches the daemon process itself (it self-daemonizes and+ /// must keep running after the app quits, see `harness_daemon_keep_alive` plan).+ ///+ /// [onReady] fires on every transition INTO ready — the daemon coming back after an update, or+ /// after a spawn — so the app can pick up where it left off without a click.+ /// [onSnapshot] receives each ready probe, including changing local working folders.+ Timer startSupervising({+ Duration checkInterval = const Duration(seconds: 5),+ Duration graceStep = const Duration(milliseconds: 500),+ Duration graceWindow = const Duration(seconds: 5),+ Duration initialBackoff = const Duration(seconds: 2),+ Duration maxBackoff = const Duration(seconds: 30),+ int spawnAfter = 2,+ Future<bool> Function()? stillSignedIn,+ void Function()? onSignedOut,+ void Function(LocalCliEndpoint endpoint)? onReady,+ void Function(LocalCliEndpoint endpoint)? onSnapshot,+ }) {+ var backoff = initialBackoff;+ var nextSpawnAllowedAt = DateTime.now();+ var quietTicks = 0;+ var wasReady = false;+ // A spawn+grace-window cycle can outlast `checkInterval` — without this, an overlapping tick+ // would race a second `harness start` before the first cycle's backoff state even lands (the same+ // "port already in use" failure mode a second concurrent spawn hits today).+ var cycleInFlight = false;++ void failedSpawn() {+ nextSpawnAllowedAt = DateTime.now().add(backoff);+ backoff = (backoff * 2) > maxBackoff ? maxBackoff : backoff * 2;+ }++ void observe(LocalCliProbe seen) {+ if (seen.ready) {+ backoff = initialBackoff;+ quietTicks = 0;+ onSnapshot?.call(seen.endpoint!);+ if (!wasReady) onReady?.call(seen.endpoint!);+ wasReady = true;+ return;+ }+ wasReady = false;+ if (seen.alive) quietTicks = 0;+ }++ late final Timer timer;+ timer = Timer.periodic(checkInterval, (_) {+ if (cycleInFlight) return;+ cycleInFlight = true;+ unawaited(() async {+ try {+ // The daemon is DELIBERATELY down while the dial is being flashed — it was stopped so the+ // port could be handed over. Starting it here takes the port back mid-write and kills the+ // flash, which is what made a firmware update fail at a few tens of kilobytes.+ if (SerialPortLease.held || SerialPortLease.heldByAnotherProcess()) {+ return;+ }+ final seen = await probe();+ observe(seen);+ // Running — ready or on its way. Nothing to spawn, nothing to back off from.+ if (seen.alive) return;+ quietTicks += 1;+ if (quietTicks < spawnAfter) return;+ if (DateTime.now().isBefore(nextSpawnAllowedAt)) return;+ // A daemon that signed itself OUT — its machine was deleted from another machine, or its+ // session expired — deletes its session file and exits. Respawning it is the one failure+ // this loop cannot fix: every replacement starts without a session and exits again,+ // forever, silently. Stop instead, and let the caller send the user somewhere that helps.+ //+ // Asked here and not on every tick because it costs a `harness auth status` process, and+ // the respawn point is already rate-limited by the backoff above — so this runs once per+ // spawn attempt rather than once every [checkInterval].+ if (stillSignedIn != null && !await stillSignedIn()) {+ timer.cancel();+ onSignedOut?.call();+ return;+ }+ try {+ await _spawnCommand();+ } catch (error) {+ debugPrint(+ 'LocalCliDiscovery.startSupervising: spawn failed: $error',+ );+ failedSpawn();+ return;+ }+ // The grace window ends the moment SOMETHING answers on the port — bound is what the+ // spawn was for; ready is the daemon's own business from there.+ final deadline = DateTime.now().add(graceWindow);+ while (DateTime.now().isBefore(deadline)) {+ await Future.delayed(graceStep);+ final after = await probe();+ observe(after);+ if (after.alive) return;+ }+ failedSpawn();+ } finally {+ cycleInFlight = false;+ }+ }());+ });+ return timer;+ }++ /// The ready endpoint, or null. Kept for the callers that only ever wanted+ /// "can I dial it now" — see [probe] for the three-way answer.+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>+ (await probe(expectedComputerId: expectedComputerId)).endpoint;++ Future<LocalCliProbe> probe({String? expectedComputerId}) async {+ final localComputerId = await computerId();+ if (localComputerId == null) {+ return const LocalCliProbe.down(+ 'this computer has no Harness identity yet',+ );+ }+ if (expectedComputerId != null && expectedComputerId != localComputerId) {+ return const LocalCliProbe.down('computer id mismatch');+ }+ final base = Uri.parse(config.localCliBaseUrl);+ if (base.host != '127.0.0.1' && base.host != 'localhost') {+ return const LocalCliProbe.down('the local CLI address is not loopback');+ }+ final Map<String, dynamic>? body;+ try {+ final response = await _dio.getUri<Map<String, dynamic>>(+ base.resolve('/api/status'),+ );+ body = response.data;+ } on DioException catch (error) {+ switch (error.type) {+ // Nobody on the port. The one case where spawning helps — and still+ // not on the first sighting: an update handoff leaves the port unowned+ // for a second or two between the old daemon closing it and the new+ // one binding, so the supervisor waits for a SECOND quiet tick (see+ // [startSupervising]'s `spawnAfter`). A single `down` is not proof.+ case DioExceptionType.connectionError:+ case DioExceptionType.connectionTimeout:+ return const LocalCliProbe.down('connection refused');+ // Something owns the port — a daemon mid-boot, a foreign process, a+ // daemon too busy to answer in time. Spawning over it can only fail.+ case DioExceptionType.badResponse:+ return LocalCliProbe.notReady(+ 'http ${error.response?.statusCode ?? '?'} from the control port',+ );+ case DioExceptionType.receiveTimeout:+ case DioExceptionType.sendTimeout:+ return const LocalCliProbe.notReady('timed out answering');+ case DioExceptionType.badCertificate:+ case DioExceptionType.cancel:+ case DioExceptionType.transformTimeout:+ case DioExceptionType.unknown:+ // A refused socket surfaces as `unknown` wrapping the SocketException+ // on older adapters — still nobody on the port. A socket that was+ // ACCEPTED and then dropped (an HttpException, "connection closed+ // while receiving") is not: something answered, then went away —+ // the old daemon mid-close, say — and that reads as alive.+ if (error.error is SocketException) {+ return const LocalCliProbe.down('connection refused');+ }+ return LocalCliProbe.notReady(error.message ?? 'unexpected answer');+ }+ } catch (error) {+ return LocalCliProbe.notReady('unexpected answer: $error');+ }+ final pid = body?['pid'] is int ? body!['pid'] as int : null;+ final version = body?['version'] is String+ ? body!['version'] as String+ : null;+ if (body == null) {+ return const LocalCliProbe.notReady('not a harness status');+ }+ // New CLIs expose the initial terminal scan explicitly. A missing field means an older CLI and+ // remains accepted for backward compatibility; false means the daemon is alive but not ready to+ // publish an authoritative empty/non-empty agent list yet.+ if (body['discoveryReady'] == false) {+ return LocalCliProbe.notReady(+ 'still scanning for agents',+ pid: pid,+ version: version,+ );+ }+ // `discoveryReady` is local-only (tmux/agent-process scanning) and can go true well before the+ // daemon has actually connected to the backend — `/api/machines` and friends proxy straight to+ // it, so treating discovery-ready as "ready" raced the handshake and surfaced as a bogus 30s+ // receive-timeout right after boot. `connected` is the daemon's own backend-socket state+ // (missing field ⇒ older CLI ⇒ accepted, same idiom as above).+ if (body['connected'] == false) {+ return LocalCliProbe.notReady(+ 'not connected to the backend yet',+ pid: pid,+ version: version,+ );+ }+ final advertisedComputerId = _normalizeComputerId(body['computerId']);+ final advertised = body['localWs'];+ if (advertisedComputerId != localComputerId) {+ return LocalCliProbe.notReady(+ 'a daemon for a different computer',+ pid: pid,+ version: version,+ );+ }+ if (advertised is! Map) {+ return LocalCliProbe.notReady(+ 'not a harness status',+ pid: pid,+ version: version,+ );+ }+ final localWs = Map<String, dynamic>.from(advertised);+ final path = localWs['path'];+ final protocolVersion = localWs['protocolVersion'];+ final terminalProtocolVersion = localWs['terminalProtocolVersion'];+ if (path is! String ||+ !path.startsWith('/') ||+ protocolVersion != localWsProtocolVersion ||+ terminalProtocolVersion != localTerminalProtocolVersion ||+ localWs['e2ee'] != false) {+ return LocalCliProbe.notReady(+ 'protocol mismatch',+ pid: pid,+ version: version,+ );+ }+ return LocalCliProbe.ready(+ LocalCliEndpoint(+ computerId: localComputerId,+ wsUri: base+ .resolve(path)+ .replace(scheme: base.scheme == 'https' ? 'wss' : 'ws'),+ protocolVersion: protocolVersion as int,+ terminalProtocolVersion: terminalProtocolVersion as int,+ agentProjects: _localAgentProjects(+ body['sessions'],+ identity.environment,+ ),+ ),+ pid: pid,+ version: version,+ );+ }+}++Map<String, AgentProject> _localAgentProjects(+ Object? sessions,+ Map<String, String> environment,+) {+ if (sessions is! List) return const {};+ final projects = <String, AgentProject>{};+ final home = environment['HOME'] ?? environment['USERPROFILE'];+ for (final session in sessions) {+ if (session is! Map || session['id'] is! String) continue;+ final id = session['id'] as String;+ final rawCwd = session['cwd'];+ if (id.isEmpty ||+ rawCwd is! String ||+ rawCwd.isEmpty ||+ rawCwd.length > 4096 ||+ RegExp(r'[\x00-\x1f\x7f]').hasMatch(rawCwd)) {+ continue;+ }+ String cwd = rawCwd;+ if (cwd == '~' ||+ cwd.startsWith('~/') ||+ (Platform.isWindows && cwd.startsWith('~\\'))) {+ if (home == null || home.isEmpty) continue;+ cwd = '$home${cwd.substring(1)}';+ }+ final absolute = Platform.isWindows+ ? RegExp(r'^[A-Za-z]:[\\/]|^\\\\').hasMatch(cwd)+ : cwd.startsWith('/');+ if (!absolute) continue;+ try {+ cwd = File(cwd).uri.normalizePath().toFilePath();+ // Directory paths in the status may carry a trailing separator.+ final separator = Platform.pathSeparator;+ while (cwd.length > 1 &&+ cwd.endsWith(separator) &&+ !(Platform.isWindows && RegExp(r'^[A-Za-z]:\\$').hasMatch(cwd))) {+ cwd = cwd.substring(0, cwd.length - 1);+ }+ final parts = cwd.split(separator).where((part) => part.isNotEmpty);+ final project = AgentProject.fromJson({+ 'name': parts.isEmpty ? cwd : parts.last,+ 'cwd': cwd,+ });+ if (project != null) projects[id] = project;+ } on FormatException {+ // A malformed status row must not prevent discovery of the daemon.+ }+ }+ return Map.unmodifiable(projects);+}++String? _normalizeComputerId(Object? raw) {+ if (raw is! String) return null;+ final value = raw.trim().toLowerCase().replaceAll('-', '');+ return RegExp(r'^[a-f0-9]{16,64}$').hasMatch(value) ? value : null;+}diff --git a/mobile/lib/ws/relay_codec.dart b/mobile/lib/ws/relay_codec.dartnew file mode 100644index 000000000..9dd854449--- /dev/null+++ b/mobile/lib/ws/relay_codec.dart@@ -0,0 +1,39 @@+import 'dart:typed_data';++/// What a relay [WsConn] needs from an end-to-end session with the machine behind it.+///+/// Where the harness CLI is the transport (macOS, Linux) nothing does — the CLI already opened the+/// session and hands over plaintext — so only a viewer build supplies one+/// (`viewer/e2ee_relay_codec.dart`). The codec speaks the loopback formats on the app's side+/// (plain JSON payloads, HTRL binary frames), so nothing above [WsConn] can tell the two apart.+abstract interface class RelayCodec {+ /// Sent once the relay acks `machine_select`.+ Map<String, dynamic> helloFrame();++ /// True once the machine's `e2e_welcome` has made the session usable.+ Future<bool> handleWelcome(Map<String, dynamic> payload);++ bool handleRekey(Map<String, dynamic> payload);++ /// The machine's `features.terminalP2p` from its welcome — 0 when it offers no+ /// P2P terminal channel (or before the welcome).+ int get terminalP2pVersion;++ /// The frame as it may cross the relay. Null when it must travel sealed and the session is not+ /// up yet — it must then not go at all: sent in the clear it leaks, and a terminal frame is+ /// rejected by the relay outright.+ Map<String, dynamic>? encodeFrame(Map<String, dynamic> frame);++ /// Null means drop it: stale, replayed or not authentic.+ Map<String, dynamic>? decodeFrame(Map<String, dynamic> frame);++ /// A loopback (HTRL) frame, sealed for the relay; null when it cannot be.+ Uint8List? encodeBinary(Uint8List localFrame);++ /// A relay frame, opened back into loopback (HTRL) form; null means drop it.+ Uint8List? decodeBinary(Uint8List wireFrame);+}++/// A fresh session for each connection to [machineId]; null when this device has no link to it —+/// the machine could only answer `e2e_denied`, so there is nothing worth dialing.+typedef RelayCodecFactory = Future<RelayCodec?> Function(String machineId);diff --git a/mobile/lib/ws/terminal_transport_plugin.dart b/mobile/lib/ws/terminal_transport_plugin.dartnew file mode 100644index 000000000..0f1fac35c--- /dev/null+++ b/mobile/lib/ws/terminal_transport_plugin.dart@@ -0,0 +1,91 @@+import 'dart:typed_data';++import 'relay_codec.dart';++/// Which wire a frame is forced onto, when the plugin asks for one rather than+/// leaving the choice to its own routing table.+enum TransportVia { ws, plugin }++/// What a [TerminalTransportPlugin] needs from the relay [WsConn] it rides on.+///+/// Every method here lands the plugin's traffic on the SAME FIFOs the socket's own+/// frames use — the outbound one so the E2EE counters are taken in send order+/// whichever wire carries a frame, and the inbound one so replay-window commits and+/// `onEvent` ordering stay serial with what arrives over the WebSocket.+abstract interface class TerminalTransportHost {+ /// The connection's E2EE session, minted per connect.+ RelayCodec get codec;++ /// A plain `{type, payload}` frame of the plugin's own, sealed by the codec where+ /// its type requires it and queued on the outbound FIFO like any other. Without+ /// [force] it is routed the ordinary way (offered back to [TerminalTransportPlugin.sendJson]);+ /// with one, that wire is used. False when it could not go at all.+ Future<bool> send(Map<String, dynamic> frame, {TransportVia? force});++ /// Runs [task] on the inbound FIFO, after everything already queued.+ void enqueueInbound(Future<void> Function() task);++ /// A decoded `{type, payload}` frame, delivered as if it had arrived over the+ /// WebSocket: request/reply matching first, `onEvent` otherwise.+ Future<void> dispatch(Map<String, dynamic> plain);++ /// A loopback (HTRL) binary frame, delivered as if it had arrived over the WebSocket.+ Future<void> deliverBinary(Uint8List localFrame);+}++/// A second wire beside the relay WebSocket — the phone's WebRTC data channel to the+/// machine — that a relay [WsConn] offers every terminal frame to before falling back+/// to the socket. Pure interface: nothing in the shared package knows what the wire+/// is, only where in the socket's life it gets a say.+///+/// The harness CLI plays this role for the desktop (`remoteRelay.ts`); a viewer build+/// that wants the same plugs one of these in through `ViewerServices`.+abstract interface class TerminalTransportPlugin {+ /// The relay's ack to `machine_select` — before the E2EE hello goes out. The+ /// payload carries the backend's transport policy (`p2p`), if any.+ void onConnectedAck(Map<String, dynamic> payload);++ /// The E2EE session is up: `codec.terminalP2pVersion` is now known.+ void onSessionReady();++ /// True for a frame type the plugin owns outright (signaling); such a frame goes+ /// to [handleInbound] and never reaches `onEvent`.+ bool consumesInbound(String type);+ Future<void> handleInbound(String type, Map<String, dynamic> payload);++ /// A decoded WebSocket frame, AFTER it was dispatched to the app. Awaited on the+ /// inbound FIFO, so anything the plugin dispatches from here lands in order.+ Future<void> observeWsFrame(Map<String, dynamic> plain);++ /// A decoded WebSocket binary frame (HTRL), BEFORE it is delivered to the app.+ Future<void> observeWsBinary(Uint8List localFrame);++ /// Called before a `terminal_open` is queued: the plugin may wait (bounded) for its+ /// wire to be ready. True means the open should ride the plugin's wire.+ Future<bool> prepareOpen(String requestId);++ /// Inside the outbound FIFO, once the codec sealed the frame. True: the plugin took+ /// it — sent on its wire, or (a frame [force]d onto a wire that just went away)+ /// deliberately dropped. False: the socket sends it — and the plugin has already+ /// recorded whatever that means for its routing (a stream it thought was its own, say).+ bool sendJson(+ String type,+ Map<String, dynamic> payload,+ String sealedJson, {+ required bool openViaPlugin,+ TransportVia? force,+ });++ /// Inside the outbound FIFO, once the codec sealed the frame. Same contract as+ /// [sendJson]; may wait briefly for backpressure to clear.+ Future<bool> sendBinary(Uint8List localFrame, Uint8List sealedFrame);++ /// The socket is gone (closed, redialing, or refused). Tear the wire down.+ void dispose({bool notifyPeer = false});+}++/// One plugin per relay connection, built once the codec exists.+typedef TerminalTransportPluginFactory = TerminalTransportPlugin Function(+ TerminalTransportHost host,+ String machineId,+);diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dartnew file mode 100644index 000000000..e48e2e6ef--- /dev/null+++ b/mobile/lib/ws/ws_conn.dart@@ -0,0 +1,855 @@+import 'dart:async';+import 'dart:convert';+import 'dart:math';++import 'package:flutter/foundation.dart';+import 'package:web_socket_channel/web_socket_channel.dart';++import '../logging/app_log.dart';+import '../logging/redact.dart';+import '../core/models.dart';+import 'relay_codec.dart';+import 'terminal_transport_plugin.dart';++typedef AccessTokenProvider = Future<String> Function(+ bool forceRefresh,+ String? failedToken,+);++enum WsTransportKind { cloudE2ee, localPlaintext }++/// 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+/// "the peer answered with a failure."+class WsRequestTimeout implements Exception {+ final String type;+ const WsRequestTimeout(this.type);+ @override+ String toString() => 'WS request timed out: $type';+}++/// The peer ANSWERED a `request()` with an explicit `{error: ...}` — a refusal it meant, as opposed+/// to [WsRequestTimeout]'s silence.+///+/// The code travels as a field rather than only inside the message because that is what callers act+/// on: `AGENT_BUSY` becomes "move it when the turn finishes", `UNSUPPORTED` becomes "update the CLI+/// on this machine". Before this existed every refusal arrived as a bare `Exception` whose only+/// content was its own `toString()`, so the mapping in `AppNotifier` sat behind an `if` on a reply+/// that had already thrown and could never run — the user got the wire code.+///+/// [toString] is the sentence this used to be thrown with, so a call site that only prints it is+/// unchanged.+class WsRequestFailure implements Exception {+ const WsRequestFailure({+ required this.responseType,+ required this.code,+ this.detail,+ });++ /// The frame that carried the refusal — `agent_create_result`, say.+ final String responseType;++ /// The peer's own error code.+ final String code;++ /// The underlying cause behind the code, when the peer sends one — the tmux message behind+ /// SPAWN_FAILED. Already reads as a sentence; prefer it to anything rewritten from [code].+ final String? detail;++ @override+ String toString() => detail == null || detail!.isEmpty+ ? '$responseType: $code'+ : '$responseType: $code — $detail';+}++/// One SSO-authenticated, machine-scoped connection to `/api/web-ws`.+class WsConn {+ 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.+ 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+ /// as they are, which is right for the local transport and the dev fixture.+ final RelayCodecFactory? relayCodecs;++ /// A second wire beside the relay socket (a viewer's WebRTC data channel to the+ /// machine), built per connect once the codec exists. Null — the desktop, the+ /// local transport, the dev fixture — means every frame rides the socket.+ final TerminalTransportPluginFactory? transportPlugins;++ Future<Map<String, dynamic>> Function(+ String type,+ Map<String, dynamic> payload,+ )?+ onOutgoing;+ Future<Map<String, dynamic>?> Function(Map<String, dynamic> frame)?+ onE2eeFrame;+ Future<void> Function(Uint8List frame)? onBinaryFrame;++ final FutureOr<void> Function(Map<String, dynamic> event) onEvent;+ final void Function(ConnectionStatus status) onStatus;++ WebSocketChannel? _channel;+ RelayCodec? _codec;+ TerminalTransportPlugin? _plugin;+ StreamSubscription? _sub;+ bool _closing = false;+ bool _connecting = false;+ bool _ready = false;+ int _attempt = 0;+ Timer? _reconnectTimer;+ String? _tokenUsed;+ bool _forceRelayReconnect = false;+ final _pending = <String, _PendingRpc>{};+ final _readinessWaiters = <Completer<void>>{};+ final _queue = <Map<String, dynamic>>[];+ Future<void> _outboundTail = Future<void>.value();+ Future<void> _inboundTail = Future<void>.value();++ bool get isReady => _ready && _channel != null;++ /// Wait for this machine's handshake without queuing a request or changing+ /// its timeout. Callers can then start independent RPCs with their own budgets.+ Future<void> waitUntilReady({required Duration timeout}) {+ if (isReady) return Future<void>.value();+ if (_closing) return Future<void>.error(StateError('WS closed'));+ final ready = Completer<void>();+ _readinessWaiters.add(ready);+ return ready.future+ .timeout(+ timeout,+ onTimeout: () => throw const WsRequestTimeout('machine_select'),+ )+ .whenComplete(() => _readinessWaiters.remove(ready));+ }++ void _settleReadiness([String? failure]) {+ final waiters = _readinessWaiters.toList();+ _readinessWaiters.clear();+ for (final waiter in waiters) {+ if (failure == null) {+ waiter.complete();+ } else {+ waiter.completeError(StateError(failure));+ }+ }+ }++ /// 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';++ WsConn({+ required this.wsBaseUrl,+ required this.autonomousEnv,+ required this.machineId,+ required this.accessTokenProvider,+ required this.onAuthFailure,+ this.onLocalFailure,+ required this.onEvent,+ required this.onStatus,+ this.transportKind = WsTransportKind.cloudE2ee,+ this.localWsUri,+ this.localApiKey,+ this.localProtocolVersion = 1,+ this.relayCodecs,+ this.transportPlugins,+ });++ Future<void> connect() async {+ if (_closing || _connecting) return;+ _connecting = true;+ _ready = false;+ onStatus(+ _attempt == 0+ ? ConnectionStatus.connecting+ : ConnectionStatus.reconnecting,+ );+ try {+ final token = isLocal ? null : await accessTokenProvider(false, null);+ if (!isLocal && (token == null || token.isEmpty)) {+ throw StateError('WebSocket credential is missing');+ }+ if (_closing) return;+ _tokenUsed = token;+ final codecs = isLocal ? null : relayCodecs;+ if (codecs != null) {+ final codec = await codecs(machineId);+ if (_closing) return;+ if (codec == null) {+ _refusePeer('NO_PEER_LINK');+ return;+ }+ _codec = codec;+ // A dial that failed past this point left one behind; this connect owns a new one.+ _disposePlugin();+ 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 = isLocal+ ? WebSocketChannel.connect(uri)+ : WebSocketChannel.connect(uri, protocols: [token!]);+ _channel = channel;+ await channel.ready;+ if (_closing || !identical(_channel, channel)) {+ await channel.sink.close();+ return;+ }+ _sub = channel.stream.listen(+ _onRaw,+ onDone: () => _onDone(channel),+ onError: (_) => _onDone(channel),+ );+ final forceRelayReconnect = _forceRelayReconnect;+ _forceRelayReconnect = false;+ await sendFrame({+ 'type': 'machine_select',+ 'payload': {+ 'machineId': machineId,+ if (isLocal) 'localProtocolVersion': localProtocolVersion,+ if (isLocal && forceRelayReconnect) 'forceReconnect': true,+ },+ });+ } catch (_) {+ if (!_closing) _scheduleReconnect();+ } finally {+ _connecting = false;+ }+ }++ void _onRaw(dynamic raw) {+ final codec = _codec;+ if (raw is List<int>) {+ final bytes = Uint8List.fromList(raw);+ _inboundTail = _inboundTail+ .then((_) async {+ final local = codec == null ? bytes : codec.decodeBinary(bytes);+ if (local == null) return;+ await _plugin?.observeWsBinary(local);+ await onBinaryFrame?.call(local);+ })+ .catchError((_) {+ // Binary E2EE/session code owns recovery for bad frames.+ });+ return;+ }+ final Map<String, dynamic> message;+ try {+ message = jsonDecode(raw as String) as Map<String, dynamic>;+ } catch (_) {+ return;+ }+ if (codec != null) {+ _inboundTail = _inboundTail+ .then((_) => _onRelayFrame(codec, message))+ .catchError((_) {+ // Keep the FIFO alive: a frame that will not open is dropped, never dispatched.+ });+ return;+ }+ final type = message['type'] as String? ?? '';+ final payload = (message['payload'] as Map<String, dynamic>?) ?? {};++ if (type == 'connected') {+ if (payload['machineId'] == machineId) _markReady();+ return;+ }+ final normalized = <String, dynamic>{...message, 'payload': payload};+ _inboundTail = _inboundTail+ .then((_) async {+ final isE2ee =+ type.startsWith('e2e_') ||+ (payload.containsKey('__e2e') && payload['__e2e'] is Map);+ if (isE2ee && onE2eeFrame != null) {+ await _handleE2ee(normalized);+ } else {+ await _dispatch(normalized);+ }+ })+ .catchError((_) {+ // Keep the FIFO alive. E2EE/session code owns recovery for bad frames.+ });+ }++ void _markReady() {+ _ready = true;+ _attempt = 0;+ onStatus(ConnectionStatus.connected);+ _flushQueue();+ _settleReadiness();+ }++ /// A frame on a relay connection whose E2EE session this app holds: relayClient.ts's dial+ /// handshake, then open-and-dispatch. Nothing is ready — and nothing queued goes out — until the+ /// machine's welcome proves it holds the identity this device pinned for it.+ Future<void> _onRelayFrame(+ RelayCodec codec,+ Map<String, dynamic> message,+ ) async {+ final payload = (message['payload'] as Map<String, dynamic>?) ?? {};+ switch (message['type']) {+ case 'connected':+ // The socket's first `connected` answers the socket itself (it names the user, not a+ // machine); only the select's own ack starts the handshake.+ if (payload['machineId'] == machineId) {+ // The policy rides the ack; the plugin must have it before the welcome+ // that decides whether to act on it.+ _plugin?.onConnectedAck(payload);+ _channel?.sink.add(jsonEncode(codec.helloFrame()));+ }+ return;+ case 'e2e_welcome':+ if (await codec.handleWelcome(payload)) {+ _markReady();+ _plugin?.onSessionReady();+ } else {+ _refusePeer('E2EE_WELCOME_INVALID');+ }+ return;+ case 'e2e_denied':+ _refusePeer('E2E_DENIED');+ return;+ case 'e2e_rekey':+ codec.handleRekey(payload);+ return;+ }+ final clear = codec.decodeFrame(message);+ if (clear == null) return;+ final plain = <String, dynamic>{+ ...clear,+ 'payload': (clear['payload'] as Map<String, dynamic>?) ?? {},+ };+ final plugin = _plugin;+ final type = plain['type'];+ if (plugin != null && type is String && plugin.consumesInbound(type)) {+ await plugin.handleInbound(+ type,+ plain['payload'] as Map<String, dynamic>,+ );+ return;+ }+ await _dispatch(plain);+ // After, not before: for `terminal_ready` the session learns its streamId from+ // the frame itself, and anything the plugin derives from it (its own+ // `terminal_link_mode`) must land once that has happened.+ await _plugin?.observeWsFrame(plain);+ }++ /// The machine is reachable but this device may not talk to it: never linked, the link revoked+ /// on its side, or a welcome that did not prove the pinned identity. No retry can fix any of the+ /// three — only a link can — so this stops and says so the way the CLI's own relay does, with+ /// 4404.+ void _refusePeer(String reason) {+ _closing = true;+ _ready = false;+ _disposePlugin();+ // 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(4404, reason);+ onStatus(ConnectionStatus.disconnected);+ unawaited(_channel?.sink.close());+ }++ Future<void> _dispatch(Map<String, dynamic> message) async {+ final payload = (message['payload'] as Map<String, dynamic>?) ?? {};+ final requestId = payload['requestId'];+ if (requestId is String && _pending.containsKey(requestId)) {+ final pending = _pending.remove(requestId)!;+ pending.timer.cancel();+ if (payload['error'] != null) {+ // `detail`, when the peer sends one, is the underlying cause behind the code — the tmux+ // message behind SPAWN_FAILED, say. Without it an error code alone sends the user to a log file+ // on a machine that is not the one in front of them.+ final detail = payload['detail'];+ pending.completer.completeError(+ WsRequestFailure(+ responseType: message['type'] as String? ?? 'unknown_result',+ code: '${payload['error']}',+ detail: detail is String && detail.isNotEmpty ? detail : null,+ ),+ );+ } else {+ pending.completer.complete(payload);+ }+ return;+ }+ final eventType = message['type'];+ if (eventType is String && _worthLogging(eventType)) {+ appLog.debug('ws', '↓ $eventType ${summariseForLog(payload)}');+ }+ await onEvent({...message, 'payload': payload});+ }++ Future<void> _handleE2ee(Map<String, dynamic> frame) async {+ final decrypted = await onE2eeFrame!(frame);+ if (decrypted != null) await _dispatch(decrypted);+ }++ /// Frame types deliberately kept OUT of the log.+ ///+ /// Terminal traffic is the overwhelming majority of what crosses this socket+ /// and none of it is diagnostic — it is somebody's screen. Logging it would+ /// bury every frame that matters, cost an fsync per keystroke, and write the+ /// contents of their editor to disk. The hardware dial's events are dropped+ /// for the volume alone.+ static const _unlogged = {+ // File paths and media contents are user data, not frame diagnostics.+ 'agent_read_file',+ 'agent_read_file_result',+ 'terminal_output',+ 'terminal_input',+ 'terminal_resize',+ 'terminal_sync',+ 'dial_scroll',+ 'dial_focus',+ 'ping',+ 'pong',+ };++ static bool _worthLogging(String type) => !_unlogged.contains(type);++ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) {+ final requestId = _newRequestId();+ final completer = Completer<Map<String, dynamic>>();+ final timer = Timer(timeout, () {+ _pending.remove(requestId);+ _queue.removeWhere(+ (f) =>+ (f['payload'] as Map<String, dynamic>?)?['requestId'] == requestId,+ );+ if (!completer.isCompleted) {+ completer.completeError(WsRequestTimeout(type));+ }+ });+ _pending[requestId] = _PendingRpc(completer, timer);+ if (_worthLogging(type)) {+ appLog.debug('ws', '→ $type ${summariseForLog(payload)}');+ // A second listener on the same future purely to record how it ended. It+ // handles its own error, so the caller's handling is unchanged and nothing+ // becomes an unhandled rejection.+ completer.future.then(+ (value) => appLog.debug('ws', '← $type ${summariseForLog(value)}'),+ onError: (Object error) =>+ appLog.warn('ws', '← $type failed', error: error),+ );+ }+ final frame = {+ 'type': type,+ 'payload': {...payload, 'requestId': requestId},+ };+ if (_ready) {+ unawaited(_sendRpcFrame(frame, requestId, type));+ } else {+ _queue.add(frame);+ }+ return completer.future;+ }++ void sendRaw(String type, Map<String, dynamic> payload) =>+ unawaited(sendFrame({'type': type, 'payload': payload}));++ /// Terminal input is best-effort: it is never queued across reconnect and+ /// the caller gets false if the socket stopped being ready before send.+ Future<bool> sendTerminalFrame(+ String type,+ Map<String, dynamic> payload,+ ) async {+ // Outside the FIFO on purpose: the plugin may wait a bounded while for its wire+ // before an open, and that wait must not hold up other panes' input.+ var openViaPlugin = false;+ final plugin = _plugin;+ final requestId = payload['requestId'];+ // Not worth the wait when the frame cannot go anyway.+ if (plugin != null &&+ isReady &&+ type == 'terminal_open' &&+ requestId is String) {+ openViaPlugin = await plugin.prepareOpen(requestId);+ }+ return _enqueueFrame(+ {'type': type, 'payload': payload},+ requireReady: true,+ openViaPlugin: openViaPlugin,+ );+ }++ Future<bool> sendTerminalBinary(Uint8List bytes) {+ final completer = Completer<bool>();+ _outboundTail = _outboundTail+ .then((_) async {+ if (!isReady) {+ completer.complete(false);+ return;+ }+ final channel = _channel;+ if (channel == null) {+ completer.complete(false);+ return;+ }+ try {+ // Sealed here, inside the outbound FIFO, so frames take their counters in send order.+ final codec = _codec;+ final wire = codec == null ? bytes : codec.encodeBinary(bytes);+ if (wire == null) {+ completer.complete(false);+ return;+ }+ final plugin = _plugin;+ if (plugin != null && await plugin.sendBinary(bytes, wire)) {+ completer.complete(true);+ return;+ }+ channel.sink.add(wire);+ completer.complete(true);+ } catch (_) {+ completer.complete(false);+ }+ })+ .catchError((_) {+ if (!completer.isCompleted) completer.complete(false);+ });+ return completer.future;+ }++ Future<void> sendFrame(Map<String, dynamic> frame) async {+ await _enqueueFrame(frame);+ }++ Future<bool> _enqueueFrame(+ Map<String, dynamic> frame, {+ bool requireReady = false,+ bool openViaPlugin = false,+ TransportVia? force,+ void Function(Object error)? onFailure,+ }) {+ final completer = Completer<bool>();+ _outboundTail = _outboundTail+ .then((_) async {+ if (requireReady && !isReady) {+ completer.complete(false);+ return;+ }+ try {+ await _sendFrameNow(+ frame,+ openViaPlugin: openViaPlugin,+ force: force,+ );+ completer.complete(true);+ } catch (error) {+ onFailure?.call(error);+ completer.complete(false);+ }+ })+ .catchError((error) {+ onFailure?.call(error);+ if (!completer.isCompleted) completer.complete(false);+ });+ return completer.future;+ }++ Future<void> _sendRpcFrame(+ Map<String, dynamic> frame,+ String requestId,+ String type,+ ) async {+ Object? failure;+ final sent = await _enqueueFrame(+ frame,+ onFailure: (error) => failure = error,+ );+ if (sent) return;+ final pending = _pending.remove(requestId);+ if (pending == null) return;+ pending.timer.cancel();+ if (!pending.completer.isCompleted) {+ pending.completer.completeError(+ failure ?? StateError('WS request could not be sent: $type'),+ );+ }+ }++ Future<void> _sendFrameNow(+ Map<String, dynamic> frame, {+ bool openViaPlugin = false,+ TransportVia? force,+ }) async {+ final type = frame['type'] as String;+ var payload = (frame['payload'] as Map<String, dynamic>?) ?? {};+ if (onOutgoing != null) payload = await onOutgoing!(type, payload);+ final channel = _channel;+ if (channel == null) throw StateError('WS is not connected');+ final out = <String, dynamic>{'type': type, 'payload': payload};+ final codec = _codec;+ final wire = codec == null ? out : codec.encodeFrame(out);+ if (wire == null) throw StateError('E2EE session is not ready for $type');+ final encoded = jsonEncode(wire);+ // Sealed first, then offered: the counter is taken in send order whichever+ // wire ends up carrying the frame, which is what the peer's replay window needs.+ // Only once the session is up: nothing before that (the select, the hello) is+ // the plugin's to route.+ final plugin = _plugin;+ if (plugin != null &&+ _ready &&+ plugin.sendJson(+ type,+ payload,+ encoded,+ openViaPlugin: openViaPlugin,+ force: force,+ )) {+ return;+ }+ channel.sink.add(encoded);+ }++ void _flushQueue() {+ final queued = List<Map<String, dynamic>>.from(_queue);+ _queue.clear();+ for (final frame in queued) {+ final payload = (frame['payload'] as Map<String, dynamic>?) ?? const {};+ final requestId = payload['requestId'];+ if (requestId is String && _pending.containsKey(requestId)) {+ unawaited(+ _sendRpcFrame(+ frame,+ requestId,+ frame['type'] as String? ?? 'request',+ ),+ );+ } else {+ unawaited(sendFrame(frame));+ }+ }+ }++ void _onDone(WebSocketChannel channel) {+ if (!identical(_channel, channel)) return;+ _channel = null;+ _sub = null;+ _codec = null;+ _disposePlugin();+ _ready = false;+ _rejectPending('WS disconnected');+ if (_closing) {+ onStatus(ConnectionStatus.disconnected);+ 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;+ }+ if (code == 4403) {+ _closing = true;+ onStatus(ConnectionStatus.disconnected);+ onAuthFailure('SSO environment does not match this backend');+ return;+ }+ _scheduleReconnect();+ }++ Future<void> _refreshAndReconnect() async {+ onStatus(ConnectionStatus.reconnecting);+ try {+ await accessTokenProvider(true, _tokenUsed);+ if (!_closing) await connect();+ } catch (_) {+ _closing = true;+ onStatus(ConnectionStatus.disconnected);+ onAuthFailure('Your SSO session expired. Please sign in again.');+ }+ }++ void _scheduleReconnect() {+ if (_closing) return;+ _attempt++;+ onStatus(ConnectionStatus.reconnecting);+ _reconnectTimer?.cancel();+ final exponent = min(max(_attempt - 1, 0), 5);+ final delay = Duration(milliseconds: min(30000, 1000 * (1 << exponent)));+ _reconnectTimer = Timer(delay, connect);+ }++ void _rejectPending(String reason) {+ _settleReadiness(reason);+ for (final pending in _pending.values) {+ pending.timer.cancel();+ if (!pending.completer.isCompleted) {+ pending.completer.completeError(Exception(reason));+ }+ }+ _pending.clear();+ _queue.clear();+ }++ Future<void> close() async {+ _closing = true;+ _ready = false;+ _codec = null;+ _disposePlugin();+ _reconnectTimer?.cancel();+ _reconnectTimer = null;+ _rejectPending('WS closed');+ final sub = _sub;+ _sub = null;+ await sub?.cancel();+ final channel = _channel;+ _channel = null;+ await channel?.sink.close();+ onStatus(ConnectionStatus.disconnected);+ }++ /// Forces a fresh upstream relay dial for this machine — the transport itself can stay technically+ /// "connected" (ping/pong healthy) while the *application*-level session behind it is dead, e.g. the+ /// relayed machine's own Harness process restarted and dropped its in-memory E2EE session state; no+ /// close event ever fires for that, so nothing else would ever redial. Callers reach for this after+ /// observing a live RPC time out on an otherwise "connected" machine. Closes the local connection and+ /// immediately reconnects with a `forceReconnect` hint so the CLI daemon drops its cached relay entry+ /// instead of reusing it.+ 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;+ _reconnectTimer?.cancel();+ _ready = false;+ _codec = null;+ _disposePlugin();+ _rejectPending('forcing relay reconnect');+ final sub = _sub;+ _sub = null;+ await sub?.cancel();+ final channel = _channel;+ _channel = null;+ if (channel != null) {+ try {+ await channel.sink.close();+ } catch (_) {+ /* already gone */+ }+ }+ _attempt = 0;+ await connect();+ }++ /// Drops only the live transport so integration tests can exercise the real+ /// reconnect path. Unlike [close], this deliberately leaves reconnect+ /// enabled and does not queue terminal input while the socket is down.+ @visibleForTesting+ Future<void> debugDropTransport() async {+ final channel = _channel;+ if (channel == null) throw StateError('WS transport is not connected');+ // 1012 is a server-only close code and Dart correctly rejects clients that+ // try to send it. Use the application/private range so this still drives+ // the real onDone -> reconnect path without pretending to be the server.+ await channel.sink.close(4000, 'integration test transport drop');+ }++ void _disposePlugin() {+ final plugin = _plugin;+ _plugin = null;+ plugin?.dispose();+ }++ static String _newRequestId() {+ final random = Random.secure();+ final bytes = List<int>.generate(16, (_) => random.nextInt(256));+ return 'dsk_${bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join()}';+ }+}++/// The connection as its plugin sees it — see [TerminalTransportHost].+class _PluginHost implements TerminalTransportHost {+ _PluginHost(this._conn);+ final WsConn _conn;++ @override+ RelayCodec get codec {+ final codec = _conn._codec;+ if (codec == null) throw StateError('relay session is gone');+ return codec;+ }++ @override+ Future<bool> send(Map<String, dynamic> frame, {TransportVia? force}) =>+ _conn._enqueueFrame(frame, requireReady: true, force: force);++ @override+ void enqueueInbound(Future<void> Function() task) {+ _conn._inboundTail = _conn._inboundTail.then((_) => task()).catchError((_) {+ // Keep the FIFO alive, as the socket's own handlers do.+ });+ }++ @override+ Future<void> dispatch(Map<String, dynamic> plain) => _conn._dispatch({+ ...plain,+ 'payload': (plain['payload'] as Map<String, dynamic>?) ?? {},+ });++ @override+ Future<void> deliverBinary(Uint8List localFrame) async {+ await _conn.onBinaryFrame?.call(localFrame);+ }+}++class _PendingRpc {+ final Completer<Map<String, dynamic>> completer;+ final Timer timer;+ _PendingRpc(this.completer, this.timer);+}diff --git a/mobile/lib/ws/ws_pool.dart b/mobile/lib/ws/ws_pool.dartnew file mode 100644index 000000000..e45bfde0f--- /dev/null+++ b/mobile/lib/ws/ws_pool.dart@@ -0,0 +1,101 @@+import 'dart:async';++import 'relay_codec.dart';+import 'terminal_transport_plugin.dart';++import '../core/models.dart';+import 'ws_conn.dart';++/// Owns one SSO-authenticated [WsConn] per machine.+class WsPool {+ final String wsBaseUrl;+ final String autonomousEnv;++ /// Handed to every relay connection — a viewer build's E2EE sessions (see [RelayCodec]).+ final RelayCodecFactory? relayCodecs;++ /// Handed to every relay connection beside [relayCodecs] — a viewer build's second+ /// wire to the machine (see [TerminalTransportPlugin]).+ final TerminalTransportPluginFactory? transportPlugins;+ final AccessTokenProvider accessTokenProvider;+ final void Function(String message) onAuthFailure;+ final void Function(String machineId, int code, String reason)?+ onLocalFailure;+ final FutureOr<void> Function(String machineId, Map<String, dynamic> event)+ onEvent;+ final void Function(String machineId, ConnectionStatus status) onStatus;++ final Map<String, WsConn> _conns = {};++ WsPool({+ required this.wsBaseUrl,+ required this.autonomousEnv,+ this.relayCodecs,+ this.transportPlugins,+ required this.accessTokenProvider,+ required this.onAuthFailure,+ this.onLocalFailure,+ required this.onEvent,+ 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';+ final current = _conns[machineId];+ if (current != null &&+ current.endpointKey == desiredKey &&+ !current.isClosed) {+ return current;+ }+ if (current != null) unawaited(current.close());+ final conn = WsConn(+ wsBaseUrl: wsBaseUrl,+ autonomousEnv: autonomousEnv,+ relayCodecs: transportKind == WsTransportKind.cloudE2ee+ ? relayCodecs+ : null,+ transportPlugins: transportKind == WsTransportKind.cloudE2ee+ ? transportPlugins+ : null,+ machineId: machineId,+ accessTokenProvider: accessTokenProvider,+ onAuthFailure: onAuthFailure,+ onLocalFailure: onLocalFailure == null+ ? null+ : (code, reason) => onLocalFailure!(machineId, code, reason),+ onEvent: (event) => onEvent(machineId, event),+ onStatus: (status) => onStatus(machineId, status),+ transportKind: transportKind,+ localWsUri: localWsUri,+ localApiKey: localApiKey,+ localProtocolVersion: localProtocolVersion,+ );+ _conns[machineId] = conn;+ unawaited(conn.connect());+ return conn;+ }++ WsConn? operator [](String machineId) => _conns[machineId];+ bool has(String machineId) => _conns.containsKey(machineId);++ Future<void> closeMachine(String machineId) async {+ final conn = _conns.remove(machineId);+ if (conn != null) await conn.close();+ }++ Future<void> closeAll() async {+ final all = _conns.values.toList();+ _conns.clear();+ for (final conn in all) {+ await conn.close();+ }+ }+}diff --git a/mobile/pubspec.lock b/mobile/pubspec.lockindex 9073e4783..923436ae1 100644--- a/mobile/pubspec.lock+++ b/mobile/pubspec.lock@@ -65,14 +65,6 @@ packages:url: "https://pub.dev"source: hostedversion: "3.1.2"- cross_file:- dependency: transitive- description:- name: cross_file- sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6- url: "https://pub.dev"- source: hosted- version: "0.3.5+5"crypto:dependency: transitivedescription:@@ -82,7 +74,7 @@ packages:source: hostedversion: "3.0.7"cryptography:- dependency: transitive+ dependency: "direct main"description:name: cryptographysha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0"@@ -105,24 +97,8 @@ packages:url: "https://pub.dev"source: hostedversion: "1.8.2"- dbus:- dependency: transitive- description:- name: dbus- sha256: a48d5da28e89bd02196e80d81ed8d7954923d00a0f4a68cc20b575038f023383- url: "https://pub.dev"- source: hosted- version: "0.7.15"- desktop_drop:- dependency: transitive- description:- name: desktop_drop- sha256: "47ded09c85909edfed644fd4cbb5051b040d0aed5c79e7e062ea4b3b7156dbe4"- url: "https://pub.dev"- source: hosted- version: "0.8.4"dio:- dependency: transitive+ dependency: "direct main"description:name: diosha256: "852ec3b48cc431ac04fff978413c541502b67ffc3e26921e74e3d994694192c1"@@ -169,70 +145,6 @@ packages:url: "https://pub.dev"source: hostedversion: "0.1.2"- file_selector:- dependency: transitive- description:- name: file_selector- sha256: bd15e43e9268db636b53eeaca9f56324d1622af30e5c34d6e267649758c84d9a- url: "https://pub.dev"- source: hosted- version: "1.1.0"- file_selector_android:- dependency: transitive- description:- name: file_selector_android- sha256: d670cd0ce77a2e785b18d8b4d0a8d6a222d6a813ec9b7ddf2790a1b4fb6fa92c- url: "https://pub.dev"- source: hosted- version: "0.5.2+11"- file_selector_ios:- dependency: transitive- description:- name: file_selector_ios- sha256: "97269e5307a0ab813b1fa2430bada0a96e0afb74848417f8676f64ba5de0051c"- url: "https://pub.dev"- source: hosted- version: "0.5.3+6"- file_selector_linux:- dependency: transitive- description:- name: file_selector_linux- sha256: da76400e7872ce7637ffdce12749ec24169c25f6195c28372208e65a24bcd2ab- url: "https://pub.dev"- source: hosted- version: "0.9.4+1"- file_selector_macos:- dependency: transitive- description:- name: file_selector_macos- sha256: d57c62362766b5e7ae739448650b66c6aab7a68ba7ecc65e04018652645ae0f4- url: "https://pub.dev"- source: hosted- version: "0.9.5+1"- file_selector_platform_interface:- dependency: transitive- description:- name: file_selector_platform_interface- sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85"- url: "https://pub.dev"- source: hosted- version: "2.7.0"- file_selector_web:- dependency: transitive- description:- name: file_selector_web- sha256: "73181fbc5257776d8ecaa6a94ab3c8e920ad143b9132a6d984a9271dfc6928d3"- url: "https://pub.dev"- source: hosted- version: "0.9.5"- file_selector_windows:- dependency: transitive- description:- name: file_selector_windows- sha256: fbefc5fb92c6d3cbe8d284a2cd971b593bb07d2cd6da8557b81a862250b4acec- url: "https://pub.dev"- source: hosted- version: "0.9.3+6"flutter:dependency: "direct main"description: flutter@@ -272,21 +184,6 @@ packages:url: "https://pub.dev"source: hostedversion: "1.6.2+hotfix.1"- go_router:- dependency: transitive- description:- name: go_router- sha256: d7a3576cb312649eaa51f2356450aed686085fb58fcdebda5b359aa951eef7ea- url: "https://pub.dev"- source: hosted- version: "17.5.0"- harness:- dependency: "direct main"- description:- path: "../desktop"- relative: true- source: path- version: "1.0.0+1"hooks:dependency: transitivedescription:@@ -335,14 +232,6 @@ packages:url: "https://pub.dev"source: hostedversion: "1.0.0"- json_annotation:- dependency: transitive- description:- name: json_annotation- sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80"- url: "https://pub.dev"- source: hosted- version: "4.12.0"leak_tracker:dependency: transitivedescription:@@ -448,7 +337,7 @@ packages:source: hostedversion: "3.0.0"package_info_plus:- dependency: transitive+ dependency: "direct main"description:name: package_info_plussha256: "127e1751e37ffb2ff4658beeaca77bad0c27bf5f932bd3a501c2296926d4b481"@@ -464,7 +353,7 @@ packages:source: hostedversion: "4.1.0"path:- dependency: transitive+ dependency: "direct main"description:name: pathsha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"@@ -519,14 +408,6 @@ packages:url: "https://pub.dev"source: hostedversion: "2.3.0"- petitparser:- dependency: transitive- description:- name: petitparser- sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"- url: "https://pub.dev"- source: hosted- version: "7.0.2"platform:dependency: transitivedescription:@@ -575,46 +456,6 @@ packages:url: "https://pub.dev"source: hostedversion: "2.6.1"- screen_retriever:- dependency: transitive- description:- name: screen_retriever- sha256: ace919117a7520c13a50a6259e60c4a0d4cbe98809468792a91b5c5adada2aa6- url: "https://pub.dev"- source: hosted- version: "0.2.2"- screen_retriever_linux:- dependency: transitive- description:- name: screen_retriever_linux- sha256: "7b52006a5ceae1f3d5af7f77188c3290d6e7d8ded16d99809bea84967c65c257"- url: "https://pub.dev"- source: hosted- version: "0.2.2"- screen_retriever_macos:- dependency: transitive- description:- name: screen_retriever_macos- sha256: a1489b99cce597c45a54b9aae1cd94c8d4705353b7e0bb2457a6e4de44e0ad8a- url: "https://pub.dev"- source: hosted- version: "0.2.2"- screen_retriever_platform_interface:- dependency: transitive- description:- name: screen_retriever_platform_interface- sha256: "94a5535277510a63184ca178ce12a1449bc0b38618879aa1c18bf57369c5064a"- url: "https://pub.dev"- source: hosted- version: "0.2.2"- screen_retriever_windows:- dependency: transitive- description:- name: screen_retriever_windows- sha256: dafc6922b0bfbf1d48cf3ccbf519b4fff47bdcb820da1728ea6db675fecc9324- url: "https://pub.dev"- source: hosted- version: "0.2.2"sky_engine:dependency: transitivedescription: flutter@@ -628,14 +469,6 @@ packages:url: "https://pub.dev"source: hostedversion: "1.10.2"- sqlite3:- dependency: transitive- description:- name: sqlite3- sha256: "3145bd74dcdb4fd6f5c6dda4d4e4490a8087d7f286a14dee5d37087290f0f8a2"- url: "https://pub.dev"- source: hosted- version: "2.9.4"stack_trace:dependency: transitivedescription:@@ -700,16 +533,8 @@ packages:url: "https://pub.dev"source: hostedversion: "1.4.0"- universal_platform:- dependency: transitive- description:- name: universal_platform- sha256: "64e16458a0ea9b99260ceb5467a214c1f298d647c659af1bff6d3bf82536b1ec"- url: "https://pub.dev"- source: hosted- version: "1.1.0"unorm_dart:- dependency: transitive+ dependency: "direct main"description:name: unorm_dartsha256: "0c69186b03ca6addab0774bcc0f4f17b88d4ce78d9d4d8f0619e30a99ead58e7"@@ -717,7 +542,7 @@ packages:source: hostedversion: "0.3.2"url_launcher:- dependency: transitive+ dependency: "direct main"description:name: url_launchersha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8@@ -813,7 +638,7 @@ packages:source: hostedversion: "1.0.1"web_socket_channel:- dependency: transitive+ dependency: "direct main"description:name: web_socket_channelsha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8@@ -836,14 +661,6 @@ packages:url: "https://pub.dev"source: hostedversion: "6.4.0"- window_manager:- dependency: transitive- description:- name: window_manager- sha256: "05c231fd7b23d2380f14c5cc10b7b93d60d4fa4a2fb4e0f032de27e44b5560e9"- url: "https://pub.dev"- source: hosted- version: "0.5.2"xdg_directories:dependency: transitivedescription:@@ -852,18 +669,10 @@ packages:url: "https://pub.dev"source: hostedversion: "1.1.0"- xml:- dependency: transitive- description:- name: xml- sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4"- url: "https://pub.dev"- source: hosted- version: "7.0.1"xterm:- dependency: transitive+ dependency: "direct main"description:- path: "../desktop/third_party/xterm"+ path: "third_party/xterm"relative: truesource: pathversion: "4.0.0"diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yamlindex c93fd1a43..b96312957 100644--- a/mobile/pubspec.yaml+++ b/mobile/pubspec.yaml@@ -7,24 +7,43 @@ version: 1.0.0+1environment:sdk: ^3.13.0+# This package is SELF-CONTAINED: it depends on no other package in this repo.+# The app it runs — state, API, auth, WS/relay, E2EE, the viewer's stand-ins for+# the harness CLI, and the design system — lives under `lib/`, in the same+# folders the desktop app uses for it (`core/`, `state/`, `ws/`, `e2ee/`,+# `viewer/`, `terminal/`, `shared/`, `widgets/`). It was vendored from+# `../desktop` rather than imported from it: a path dependency made every+# desktop-only concern (the managed window, the self-updater, first-run+# provisioning) a concern of the phone build too, and pinned this package to a+# Flutter app that targets macOS and Linux.dependencies:flutter:sdk: flutter- # The shared app: state, API, auth, WS/relay, E2EE, the viewer's stand-ins for- # the harness CLI, and the design system. A path dependency rather than a copy- # — the mobile work once lived in a separate checkout and drifted out of reach,- # which is the whole reason it had to be ported back by hand. One source, two- # entry points.- harness:- path: ../desktop-- # Used directly by this package's own code (lib/phone/, lib/main.dart). Kept- # explicit rather than leaned on transitively, so an import here cannot break- # because the shared app dropped a dependency it no longer uses.cupertino_icons: ^1.0.8- flutter_riverpod: ^2.6.1lucide_icons_flutter: ^3.1.15+ flutter_riverpod: ^2.6.1++ # Backend HTTP (`api/`, `viewer/direct_auth_api.dart`) and the update manifest.+ dio: ^5.11.0+ # The relay socket every machine is reached over (`ws/`).+ web_socket_channel: ^3.0.3+ # Sign-in hands the SSO URL to the system browser (`viewer/sign_in_browser.dart`)+ # and the terminal opens links a program printed (`terminal/terminal_link_opener.dart`).+ url_launcher: ^6.3.2+ # X25519/HKDF/ChaCha20-Poly1305 for the end-to-end encryption this app+ # terminates itself, being a viewer (`e2ee/`).+ cryptography: ^2.9.0+ # Unicode normalisation for the viewer's password-linking PAKE: the same+ # password must hash identically whatever form the keyboard produced it in.+ unorm_dart: ^0.3.2+ # Keep the terminal core in-tree until the upstream circular-buffer ownership+ # fix is released. See third_party/xterm/lib/src/core/buffer/buffer.dart.+ xterm:+ path: third_party/xterm+ # The running build's version, shown in Settings and sent with analytics.+ package_info_plus: ^10.2.1+ path: ^1.9.1# The phone's second wire to a machine: the `terminal-v1` data channel the# harness CLI opens with werift on the desktop's behalf (lib/p2p/). Data@@ -43,3 +62,7 @@ dev_dependencies:flutter:uses-material-design: true+ assets:+ - assets/engine-icons/+ # The real app icon, shown on the sign-in and bootstrapping screens.+ - assets/app_icon.pngdiff --git a/mobile/test/p2p/fakes.dart b/mobile/test/p2p/fakes.dartindex 1b98e9647..79b6f5da6 100644--- a/mobile/test/p2p/fakes.dart+++ b/mobile/test/p2p/fakes.dart@@ -4,9 +4,9 @@ import 'dart:typed_data';import 'package:fake_async/fake_async.dart';-import 'package:harness/terminal/terminal_binary.dart';-import 'package:harness/ws/relay_codec.dart';-import 'package:harness/ws/terminal_transport_plugin.dart';+import 'package:harness_mobile/terminal/terminal_binary.dart';+import 'package:harness_mobile/ws/relay_codec.dart';+import 'package:harness_mobile/ws/terminal_transport_plugin.dart';import 'package:harness_mobile/p2p/terminal_p2p_link.dart';import 'package:harness_mobile/p2p/terminal_p2p_plugin.dart';import 'package:harness_mobile/p2p/terminal_p2p_policy.dart';diff --git a/mobile/test/p2p/terminal_p2p_plugin_test.dart b/mobile/test/p2p/terminal_p2p_plugin_test.dartindex 7ae89aa19..0b22bf243 100644--- a/mobile/test/p2p/terminal_p2p_plugin_test.dart+++ b/mobile/test/p2p/terminal_p2p_plugin_test.dart@@ -2,8 +2,8 @@ import 'dart:convert';import 'package:fake_async/fake_async.dart';import 'package:flutter_test/flutter_test.dart';-import 'package:harness/terminal/terminal_binary.dart';-import 'package:harness/ws/terminal_transport_plugin.dart';+import 'package:harness_mobile/terminal/terminal_binary.dart';+import 'package:harness_mobile/ws/terminal_transport_plugin.dart';import 'package:harness_mobile/p2p/terminal_p2p_link.dart';import 'fakes.dart';diff --git a/mobile/test/phone_delete_agent_test.dart b/mobile/test/phone_delete_agent_test.dartindex 9a6093738..360232bf9 100644--- a/mobile/test/phone_delete_agent_test.dart+++ b/mobile/test/phone_delete_agent_test.dart@@ -1,10 +1,10 @@import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';-import 'package:harness/auth/auth_session.dart';-import 'package:harness/core/config.dart';-import 'package:harness/core/models.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/ws/ws_conn.dart';+import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/ws/ws_conn.dart';import 'package:harness_mobile/phone/agent_tile.dart';import 'package:harness_mobile/phone/agents_page.dart';diff --git a/mobile/test/phone_reclaim_test.dart b/mobile/test/phone_reclaim_test.dartindex 5230b985c..ead5f9e95 100644--- a/mobile/test/phone_reclaim_test.dart+++ b/mobile/test/phone_reclaim_test.dart@@ -1,5 +1,5 @@import 'package:flutter_test/flutter_test.dart';-import 'package:harness/terminal/terminal_session.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';import 'package:harness_mobile/phone/phone_status.dart';TerminalSession _session(TerminalSessionStatus status) => TerminalSession(diff --git a/mobile/third_party/xterm/LICENSE b/mobile/third_party/xterm/LICENSEnew file mode 100644index 000000000..7a5fd3e86--- /dev/null+++ b/mobile/third_party/xterm/LICENSE@@ -0,0 +1,21 @@+The MIT License (MIT)++Copyright (c) 2020 xuty++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/mobile/third_party/xterm/README.autonomous.md b/mobile/third_party/xterm/README.autonomous.mdnew file mode 100644index 000000000..5912e9a02--- /dev/null+++ b/mobile/third_party/xterm/README.autonomous.md@@ -0,0 +1,115 @@+# Vendored xterm.dart++This directory contains the MIT-licensed `xterm` 4.0.0 package used by the+desktop app. It is pinned in-tree because that release corrupts+`IndexAwareCircularBuffer` ownership when `Buffer.scrollUp` or+`Buffer.scrollDown` moves line objects through repeated `operator []=` calls.++The local patch adds an atomic same-length `replaceRange` operation and uses it+for vertical scroll regions. This preserves line identity (and selection+anchors) without temporarily storing the same `BufferLine` in multiple slots.+Remove the vendored dependency once the upstream package ships an equivalent+fix and the regression in `test/terminal_session_test.dart` passes against it.++## Local patches++- **Remote grids survive viewport resizing** (`lib/src/terminal_view.dart`,+ `lib/src/ui/render.dart`). `TerminalView.resizeBuffer` defaults to true;+ Harness sets it to false so a smaller local pane reports its desired size+ without deleting rows from the captured remote screen. The next remote+ keyframe supplies the resized grid. Repeated output does not repeat the+ resize request. Regressions: `test/terminal_initial_output_test.dart`, including+ a tall screen with its cursor parked above the newest output, five fresh+ panes, delayed snapshots, and preserved reading positions on return.++- **On-demand terminal find** (`lib/src/core/buffer/line.dart`,+ `lib/src/terminal.dart`). Text mutations advance a local line version so a+ search can reuse decoded rows; color-only changes keep the version. Optional+ resize listeners run after buffer reflow without replacing the transport's+ `onResize` callback. Search attaches only while visible with a nonempty query.+ Regressions: `test/terminal_search_test.dart`, `test/terminal_find_test.dart`.++- **Host-handled primary clicks** (`lib/src/terminal_view.dart`,+ `lib/src/ui/gesture/gesture_handler.dart`). `onTapUp` was declared but never+ dispatched by the single-click path. It now runs, and a consuming `onTapDown`+ lets Desktop own modifier-clicks without also sending mouse reports to a TUI.+ Ordinary clicks and drag selection keep their existing behavior. Regressions:+ `test/terminal_link_gesture_test.dart`, `test/terminal_panel_links_test.dart`.++Each of these has to survive an upstream bump — the tests named are what catch+it if one is dropped.++1. **Atomic `replaceRange` for scroll regions** (the reason this copy exists at+ all — see above). Regression: `test/terminal_session_test.dart`.++2. **Backspace is only handed to the native text input client on Apple+ platforms** (`lib/src/terminal_view.dart`). The key is deliberately not+ turned into bytes there, so that an IME can use it internally (Telex types+ `ư` as `u` + backspace + `ư`); macOS returns it as the `deleteBackward:`+ selector over `TextInputClient.performSelectors`. The GTK embedder has no+ such channel method and names `GDK_KEY_BackSpace` explicitly to ignore it —+ correct for an `EditableText`, wrong for the bare `TextInputClient` here —+ so upstream's unconditional version dropped the key entirely on Linux and no+ byte reached the pty. Regression: the macOS/Linux pair in+ `test/terminal_view_interaction_test.dart`.++3. **A Meta chord is left for the app on every platform, not just Apple**+ (`lib/src/terminal_view.dart`). Every shortcut in+ `lib/shortcuts/app_shortcuts.dart` is declared `meta: true`, which is Super+ on Linux; while this was gated on macOS/iOS a focused terminal answered+ Super+key itself and no app shortcut worked with a pane open. Regression:+ `test/terminal_view_interaction_test.dart`.++4. **Erase-left accepts a cursor in the first column**+ (`lib/src/core/buffer/line.dart`, `lib/src/core/buffer/buffer.dart`). `CSI 1 K`+ at column zero previously passed an empty range to `BufferLine.eraseRange`,+ which read cell `-1` while checking a wide-character boundary. The range+ guard now accepts an empty range, and erase-left includes the cursor cell as+ required by its terminal contract. Regression: `test/terminal_session_test.dart`.++5. **String sequences (DCS/APC/PM/SOS) are consumed instead of leaking**+ (`lib/src/core/escape/parser.dart`). `ESC P` had no handler, so its body was+ handed to the text path one fragment at a time. tmux wraps passthrough as+ `ESC P tmux; <body> ESC \` and doubles every ESC inside that body, so a+ program asking the outer terminal for its background colour from inside tmux+ painted `tmux;]11;?` into the pane — seen in Claude Code's theme picker.+ Only ST ends the body: neither the doubled `ESC ESC` nor an inner OSC's BEL+ may terminate it, and a body split across two pty chunks rolls back and waits+ the same way `_consumeOsc` does. Regression: the two string-sequence tests in+ `test/terminal_session_test.dart`.++6. **The selection/highlight rectangle is painted at the render box's own paint+ offset, not at (0,0)** (`lib/src/ui/render.dart`). `_paintHighlights`/+ `_paintSelection`/`_paintSegment` never received the `offset` `paint()` is+ handed — unlike the line-glyph and cursor paints right above them, which+ both add it — so whenever this box has a non-zero paint offset (the pane's+ own padding, in this app) the highlighted rectangle was drawn shifted away+ from the glyphs it was supposed to cover, leaving trailing selected+ characters rendered outside the box instead of inside it. No regression+ test (would need a golden/paint-offset test harness this repo doesn't+ have yet) — verify visually: drag-select text ending near the right edge+ of a padded pane and confirm the highlight covers every selected glyph.++7. **`BufferLine.getText` renders a blank cell as a literal space instead of+ dropping it** (`lib/src/core/buffer/line.dart`). A cell whose stored+ codePoint is 0 — never written, or erased — was skipped outright rather+ than emitting anything, so a gap laid out with cursor-forward (CSI `C`)+ instead of literal space bytes (the normal way TUI output from Claude Code,+ Codex, etc. positions text and indentation) copied as nothing: two words+ glued together with no separator, leading indentation gone. Only the+ second half of a wide character also stores codePoint 0 and must still be+ skipped (checked via the preceding cell's width being 2), and only+ *trailing* blank cells stay trimmed — a wholly blank line still copies as+ empty, not as columns of padding. Regression: `test/terminal_session_test.dart`+ (`'copied text keeps cursor-positioned gaps as spaces...'` and the+ erase-left test, which now expects a leading space where the erased cell+ is).++8. **Shift+Left/Right reach the TUI in both screen buffers**+ (`lib/src/core/input/keytab/keytab_default.dart`). The upstream mapping+ required the alternate screen, so a normal-screen Codex terminal emitted+ no input for its "shift + left to answer" queued-question shortcut. Both+ horizontal chords now send the xterm modifier sequence in either buffer;+ vertical scrolling and app-owned Meta shortcuts keep their bindings.+ Regression: the macOS/Linux pair in `test/terminal_panel_focus_test.dart`+ exercises physical key events through `TerminalPanel` to binary PTY input.diff --git a/mobile/third_party/xterm/lib/core.dart b/mobile/third_party/xterm/lib/core.dartnew file mode 100644index 000000000..ffe7f1cc9--- /dev/null+++ b/mobile/third_party/xterm/lib/core.dart@@ -0,0 +1,22 @@+export 'src/core/buffer/buffer.dart';+export 'src/core/buffer/cell_flags.dart';+export 'src/core/buffer/cell_offset.dart';+export 'src/core/buffer/line.dart';+export 'src/core/buffer/range.dart';+export 'src/core/buffer/range_block.dart';+export 'src/core/buffer/range_line.dart';+export 'src/core/buffer/segment.dart';+export 'src/core/cell.dart';+export 'src/core/color.dart';+export 'src/core/cursor.dart';+export 'src/core/escape/handler.dart';+export 'src/core/escape/parser.dart';+export 'src/core/input/handler.dart';+export 'src/core/input/keys.dart';+export 'src/core/mouse/button.dart';+export 'src/core/mouse/button_state.dart';+export 'src/core/mouse/handler.dart';+export 'src/core/mouse/mode.dart';+export 'src/core/platform.dart';+export 'src/core/state.dart';+export 'src/terminal.dart';diff --git a/mobile/third_party/xterm/lib/src/base/disposable.dart b/mobile/third_party/xterm/lib/src/base/disposable.dartnew file mode 100644index 000000000..c6dc023cd--- /dev/null+++ b/mobile/third_party/xterm/lib/src/base/disposable.dart@@ -0,0 +1,41 @@+import 'package:xterm/src/base/event.dart';++mixin Disposable {+ final _disposables = <Disposable>[];++ bool get disposed => _disposed;+ bool _disposed = false;++ Event get onDisposed => _onDisposed.event;+ final _onDisposed = EventEmitter();++ void register(Disposable disposable) {+ assert(!_disposed);+ _disposables.add(disposable);+ }++ void registerCallback(void Function() callback) {+ assert(!_disposed);+ _disposables.add(_DisposeCallback(callback));+ }++ void dispose() {+ _disposed = true;+ for (final disposable in _disposables) {+ disposable.dispose();+ }+ _onDisposed.emit(null);+ }+}++class _DisposeCallback with Disposable {+ final void Function() callback;++ _DisposeCallback(this.callback);++ @override+ void dispose() {+ super.dispose();+ callback();+ }+}diff --git a/mobile/third_party/xterm/lib/src/base/event.dart b/mobile/third_party/xterm/lib/src/base/event.dartnew file mode 100644index 000000000..3987332ed--- /dev/null+++ b/mobile/third_party/xterm/lib/src/base/event.dart@@ -0,0 +1,42 @@+import 'package:xterm/src/base/disposable.dart';++typedef EventListener<T> = void Function(T event);++class Event<T> {+ final EventEmitter<T> emitter;++ Event(this.emitter);++ void call(EventListener<T> listener) {+ emitter(listener);+ }+}++class EventEmitter<T> {+ final _listeners = <EventListener<T>>[];++ EventSubscription<T> call(EventListener<T> listener) {+ _listeners.add(listener);+ return EventSubscription(this, listener);+ }++ void emit(T event) {+ for (final listener in _listeners) {+ listener(event);+ }+ }++ Event<T> get event => Event(this);+}++class EventSubscription<T> with Disposable {+ final EventEmitter<T> emitter;+ final EventListener<T> listener;++ EventSubscription(this.emitter, this.listener);++ @override+ void dispose() {+ emitter._listeners.remove(listener);+ }+}diff --git a/mobile/third_party/xterm/lib/src/base/observable.dart b/mobile/third_party/xterm/lib/src/base/observable.dartnew file mode 100644index 000000000..ac2b78a51--- /dev/null+++ b/mobile/third_party/xterm/lib/src/base/observable.dart@@ -0,0 +1,17 @@+mixin Observable {+ final listeners = <void Function()>{};++ void addListener(void Function() listener) {+ listeners.add(listener);+ }++ void removeListener(void Function() listener) {+ listeners.remove(listener);+ }++ void notifyListeners() {+ for (var listener in listeners) {+ listener();+ }+ }+}diff --git a/mobile/third_party/xterm/lib/src/core/buffer/buffer.dart b/mobile/third_party/xterm/lib/src/core/buffer/buffer.dartnew file mode 100644index 000000000..5481c3f26--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/buffer/buffer.dart@@ -0,0 +1,612 @@+import 'dart:math' show max, min;++import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/buffer/line.dart';+import 'package:xterm/src/core/buffer/range_line.dart';+import 'package:xterm/src/core/buffer/range.dart';+import 'package:xterm/src/core/charset.dart';+import 'package:xterm/src/core/cursor.dart';+import 'package:xterm/src/core/reflow.dart';+import 'package:xterm/src/core/state.dart';+import 'package:xterm/src/utils/circular_buffer.dart';+import 'package:xterm/src/utils/unicode_v11.dart';++class Buffer {+ final TerminalState terminal;++ final int maxLines;++ final bool isAltBuffer;++ /// Characters that break selection when calling [getWordBoundary]. If null,+ /// defaults to [defaultWordSeparators].+ final Set<int>? wordSeparators;++ Buffer(+ this.terminal, {+ required this.maxLines,+ required this.isAltBuffer,+ this.wordSeparators,+ }) {+ for (int i = 0; i < terminal.viewHeight; i++) {+ lines.push(_newEmptyLine());+ }++ resetVerticalMargins();+ }++ int _cursorX = 0;++ int _cursorY = 0;++ late int _marginTop;++ late int _marginBottom;++ var _savedCursorX = 0;++ var _savedCursorY = 0;++ final _savedCursorStyle = CursorStyle();++ final charset = Charset();++ /// Width of the viewport in columns. Also the index of the last column.+ int get viewWidth => terminal.viewWidth;++ /// Height of the viewport in rows. Also the index of the last line.+ int get viewHeight => terminal.viewHeight;++ /// lines of the buffer. the length of [lines] should always be equal or+ /// greater than [viewHeight].+ late final lines = IndexAwareCircularBuffer<BufferLine>(maxLines);++ /// Total number of lines in the buffer. Always equal or greater than+ /// [viewHeight].+ int get height => lines.length;++ /// Horizontal position of the cursor relative to the top-left cornor of the+ /// screen, starting from 0.+ int get cursorX => _cursorX.clamp(0, terminal.viewWidth - 1);++ /// Vertical position of the cursor relative to the top-left cornor of the+ /// screen, starting from 0.+ int get cursorY => _cursorY;++ /// Index of the first line in the scroll region.+ int get marginTop => _marginTop;++ /// Index of the last line in the scroll region.+ int get marginBottom => _marginBottom;++ /// The number of lines above the viewport.+ int get scrollBack => height - viewHeight;++ /// Vertical position of the cursor relative to the top of the buffer,+ /// starting from 0.+ int get absoluteCursorY => _cursorY + scrollBack;++ /// Absolute index of the first line in the scroll region.+ int get absoluteMarginTop => _marginTop + scrollBack;++ /// Absolute index of the last line in the scroll region.+ int get absoluteMarginBottom => _marginBottom + scrollBack;++ /// Writes data to the _terminal. Terminal sequences or special characters are+ /// not interpreted and directly added to the buffer.+ ///+ /// See also: [Terminal.write]+ void write(String text) {+ for (var char in text.runes) {+ writeChar(char);+ }+ }++ /// Writes a single character to the _terminal. Escape sequences or special+ /// characters are not interpreted and directly added to the buffer.+ ///+ /// See also: [Terminal.writeChar]+ void writeChar(int codePoint) {+ codePoint = charset.translate(codePoint);++ final cellWidth = unicodeV11.wcwidth(codePoint);+ if (_cursorX >= terminal.viewWidth) {+ index();+ setCursorX(0);+ if (terminal.autoWrapMode) {+ currentLine.isWrapped = true;+ }+ }++ final line = currentLine;+ line.setCell(_cursorX, codePoint, cellWidth, terminal.cursor);++ if (_cursorX < viewWidth) {+ _cursorX++;+ }++ if (cellWidth == 2) {+ writeChar(0);+ }+ }++ /// The line at the current cursor position.+ BufferLine get currentLine {+ return lines[absoluteCursorY];+ }++ void backspace() {+ if (_cursorX == 0 && currentLine.isWrapped) {+ currentLine.isWrapped = false;+ moveCursor(viewWidth - 1, -1);+ } else if (_cursorX == viewWidth) {+ moveCursor(-2, 0);+ } else {+ moveCursor(-1, 0);+ }+ }++ /// Erases the viewport from the cursor position to the end of the buffer,+ /// including the cursor position.+ void eraseDisplayFromCursor() {+ eraseLineFromCursor();++ for (var i = absoluteCursorY + 1; i < height; i++) {+ final line = lines[i];+ line.isWrapped = false;+ line.eraseRange(0, viewWidth, terminal.cursor);+ }+ }++ /// Erases the viewport from the top-left corner to the cursor, including the+ /// cursor.+ void eraseDisplayToCursor() {+ eraseLineToCursor();++ for (var i = 0; i < _cursorY; i++) {+ final line = lines[i + scrollBack];+ line.isWrapped = false;+ line.eraseRange(0, viewWidth, terminal.cursor);+ }+ }++ /// Erases the whole viewport.+ void eraseDisplay() {+ for (var i = 0; i < viewHeight; i++) {+ final line = lines[i + scrollBack];+ line.isWrapped = false;+ line.eraseRange(0, viewWidth, terminal.cursor);+ }+ }++ /// Erases the line from the cursor to the end of the line, including the+ /// cursor position.+ void eraseLineFromCursor() {+ currentLine.isWrapped = false;+ currentLine.eraseRange(cursorX, viewWidth, terminal.cursor);+ }++ /// Erases the line from the start of the line to the cursor, including the+ /// cursor.+ void eraseLineToCursor() {+ currentLine.isWrapped = false;+ currentLine.eraseRange(0, cursorX + 1, terminal.cursor);+ }++ /// Erases the line at the current cursor position.+ void eraseLine() {+ currentLine.isWrapped = false;+ currentLine.eraseRange(0, viewWidth, terminal.cursor);+ }++ /// Erases [count] cells starting at the cursor position.+ void eraseChars(int count) {+ final start = _cursorX;+ currentLine.eraseRange(start, start + count, terminal.cursor);+ }++ void scrollDown(int count) {+ final top = absoluteMarginTop;+ final bottom = absoluteMarginBottom;+ final height = bottom - top + 1;+ count = min(count, height);+ if (count <= 0) return;++ final replacement = <BufferLine>[+ for (var i = 0; i < count; i++) _newEmptyLine(),+ for (var i = top; i <= bottom - count; i++) lines[i],+ ];+ lines.replaceRange(top, replacement);+ }++ void scrollUp(int count) {+ final top = absoluteMarginTop;+ final bottom = absoluteMarginBottom;+ final height = bottom - top + 1;+ count = min(count, height);+ if (count <= 0) return;++ final replacement = <BufferLine>[+ for (var i = top + count; i <= bottom; i++) lines[i],+ for (var i = 0; i < count; i++) _newEmptyLine(),+ ];+ lines.replaceRange(top, replacement);+ }++ /// https://vt100.net/docs/vt100-ug/chapter3.html#IND IND – Index+ ///+ /// ESC D+ ///+ /// [index] causes the active position to move downward one line without+ /// changing the column position. If the active position is at the bottom+ /// margin, a scroll up is performed.+ void index() {+ if (isInVerticalMargin) {+ if (_cursorY == _marginBottom) {+ if (marginTop == 0 && !isAltBuffer) {+ lines.insert(absoluteMarginBottom + 1, _newEmptyLine());+ } else {+ scrollUp(1);+ }+ } else {+ moveCursorY(1);+ }+ return;+ }++ // the cursor is not in the scrollable region+ if (_cursorY >= viewHeight - 1) {+ // we are at the bottom+ if (isAltBuffer) {+ scrollUp(1);+ } else {+ lines.push(_newEmptyLine());+ }+ } else {+ // there're still lines so we simply move cursor down.+ moveCursorY(1);+ }+ }++ void lineFeed() {+ index();+ if (terminal.lineFeedMode) {+ setCursorX(0);+ }+ }++ /// https://terminalguide.namepad.de/seq/a_esc_cm/+ void reverseIndex() {+ if (isInVerticalMargin) {+ if (_cursorY == _marginTop) {+ scrollDown(1);+ } else {+ moveCursorY(-1);+ }+ } else {+ moveCursorY(-1);+ }+ }++ void cursorGoForward() {+ _cursorX = min(_cursorX + 1, viewWidth);+ }++ void setCursorX(int cursorX) {+ _cursorX = cursorX.clamp(0, viewWidth - 1);+ }++ void setCursorY(int cursorY) {+ _cursorY = cursorY.clamp(0, viewHeight - 1);+ }++ void moveCursorX(int offset) {+ setCursorX(_cursorX + offset);+ }++ void moveCursorY(int offset) {+ setCursorY(_cursorY + offset);+ }++ void setCursor(int cursorX, int cursorY) {+ var maxCursorY = viewHeight - 1;++ if (terminal.originMode) {+ cursorY += _marginTop;+ maxCursorY = _marginBottom;+ }++ _cursorX = cursorX.clamp(0, viewWidth - 1);+ _cursorY = cursorY.clamp(0, maxCursorY);+ }++ void moveCursor(int offsetX, int offsetY) {+ final cursorX = _cursorX + offsetX;+ final cursorY = _cursorY + offsetY;+ setCursor(cursorX, cursorY);+ }++ /// Save cursor position, charmap and text attributes.+ void saveCursor() {+ _savedCursorX = _cursorX;+ _savedCursorY = _cursorY;+ _savedCursorStyle.foreground = terminal.cursor.foreground;+ _savedCursorStyle.background = terminal.cursor.background;+ _savedCursorStyle.attrs = terminal.cursor.attrs;+ charset.save();+ }++ /// Restore cursor position, charmap and text attributes.+ void restoreCursor() {+ _cursorX = _savedCursorX;+ _cursorY = _savedCursorY;+ terminal.cursor.foreground = _savedCursorStyle.foreground;+ terminal.cursor.background = _savedCursorStyle.background;+ terminal.cursor.attrs = _savedCursorStyle.attrs;+ charset.restore();+ }++ /// Sets the vertical scrolling margin to [top] and [bottom].+ /// Both values must be between 0 and [viewHeight] - 1.+ void setVerticalMargins(int top, int bottom) {+ _marginTop = top.clamp(0, viewHeight - 1);+ _marginBottom = bottom.clamp(0, viewHeight - 1);++ _marginTop = min(_marginTop, _marginBottom);+ _marginBottom = max(_marginTop, _marginBottom);+ }++ bool get isInVerticalMargin {+ return _cursorY >= _marginTop && _cursorY <= _marginBottom;+ }++ void resetVerticalMargins() {+ setVerticalMargins(0, viewHeight - 1);+ }++ void deleteChars(int count) {+ final start = _cursorX.clamp(0, viewWidth);+ count = min(count, viewWidth - start);+ currentLine.removeCells(start, count, terminal.cursor);+ }++ /// Remove all lines above the top of the viewport.+ void clearScrollback() {+ if (height <= viewHeight) {+ return;+ }++ lines.trimStart(scrollBack);+ }++ /// Clears the viewport and scrollback buffer. Then fill with empty lines.+ void clear() {+ lines.clear();+ for (int i = 0; i < viewHeight; i++) {+ lines.push(_newEmptyLine());+ }+ }++ void insertBlankChars(int count) {+ currentLine.insertCells(_cursorX, count, terminal.cursor);+ }++ void insertLines(int count) {+ if (!isInVerticalMargin) {+ return;+ }++ setCursorX(0);++ // Number of lines from the cursor to the bottom of the scrollable region+ // including the cursor itself.+ final linesBelow = absoluteMarginBottom - absoluteCursorY + 1;++ // Number of empty lines to insert.+ final linesToInsert = min(count, linesBelow);++ // Number of lines to move up.+ final linesToMove = linesBelow - linesToInsert;++ for (var i = 0; i < linesToMove; i++) {+ final index = absoluteMarginBottom - i;+ lines[index] = lines.swap(index - linesToInsert, _newEmptyLine());+ }++ for (var i = linesToMove; i < linesToInsert; i++) {+ lines[absoluteCursorY + i] = _newEmptyLine();+ }+ }++ /// Remove [count] lines starting at the current cursor position. Lines below+ /// the removed lines are shifted up. This only affects the scrollable region.+ /// Lines outside the scrollable region are not affected.+ void deleteLines(int count) {+ if (!isInVerticalMargin) {+ return;+ }++ setCursorX(0);++ count = min(count, absoluteMarginBottom - absoluteCursorY + 1);++ final linesToMove = absoluteMarginBottom - absoluteCursorY + 1 - count;++ for (var i = 0; i < linesToMove; i++) {+ final index = absoluteCursorY + i;+ lines[index] = lines[index + count];+ }++ for (var i = 0; i < count; i++) {+ lines[absoluteMarginBottom - i] = _newEmptyLine();+ }+ }++ void resize(int oldWidth, int oldHeight, int newWidth, int newHeight) {+ // 1. Adjust the height.+ if (newHeight > oldHeight) {+ // Grow larger+ for (var i = 0; i < newHeight - oldHeight; i++) {+ if (newHeight > lines.length) {+ lines.push(_newEmptyLine(newWidth));+ } else {+ _cursorY++;+ }+ }+ } else {+ // Shrink smaller+ for (var i = 0; i < oldHeight - newHeight; i++) {+ if (_cursorY > newHeight - 1) {+ _cursorY--;+ } else {+ lines.pop();+ }+ }+ }++ // Ensure cursor is within the screen.+ _cursorX = _cursorX.clamp(0, newWidth - 1);+ _cursorY = _cursorY.clamp(0, newHeight - 1);++ // 2. Adjust the width.+ if (newWidth != oldWidth) {+ if (terminal.reflowEnabled && !isAltBuffer) {+ final reflowResult = reflow(lines, oldWidth, newWidth);++ while (reflowResult.length < newHeight) {+ reflowResult.add(_newEmptyLine(newWidth));+ }++ lines.replaceWith(reflowResult);+ } else {+ lines.forEach((item) => item.resize(newWidth));+ }+ }+ }++ /// Create a new [CellAnchor] at the specified [x] and [y] coordinates.+ CellAnchor createAnchor(int x, int y) {+ return lines[y].createAnchor(x);+ }++ /// Create a new [CellAnchor] at the specified [x] and [y] coordinates.+ CellAnchor createAnchorFromOffset(CellOffset offset) {+ return lines[offset.y].createAnchor(offset.x);+ }++ CellAnchor createAnchorFromCursor() {+ return createAnchor(cursorX, absoluteCursorY);+ }++ /// Create a new empty [BufferLine] with the current [viewWidth] if [width]+ /// is not specified.+ BufferLine _newEmptyLine([int? width]) {+ final line = BufferLine(width ?? viewWidth);+ return line;+ }++ static final defaultWordSeparators = <int>{+ 0,+ r' '.codeUnitAt(0),+ r'.'.codeUnitAt(0),+ r':'.codeUnitAt(0),+ r'-'.codeUnitAt(0),+ r'\'.codeUnitAt(0),+ r'"'.codeUnitAt(0),+ r'*'.codeUnitAt(0),+ r'+'.codeUnitAt(0),+ r'/'.codeUnitAt(0),+ r'\'.codeUnitAt(0),+ };++ BufferRangeLine? getWordBoundary(CellOffset position) {+ var separators = wordSeparators ?? defaultWordSeparators;+ if (position.y >= lines.length) {+ return null;+ }++ var line = lines[position.y];+ var start = position.x;+ var end = position.x;++ do {+ if (start == 0) {+ break;+ }+ final char = line.getCodePoint(start - 1);+ if (separators.contains(char)) {+ break;+ }+ start--;+ } while (true);++ do {+ if (end >= viewWidth) {+ break;+ }+ final char = line.getCodePoint(end);+ if (separators.contains(char)) {+ break;+ }+ end++;+ } while (true);++ if (start == end) {+ return null;+ }++ return BufferRangeLine(+ CellOffset(start, position.y),+ CellOffset(end, position.y),+ );+ }++ /// Get the plain text content of the buffer including the scrollback.+ /// Accepts an optional [range] to get a specific part of the buffer.+ String getText([BufferRange? range]) {+ range ??= BufferRangeLine(+ CellOffset(0, 0),+ CellOffset(viewWidth - 1, height - 1),+ );++ range = range.normalized;++ final builder = StringBuffer();++ for (var segment in range.toSegments()) {+ if (segment.line < 0 || segment.line >= height) {+ continue;+ }+ final line = lines[segment.line];+ if (!(segment.line == range.begin.y ||+ segment.line == 0 ||+ line.isWrapped)) {+ builder.write("\n");+ }+ builder.write(line.getText(segment.start, segment.end));+ }++ return builder.toString();+ }++ /// Returns a debug representation of the buffer.+ @override+ String toString() {+ final builder = StringBuffer();+ final lineNumberLength = lines.length.toString().length;++ for (var i = 0; i < lines.length; i++) {+ final line = lines[i];++ builder.write('${i.toString().padLeft(lineNumberLength)}: |${lines[i]}|');++ if (line.isWrapped) {+ builder.write(' (⏎)');+ }++ builder.write('\n');+ }++ return builder.toString();+ }+}diff --git a/mobile/third_party/xterm/lib/src/core/buffer/cell_flags.dart b/mobile/third_party/xterm/lib/src/core/buffer/cell_flags.dartnew file mode 100644index 000000000..97c5b8aa8--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/buffer/cell_flags.dart@@ -0,0 +1,9 @@+abstract class CellFlags {+ static const bold = 1 << 0;+ static const faint = 1 << 1;+ static const italic = 1 << 2;+ static const underline = 1 << 3;+ static const blink = 1 << 4;+ static const inverse = 1 << 5;+ static const invisible = 1 << 6;+}diff --git a/mobile/third_party/xterm/lib/src/core/buffer/cell_offset.dart b/mobile/third_party/xterm/lib/src/core/buffer/cell_offset.dartnew file mode 100644index 000000000..36eb426fa--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/buffer/cell_offset.dart@@ -0,0 +1,55 @@+import 'package:xterm/src/core/buffer/range.dart';++class CellOffset {+ final int x;++ final int y;++ const CellOffset(this.x, this.y);++ bool isEqual(CellOffset other) {+ return other.x == x && other.y == y;+ }++ bool isBefore(CellOffset other) {+ return y < other.y || (y == other.y && x < other.x);+ }++ bool isAfter(CellOffset other) {+ return y > other.y || (y == other.y && x > other.x);+ }++ bool isBeforeOrSame(CellOffset other) {+ return y < other.y || (y == other.y && x <= other.x);+ }++ bool isAfterOrSame(CellOffset other) {+ return y > other.y || (y == other.y && x >= other.x);+ }++ bool isAtSameRow(CellOffset other) {+ return y == other.y;+ }++ bool isAtSameColumn(CellOffset other) {+ return x == other.x;+ }++ bool isWithin(BufferRange range) {+ return range.contains(this);+ }++ @override+ String toString() => 'CellOffset($x, $y)';++ @override+ int get hashCode => x.hashCode ^ y.hashCode;++ @override+ bool operator ==(Object other) =>+ identical(this, other) ||+ other is CellOffset &&+ runtimeType == other.runtimeType &&+ x == other.x &&+ y == other.y;+}diff --git a/mobile/third_party/xterm/lib/src/core/buffer/line.dart b/mobile/third_party/xterm/lib/src/core/buffer/line.dartnew file mode 100644index 000000000..7ea477ad4--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/buffer/line.dart@@ -0,0 +1,456 @@+import 'dart:math' show min;+import 'dart:typed_data';++import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/cell.dart';+import 'package:xterm/src/core/cursor.dart';+import 'package:xterm/src/utils/circular_buffer.dart';+import 'package:xterm/src/utils/unicode_v11.dart';++const _cellSize = 4;++const _cellForeground = 0;++const _cellBackground = 1;++const _cellAttributes = 2;++const _cellContent = 3;++class BufferLine with IndexedItem {+ BufferLine(+ this._length, {+ this.isWrapped = false,+ }) : _data = Uint32List(_calcCapacity(_length) * _cellSize);++ int _length;++ Uint32List _data;++ Uint32List get data => _data;++ var isWrapped = false;++ int get length => _length;++ /// Local text caches can reuse an unchanged line without rereading its cells.+ /// Color-only changes do not invalidate text; wrapping is tracked separately.+ int get textVersion => _textVersion;+ int _textVersion = 0;++ final _anchors = <CellAnchor>[];++ List<CellAnchor> get anchors => _anchors;++ int getForeground(int index) {+ return _data[index * _cellSize + _cellForeground];+ }++ int getBackground(int index) {+ return _data[index * _cellSize + _cellBackground];+ }++ int getAttributes(int index) {+ return _data[index * _cellSize + _cellAttributes];+ }++ int getContent(int index) {+ return _data[index * _cellSize + _cellContent];+ }++ int getCodePoint(int index) {+ return _data[index * _cellSize + _cellContent] & CellContent.codepointMask;+ }++ int getWidth(int index) {+ return _data[index * _cellSize + _cellContent] >> CellContent.widthShift;+ }++ void getCellData(int index, CellData cellData) {+ final offset = index * _cellSize;+ cellData.foreground = _data[offset + _cellForeground];+ cellData.background = _data[offset + _cellBackground];+ cellData.flags = _data[offset + _cellAttributes];+ cellData.content = _data[offset + _cellContent];+ }++ CellData createCellData(int index) {+ _textVersion++;+ final cellData = CellData.empty();+ final offset = index * _cellSize;+ _data[offset + _cellForeground] = cellData.foreground;+ _data[offset + _cellBackground] = cellData.background;+ _data[offset + _cellAttributes] = cellData.flags;+ _data[offset + _cellContent] = cellData.content;+ return cellData;+ }++ void setForeground(int index, int value) {+ _data[index * _cellSize + _cellForeground] = value;+ }++ void setBackground(int index, int value) {+ _data[index * _cellSize + _cellBackground] = value;+ }++ void setAttributes(int index, int value) {+ _data[index * _cellSize + _cellAttributes] = value;+ }++ void setContent(int index, int value) {+ _textVersion++;+ _data[index * _cellSize + _cellContent] = value;+ }++ void setCodePoint(int index, int char) {+ final width = unicodeV11.wcwidth(char);+ setContent(index, char | (width << CellContent.widthShift));+ }++ void setCell(int index, int char, int witdh, CursorStyle style) {+ _textVersion++;+ final offset = index * _cellSize;+ _data[offset + _cellForeground] = style.foreground;+ _data[offset + _cellBackground] = style.background;+ _data[offset + _cellAttributes] = style.attrs;+ _data[offset + _cellContent] = char | (witdh << CellContent.widthShift);+ }++ void setCellData(int index, CellData cellData) {+ _textVersion++;+ final offset = index * _cellSize;+ _data[offset + _cellForeground] = cellData.foreground;+ _data[offset + _cellBackground] = cellData.background;+ _data[offset + _cellAttributes] = cellData.flags;+ _data[offset + _cellContent] = cellData.content;+ }++ void eraseCell(int index, CursorStyle style) {+ _textVersion++;+ final offset = index * _cellSize;+ _data[offset + _cellForeground] = style.foreground;+ _data[offset + _cellBackground] = style.background;+ _data[offset + _cellAttributes] = style.attrs;+ _data[offset + _cellContent] = 0;+ }++ void resetCell(int index) {+ _textVersion++;+ final offset = index * _cellSize;+ _data[offset + _cellForeground] = 0;+ _data[offset + _cellBackground] = 0;+ _data[offset + _cellAttributes] = 0;+ _data[offset + _cellContent] = 0;+ }++ /// Erase cells whose index satisfies [start] <= index < [end]. Erased cells+ /// are filled with [style].+ void eraseRange(int start, int end, CursorStyle style) {+ // reset cell one to the left if start is second cell of a wide char+ if (start > 0 && getWidth(start - 1) == 2) {+ eraseCell(start - 1, style);+ }++ // reset cell one to the right if end is second cell of a wide char+ if (end > 0 && end < _length && getWidth(end - 1) == 2) {+ eraseCell(end - 1, style);+ }++ end = min(end, _length);+ for (var i = start; i < end; i++) {+ eraseCell(i, style);+ }+ }++ /// Remove [count] cells starting at [start]. Cells that are empty after the+ /// removal are filled with [style].+ void removeCells(int start, int count, [CursorStyle? style]) {+ assert(start >= 0 && start < _length);+ assert(count >= 0 && start + count <= _length);++ style ??= CursorStyle.empty;++ if (start + count < _length) {+ final moveStart = start * _cellSize;+ final moveEnd = (_length - count) * _cellSize;+ final moveOffset = count * _cellSize;+ for (var i = moveStart; i < moveEnd; i++) {+ _data[i] = _data[i + moveOffset];+ }+ }++ for (var i = _length - count; i < _length; i++) {+ eraseCell(i, style);+ }++ if (start > 0 && getWidth(start - 1) == 2) {+ eraseCell(start - 1, style);+ }++ // Update anchors, remove anchors that are inside the removed range.+ for (var i = 0; i < _anchors.length; i++) {+ final anchor = _anchors[i];+ if (anchor.x >= start) {+ if (anchor.x < start + count) {+ anchor.dispose();+ } else {+ anchor.reposition(anchor.x - count);+ }+ }+ }+ }++ /// Inserts [count] cells at [start]. New cells are initialized with [style].+ void insertCells(int start, int count, [CursorStyle? style]) {+ style ??= CursorStyle.empty;++ if (start > 0 && getWidth(start - 1) == 2) {+ eraseCell(start - 1, style);+ }++ if (start + count < _length) {+ final moveStart = start * _cellSize;+ final moveEnd = (_length - count) * _cellSize;+ final moveOffset = count * _cellSize;+ for (var i = moveEnd - 1; i >= moveStart; i--) {+ _data[i + moveOffset] = _data[i];+ }+ }++ final end = min(start + count, _length);+ for (var i = start; i < end; i++) {+ eraseCell(i, style);+ }++ if (getWidth(_length - 1) == 2) {+ eraseCell(_length - 1, style);+ }++ // Update anchors, move anchors that are after the inserted range.+ for (var i = 0; i < _anchors.length; i++) {+ final anchor = _anchors[i];+ if (anchor.x >= start + count) {+ anchor.reposition(anchor.x + count);++ // Remove anchors that are now outside the buffer.+ if (anchor.x >= _length) {+ anchor.dispose();+ }+ }+ }+ }++ void resize(int length) {+ assert(length >= 0);++ if (length == _length) {+ return;+ }++ if (length > _length) {+ final newBufferSize = _calcCapacity(length) * _cellSize;++ if (newBufferSize > _data.length) {+ final newBuffer = Uint32List(newBufferSize);+ newBuffer.setRange(0, _data.length, _data);+ _data = newBuffer;+ }+ }++ _textVersion++;+ _length = length;++ for (var i = 0; i < _anchors.length; i++) {+ final anchor = _anchors[i];+ if (anchor.x > _length) {+ anchor.reposition(_length);+ }+ }+ }++ /// Returns the offset of the last cell that has content from the start of+ /// the line.+ int getTrimmedLength([int? cols]) {+ final maxCols = _data.length ~/ _cellSize;++ if (cols == null || cols > maxCols) {+ cols = maxCols;+ }++ if (cols <= 0) {+ return 0;+ }++ for (var i = cols - 1; i >= 0; i--) {+ var codePoint = getCodePoint(i);++ if (codePoint != 0) {+ // we are at the last cell in this line that has content.+ // the length of this line is the index of this cell + 1+ // the only exception is that if that last cell is wider+ // than 1 then we have to add the diff+ final lastCellWidth = getWidth(i);+ return i + lastCellWidth;+ }+ }+ return 0;+ }++ /// Copies [len] cells from [src] starting at [srcCol] to [dstCol] at this+ /// line.+ void copyFrom(BufferLine src, int srcCol, int dstCol, int len) {+ _textVersion++;+ resize(dstCol + len);++ // data.setRange(+ // dstCol * _cellSize,+ // (dstCol + len) * _cellSize,+ // Uint32List.sublistView(src.data, srcCol * _cellSize, len * _cellSize),+ // );++ var srcOffset = srcCol * _cellSize;+ var dstOffset = dstCol * _cellSize;++ for (var i = 0; i < len * _cellSize; i++) {+ _data[dstOffset++] = src._data[srcOffset++];+ }+ }++ static int _calcCapacity(int length) {+ assert(length >= 0);++ var capacity = 64;++ if (length < 256) {+ while (capacity < length) {+ capacity *= 2;+ }+ } else {+ capacity = 256;+ while (capacity < length) {+ capacity += 32;+ }+ }++ return capacity;+ }++ String getText([int? from, int? to]) {+ if (from == null || from < 0) {+ from = 0;+ }++ if (to == null || to > _length) {+ to = _length;+ }++ // The second half of a wide character stores codePoint 0 by design (see writeChar in+ // buffer.dart, which recurses with codePoint 0 to fill the cell after a width-2 write) — it is+ // not blank, it is half of the character written into the cell before it.+ bool isWideContinuation(int i) => i > 0 && getWidth(i - 1) == 2;++ // Trailing blank cells — never written, or erased (both store codePoint 0) — must not become+ // trailing spaces, the same way a blank line must not copy as a run of padding. Only the gap+ // *before* the last real content on the line, below, becomes literal spaces.+ var end = to;+ while (end > from &&+ getCodePoint(end - 1) == 0 &&+ !isWideContinuation(end - 1)) {+ end--;+ }++ final builder = StringBuffer();+ for (var i = from; i < end; i++) {+ final codePoint = getCodePoint(i);+ if (codePoint == 0) {+ if (!isWideContinuation(i)) {+ // A gap left by cursor-forward/erase rather than a literal space byte — TUI output+ // (Claude Code, Codex, …) positions the cursor instead of printing spaces for+ // layout/indentation, so treating this as "nothing" glued adjacent words together and+ // ate leading indentation when the pane was copied.+ builder.writeCharCode(0x20);+ }+ continue;+ }+ final width = getWidth(i);+ if (i + width <= to) {+ builder.writeCharCode(codePoint);+ }+ }++ return builder.toString();+ }++ CellAnchor createAnchor(int offset) {+ final anchor = CellAnchor(offset, owner: this);+ _anchors.add(anchor);+ return anchor;+ }++ void dispose() {+ for (final anchor in _anchors) {+ anchor.dispose();+ }+ }++ @override+ String toString() {+ return getText();+ }+}++/// A handle to a cell in a [BufferLine] that can be used to track the location+/// of the cell. Anchors are guaranteed to be stable, retaining their relative+/// position to each other after mutations to the buffer.+class CellAnchor {+ CellAnchor(int offset, {BufferLine? owner})+ : _offset = offset,+ _owner = owner;++ int _offset;++ int get x {+ return _offset;+ }++ int get y {+ assert(attached);+ return _owner!.index;+ }++ CellOffset get offset {+ assert(attached);+ return CellOffset(_offset, _owner!.index);+ }++ BufferLine? _owner;++ BufferLine? get line => _owner;++ bool get attached => _owner?.attached ?? false;++ void reparent(BufferLine owner, int offset) {+ _owner?._anchors.remove(this);+ _owner = owner;+ _owner?._anchors.add(this);+ _offset = offset;+ }++ void reposition(int offset) {+ _offset = offset;+ }++ void dispose() {+ _owner?._anchors.remove(this);+ _owner = null;+ }++ @override+ String toString() {+ if (attached) {+ return 'CellAnchor($x, $y)';+ } else {+ return 'CellAnchor($x, detached)';+ }+ }+}diff --git a/mobile/third_party/xterm/lib/src/core/buffer/range.dart b/mobile/third_party/xterm/lib/src/core/buffer/range.dartnew file mode 100644index 000000000..2401f15fd--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/buffer/range.dart@@ -0,0 +1,55 @@+import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/buffer/segment.dart';++abstract class BufferRange {+ final CellOffset begin;++ final CellOffset end;++ const BufferRange(this.begin, this.end);++ BufferRange.collapsed(this.begin) : end = begin;++ bool get isNormalized {+ return begin.isBefore(end) || begin.isEqual(end);+ }++ bool get isCollapsed {+ return begin.isEqual(end);+ }++ BufferRange get normalized;++ /// Convert this range to segments of single lines.+ Iterable<BufferSegment> toSegments();++ /// Returns true if the given[position] is within this range.+ bool contains(CellOffset position);++ /// Returns the smallest range that contains both this range and the given+ /// [range].+ BufferRange merge(BufferRange range);++ /// Returns the smallest range that contains both this range and the given+ /// [position].+ BufferRange extend(CellOffset position);++ @override+ operator ==(Object other) {+ if (identical(this, other)) {+ return true;+ }++ if (other is! BufferRange) {+ return false;+ }++ return begin == other.begin && end == other.end;+ }++ @override+ int get hashCode => begin.hashCode ^ end.hashCode;++ @override+ String toString() => 'Range($begin, $end)';+}diff --git a/mobile/third_party/xterm/lib/src/core/buffer/range_block.dart b/mobile/third_party/xterm/lib/src/core/buffer/range_block.dartnew file mode 100644index 000000000..33c183659--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/buffer/range_block.dart@@ -0,0 +1,111 @@+import 'dart:math';++import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/buffer/range.dart';+import 'package:xterm/src/core/buffer/segment.dart';++class BufferRangeBlock extends BufferRange {+ BufferRangeBlock(super.begin, super.end);++ BufferRangeBlock.collapsed(super.begin) : super.collapsed();++ @override+ bool get isNormalized {+ // A block range is normalized if begin is the top left corner of the range+ // and end the bottom right corner.+ return (begin.isBefore(end) && begin.x <= end.x) || begin.isEqual(end);+ }++ @override+ BufferRangeBlock get normalized {+ if (isNormalized) {+ return this;+ }+ // Determine new normalized begin and end offset, such that begin is the+ // top left corner and end is the bottom right corner of the block.+ final normalBegin = CellOffset(min(begin.x, end.x), min(begin.y, end.y));+ final normalEnd = CellOffset(max(begin.x, end.x), max(begin.y, end.y));+ return BufferRangeBlock(normalBegin, normalEnd);+ }++ @override+ Iterable<BufferSegment> toSegments() sync* {+ var begin = this.begin;+ var end = this.end;++ if (!isNormalized) {+ end = this.begin;+ begin = this.end;+ }++ final startX = min(begin.x, end.x);+ final endX = max(begin.x, end.x);+ for (var i = begin.y; i <= end.y; i++) {+ yield BufferSegment(this, i, startX, endX);+ }+ }++ @override+ bool contains(CellOffset position) {+ var begin = this.begin;+ var end = this.end;++ if (!isNormalized) {+ end = this.begin;+ begin = this.end;+ }+ if (!(begin.y <= position.y && position.y <= end.y)) {+ return false;+ }++ final startX = min(begin.x, end.x);+ final endX = max(begin.x, end.x);+ return startX <= position.x && position.x <= endX;+ }++ @override+ BufferRangeBlock merge(BufferRange range) {+ // Enlarge the block such that both borders of the range+ // are within the selected block.+ return extend(range.begin).extend(range.end);+ }++ @override+ BufferRangeBlock extend(CellOffset position) {+ // If the position is within the block, there is nothing to do.+ if (contains(position)) {+ return this;+ }+ // Otherwise normalize the block and push the borders outside up to+ // the position to which the block has to extended.+ final normal = normalized;+ final extendBegin = CellOffset(+ min(normal.begin.x, position.x),+ min(normal.begin.y, position.y),+ );+ final extendEnd = CellOffset(+ max(normal.end.x, position.x),+ max(normal.end.y, position.y),+ );+ return BufferRangeBlock(extendBegin, extendEnd);+ }++ @override+ operator ==(Object other) {+ if (identical(this, other)) {+ return true;+ }++ if (other is! BufferRangeBlock) {+ return false;+ }++ return begin == other.begin && end == other.end;+ }++ @override+ int get hashCode => begin.hashCode ^ end.hashCode;++ @override+ String toString() => 'Block Range($begin, $end)';+}diff --git a/mobile/third_party/xterm/lib/src/core/buffer/range_line.dart b/mobile/third_party/xterm/lib/src/core/buffer/range_line.dartnew file mode 100644index 000000000..83218eb9b--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/buffer/range_line.dart@@ -0,0 +1,66 @@+import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/buffer/range.dart';+import 'package:xterm/src/core/buffer/segment.dart';++class BufferRangeLine extends BufferRange {+ BufferRangeLine(super.begin, super.end);++ BufferRangeLine.collapsed(super.begin) : super.collapsed();++ @override+ BufferRangeLine get normalized {+ return isNormalized ? this : BufferRangeLine(end, begin);+ }++ @override+ Iterable<BufferSegment> toSegments() sync* {+ final self = normalized;+ for (var i = self.begin.y; i <= self.end.y; i++) {+ var startX = i == self.begin.y ? self.begin.x : null;+ var endX = i == self.end.y ? self.end.x : null;+ yield BufferSegment(this, i, startX, endX);+ }+ }++ @override+ bool contains(CellOffset position) {+ final self = normalized;+ return self.begin.isBeforeOrSame(position) &&+ self.end.isAfterOrSame(position);+ }++ @override+ BufferRangeLine merge(BufferRange range) {+ final self = normalized;+ final begin = self.begin.isBefore(range.begin) ? self.begin : range.begin;+ final end = self.end.isAfter(range.end) ? self.end : range.end;+ return BufferRangeLine(begin, end);+ }++ @override+ BufferRangeLine extend(CellOffset position) {+ final self = normalized;+ final begin = self.begin.isAfter(position) ? position : self.begin;+ final end = self.end.isBefore(position) ? position : self.end;+ return BufferRangeLine(begin, end);+ }++ @override+ operator ==(Object other) {+ if (identical(this, other)) {+ return true;+ }++ if (other is! BufferRangeLine) {+ return false;+ }++ return begin == other.begin && end == other.end;+ }++ @override+ int get hashCode => begin.hashCode ^ end.hashCode;++ @override+ String toString() => 'Line Range($begin, $end)';+}diff --git a/mobile/third_party/xterm/lib/src/core/buffer/segment.dart b/mobile/third_party/xterm/lib/src/core/buffer/segment.dartnew file mode 100644index 000000000..9314ab6ce--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/buffer/segment.dart@@ -0,0 +1,58 @@+import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/buffer/range.dart';++/// A BufferSegment represents a range within a line.+class BufferSegment {+ /// The range that this segment belongs to.+ final BufferRange range;++ /// The line that this segment resides on.+ final int line;++ /// The start position of this segment. [null] means the start of the line.+ final int? start;++ /// The end position of this segment. [null] means the end of the line.+ /// Should be greater than or equal to [start].+ final int? end;++ const BufferSegment(this.range, this.line, this.start, this.end)+ : assert((start != null && end != null) ? start <= end : true);++ bool isWithin(CellOffset position) {+ if (position.y != line) {+ return false;+ }++ if (start != null && position.x < start!) {+ return false;+ }++ if (end != null && position.x > end!) {+ return false;+ }++ return true;+ }++ @override+ String toString() {+ final start = this.start != null ? this.start.toString() : 'start';+ final end = this.end != null ? this.end.toString() : 'end';+ return 'Segment($line, $start -> $end)';+ }++ @override+ int get hashCode =>+ range.hashCode ^ line.hashCode ^ start.hashCode ^ end.hashCode;++ @override+ bool operator ==(Object other) =>+ identical(this, other) ||+ other is BufferSegment &&+ runtimeType == other.runtimeType &&+ range == other.range &&+ line == other.line &&+ start == other.start &&+ end == other.end;+}diff --git a/mobile/third_party/xterm/lib/src/core/cell.dart b/mobile/third_party/xterm/lib/src/core/cell.dartnew file mode 100644index 000000000..c52039ff1--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/cell.dart@@ -0,0 +1,66 @@+import 'package:xterm/src/utils/hash_values.dart';++class CellData {+ CellData({+ required this.foreground,+ required this.background,+ required this.flags,+ required this.content,+ });++ factory CellData.empty() {+ return CellData(+ foreground: 0,+ background: 0,+ flags: 0,+ content: 0,+ );+ }++ int foreground;++ int background;++ int flags;++ int content;++ int getHash() {+ return hashValues(foreground, background, flags, content);+ }++ @override+ String toString() {+ return 'CellData{foreground: $foreground, background: $background, flags: $flags, content: $content}';+ }+}++abstract class CellAttr {+ static const bold = 1 << 0;+ static const faint = 1 << 1;+ static const italic = 1 << 2;+ static const underline = 1 << 3;+ static const blink = 1 << 4;+ static const inverse = 1 << 5;+ static const invisible = 1 << 6;+ static const strikethrough = 1 << 7;+}++abstract class CellColor {+ static const valueMask = 0xFFFFFF;++ static const typeShift = 25;+ static const typeMask = 3 << typeShift;++ static const normal = 0 << typeShift;+ static const named = 1 << typeShift;+ static const palette = 2 << typeShift;+ static const rgb = 3 << typeShift;+}++abstract class CellContent {+ static const codepointMask = 0x1fffff;++ static const widthShift = 22;+ // static const widthMask = 3 << widthShift;+}diff --git a/mobile/third_party/xterm/lib/src/core/charset.dart b/mobile/third_party/xterm/lib/src/core/charset.dartnew file mode 100644index 000000000..3659810ac--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/charset.dart@@ -0,0 +1,95 @@+typedef CharsetTranslator = int Function(int);++final _charsets = <int, CharsetTranslator>{+ '0'.codeUnitAt(0): decSpecGraphicsTranslator,+ 'B'.codeUnitAt(0): asciiTranslator,+};++class Charset {+ var _charsetMap = <int, CharsetTranslator>{};+ var _currentIndex = 0;++ var _savedCharsetMap = <int, CharsetTranslator>{};+ var _savedIndex = 0;++ var _cached = asciiTranslator;++ void _updateCache() {+ _cached = _charsetMap[_currentIndex] ?? asciiTranslator;+ }++ int translate(int codePoint) {+ return _cached(codePoint);+ }++ void designate(int index, int name) {+ final charset = _charsets[name];+ if (charset != null) {+ _charsetMap[index] = charset;+ _updateCache();+ }+ }++ void use(int index) {+ _currentIndex = index;+ _updateCache();+ }++ void save() {+ _savedCharsetMap = Map.from(_charsetMap);+ _savedIndex = _currentIndex;+ }++ void restore() {+ _charsetMap = _savedCharsetMap;+ _currentIndex = _savedIndex;+ _updateCache();+ }+}++const decSpecGraphics = <int, int>{+ 0x5f: 0x00A0, // NO-BREAK SPACE+ 0x60: 0x25C6, // BLACK DIAMOND+ 0x61: 0x2592, // MEDIUM SHADE+ 0x62: 0x2409, // SYMBOL FOR HORIZONTAL TABULATION+ 0x63: 0x240C, // SYMBOL FOR FORM FEED+ 0x64: 0x240D, // SYMBOL FOR CARRIAGE RETURN+ 0x65: 0x240A, // SYMBOL FOR LINE FEED+ 0x66: 0x00B0, // DEGREE SIGN+ 0x67: 0x00B1, // PLUS-MINUS SIGN+ 0x68: 0x2424, // SYMBOL FOR NEWLINE+ 0x69: 0x240B, // SYMBOL FOR VERTICAL TABULATION+ 0x6a: 0x2518, // BOX DRAWINGS LIGHT UP AND LEFT+ 0x6b: 0x2510, // BOX DRAWINGS LIGHT DOWN AND LEFT+ 0x6c: 0x250C, // BOX DRAWINGS LIGHT DOWN AND RIGHT+ 0x6d: 0x2514, // BOX DRAWINGS LIGHT UP AND RIGHT+ 0x6e: 0x253C, // BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL+ 0x6f: 0x23BA, // HORIZONTAL SCAN LINE-1+ 0x70: 0x23BB, // HORIZONTAL SCAN LINE-3+ 0x71: 0x2500, // BOX DRAWINGS LIGHT HORIZONTAL+ 0x72: 0x23BC, // HORIZONTAL SCAN LINE-7+ 0x73: 0x23BD, // HORIZONTAL SCAN LINE-9+ 0x74: 0x251C, // BOX DRAWINGS LIGHT VERTICAL AND RIGHT+ 0x75: 0x2524, // BOX DRAWINGS LIGHT VERTICAL AND LEFT+ 0x76: 0x2534, // BOX DRAWINGS LIGHT UP AND HORIZONTAL+ 0x77: 0x252C, // BOX DRAWINGS LIGHT DOWN AND HORIZONTAL+ 0x78: 0x2502, // BOX DRAWINGS LIGHT VERTICAL+ 0x79: 0x2264, // LESS-THAN OR EQUAL TO+ 0x7a: 0x2265, // GREATER-THAN OR EQUAL TO+ 0x7b: 0x03C0, // GREEK SMALL LETTER PI+ 0x7c: 0x2260, // NOT EQUAL TO+ 0x7d: 0x00A3, // POUND SIGN+ 0x7e: 0x00B7, // MIDDLE DOT+};++int asciiTranslator(int codePoint) {+ return codePoint;+}++int decSpecGraphicsTranslator(int codePoint) {+ if (codePoint >= 127) {+ return codePoint;+ }++ return decSpecGraphics[codePoint] ?? codePoint;+}diff --git a/mobile/third_party/xterm/lib/src/core/color.dart b/mobile/third_party/xterm/lib/src/core/color.dartnew file mode 100644index 000000000..716219c3d--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/color.dart@@ -0,0 +1,19 @@+abstract class NamedColor {+ static const black = 0;+ static const red = 1;+ static const green = 2;+ static const yellow = 3;+ static const blue = 4;+ static const magenta = 5;+ static const cyan = 6;+ static const white = 7;++ static const brightBlack = 8;+ static const brightRed = 9;+ static const brightGreen = 10;+ static const brightYellow = 11;+ static const brightBlue = 12;+ static const brightMagenta = 13;+ static const brightCyan = 14;+ static const brightWhite = 15;+}diff --git a/mobile/third_party/xterm/lib/src/core/cursor.dart b/mobile/third_party/xterm/lib/src/core/cursor.dartnew file mode 100644index 000000000..ce08610d8--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/cursor.dart@@ -0,0 +1,137 @@+import 'package:xterm/src/core/cell.dart';++class CursorStyle {+ int foreground;++ int background;++ int attrs;++ CursorStyle({this.foreground = 0, this.background = 0, this.attrs = 0});++ static final empty = CursorStyle();++ void setBold() {+ attrs |= CellAttr.bold;+ }++ void setFaint() {+ attrs |= CellAttr.faint;+ }++ void setItalic() {+ attrs |= CellAttr.italic;+ }++ void setUnderline() {+ attrs |= CellAttr.underline;+ }++ void setBlink() {+ attrs |= CellAttr.blink;+ }++ void setInverse() {+ attrs |= CellAttr.inverse;+ }++ void setInvisible() {+ attrs |= CellAttr.invisible;+ }++ void setStrikethrough() {+ attrs |= CellAttr.strikethrough;+ }++ void unsetBold() {+ attrs &= ~CellAttr.bold;+ }++ void unsetFaint() {+ attrs &= ~CellAttr.faint;+ }++ void unsetItalic() {+ attrs &= ~CellAttr.italic;+ }++ void unsetUnderline() {+ attrs &= ~CellAttr.underline;+ }++ void unsetBlink() {+ attrs &= ~CellAttr.blink;+ }++ void unsetInverse() {+ attrs &= ~CellAttr.inverse;+ }++ void unsetInvisible() {+ attrs &= ~CellAttr.invisible;+ }++ void unsetStrikethrough() {+ attrs &= ~CellAttr.strikethrough;+ }++ bool get isBold => (attrs & CellAttr.bold) != 0;++ bool get isFaint => (attrs & CellAttr.faint) != 0;++ bool get isItalis => (attrs & CellAttr.italic) != 0;++ bool get isUnderline => (attrs & CellAttr.underline) != 0;++ bool get isBlink => (attrs & CellAttr.blink) != 0;++ bool get isInverse => (attrs & CellAttr.inverse) != 0;++ bool get isInvisible => (attrs & CellAttr.invisible) != 0;++ void setForegroundColor16(int color) {+ foreground = color | CellColor.named;+ }++ void setForegroundColor256(int color) {+ foreground = color | CellColor.palette;+ }++ void setForegroundColorRgb(int r, int g, int b) {+ foreground = (r << 16) | (g << 8) | b | CellColor.rgb;+ }++ void resetForegroundColor() {+ foreground = 0; // | CellColor.normal;+ }++ void setBackgroundColor16(int color) {+ background = color | CellColor.named;+ }++ void setBackgroundColor256(int color) {+ background = color | CellColor.palette;+ }++ void setBackgroundColorRgb(int r, int g, int b) {+ background = (r << 16) | (g << 8) | b | CellColor.rgb;+ }++ void resetBackgroundColor() {+ background = 0; // | CellColor.normal;+ }++ void reset() {+ foreground = 0;+ background = 0;+ attrs = 0;+ }+}++class CursorPosition {+ int x;++ int y;++ CursorPosition(this.x, this.y);+}diff --git a/mobile/third_party/xterm/lib/src/core/escape/emitter.dart b/mobile/third_party/xterm/lib/src/core/escape/emitter.dartnew file mode 100644index 000000000..faf5d401d--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/escape/emitter.dart@@ -0,0 +1,33 @@+class EscapeEmitter {+ const EscapeEmitter();++ String primaryDeviceAttributes() {+ return '\x1b[?1;2c';+ }++ String secondaryDeviceAttributes() {+ const model = 0;+ const version = 0;+ return '\x1b[>$model;$version;0c';+ }++ String tertiaryDeviceAttributes() {+ return '\x1bP!|00000000\x1b\\';+ }++ String operatingStatus() {+ return '\x1b[0n';+ }++ String cursorPosition(int x, int y) {+ return '\x1b[$y;${x}R';+ }++ String bracketedPaste(String text) {+ return '\x1b[200~$text\x1b[201~';+ }++ String size(int rows, int cols) {+ return '\x1b[8;$rows;${cols}t';+ }+}diff --git a/mobile/third_party/xterm/lib/src/core/escape/handler.dart b/mobile/third_party/xterm/lib/src/core/escape/handler.dartnew file mode 100644index 000000000..166fb485c--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/escape/handler.dart@@ -0,0 +1,215 @@+import 'package:xterm/src/core/mouse/mode.dart';++abstract class EscapeHandler {+ void writeChar(int char);++ /* SBC */++ void bell();++ void backspaceReturn();++ void tab();++ void lineFeed();++ void carriageReturn();++ void shiftOut();++ void shiftIn();++ void unknownSBC(int char);++ /* ANSI sequence */++ void saveCursor();++ void restoreCursor();++ void index();++ void nextLine();++ void setTapStop();++ void reverseIndex();++ void designateCharset(int charset, int name);++ void unkownEscape(int char);++ /* CSI */++ void repeatPreviousCharacter(int n);++ void setCursor(int x, int y);++ void setCursorX(int x);++ void setCursorY(int y);++ void sendPrimaryDeviceAttributes();++ void clearTabStopUnderCursor();++ void clearAllTabStops();++ void moveCursorX(int offset);++ void moveCursorY(int n);++ void sendSecondaryDeviceAttributes();++ void sendTertiaryDeviceAttributes();++ void sendOperatingStatus();++ void sendCursorPosition();++ void setMargins(int i, [int? bottom]);++ void cursorNextLine(int amount);++ void cursorPrecedingLine(int amount);++ void eraseDisplayBelow();++ void eraseDisplayAbove();++ void eraseDisplay();++ void eraseScrollbackOnly();++ void eraseLineRight();++ void eraseLineLeft();++ void eraseLine();++ void insertLines(int amount);++ void deleteLines(int amount);++ void deleteChars(int amount);++ void scrollUp(int amount);++ void scrollDown(int amount);++ void eraseChars(int amount);++ void insertBlankChars(int amount);++ void unknownCSI(int finalByte);++ /* Modes */++ void setInsertMode(bool enabled);++ void setLineFeedMode(bool enabled);++ void setUnknownMode(int mode, bool enabled);++ /* DEC Private modes */++ void setCursorKeysMode(bool enabled);++ void setReverseDisplayMode(bool enabled);++ void setOriginMode(bool enabled);++ void setColumnMode(bool enabled);++ void setAutoWrapMode(bool enabled);++ void setMouseMode(MouseMode mode);++ void setCursorBlinkMode(bool enabled);++ void setCursorVisibleMode(bool enabled);++ void useAltBuffer();++ void useMainBuffer();++ void clearAltBuffer();++ void setAppKeypadMode(bool enabled);++ void setReportFocusMode(bool enabled);++ void setMouseReportMode(MouseReportMode mode);++ void setAltBufferMouseScrollMode(bool enabled);++ void setBracketedPasteMode(bool enabled);++ void setUnknownDecMode(int mode, bool enabled);++ void resize(int cols, int rows);++ void sendSize();++ /* Select Graphic Rendition (SGR) */++ void resetCursorStyle();++ void setCursorBold();++ void setCursorFaint();++ void setCursorItalic();++ void setCursorUnderline();++ void setCursorBlink();++ void setCursorInverse();++ void setCursorInvisible();++ void setCursorStrikethrough();++ void unsetCursorBold();++ void unsetCursorFaint();++ void unsetCursorItalic();++ void unsetCursorUnderline();++ void unsetCursorBlink();++ void unsetCursorInverse();++ void unsetCursorInvisible();++ void unsetCursorStrikethrough();++ void setForegroundColor16(int color);++ void setForegroundColor256(int index);++ void setForegroundColorRgb(int r, int g, int b);++ void resetForeground();++ void setBackgroundColor16(int color);++ void setBackgroundColor256(int index);++ void setBackgroundColorRgb(int r, int g, int b);++ void resetBackground();++ void unsupportedStyle(int param);++ /* OSC */++ void setTitle(String name);++ void setIconName(String name);++ void unknownOSC(String code, List<String> args);+}diff --git a/mobile/third_party/xterm/lib/src/core/escape/parser.dart b/mobile/third_party/xterm/lib/src/core/escape/parser.dartnew file mode 100644index 000000000..7571a9e18--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/escape/parser.dart@@ -0,0 +1,1199 @@+import 'package:xterm/src/core/color.dart';+import 'package:xterm/src/core/mouse/mode.dart';+import 'package:xterm/src/core/escape/handler.dart';+import 'package:xterm/src/utils/ascii.dart';+import 'package:xterm/src/utils/byte_consumer.dart';+import 'package:xterm/src/utils/char_code.dart';+import 'package:xterm/src/utils/lookup_table.dart';++/// [EscapeParser] translates control characters and escape sequences into+/// function calls that the terminal can handle.+///+/// Design goals:+/// * Zero object allocation during processing.+/// * No internal state. Same input will always produce same output.+class EscapeParser {+ final EscapeHandler handler;++ EscapeParser(this.handler);++ final _queue = ByteConsumer();++ /// Start of sequence or character being processed. Useful for debugging.+ var tokenBegin = 0;++ /// End of sequence or character being processed. Useful for debugging.+ int get tokenEnd => _queue.totalConsumed;++ void write(String chunk) {+ _queue.unrefConsumedBlocks();+ _queue.add(chunk);+ _process();+ }++ void _process() {+ while (_queue.isNotEmpty) {+ tokenBegin = _queue.totalConsumed;+ final char = _queue.consume();++ if (char == Ascii.ESC) {+ final processed = _processEscape();+ if (!processed) {+ _queue.rollback(tokenEnd - tokenBegin);+ return;+ }+ } else {+ _processChar(char);+ }+ }+ }++ void _processChar(int char) {+ if (char > _sbcHandlers.maxIndex) {+ handler.writeChar(char);+ return;+ }++ final sbcHandler = _sbcHandlers[char];+ if (sbcHandler == null) {+ handler.unkownEscape(char);+ return;+ }++ sbcHandler();+ }++ /// Processes a sequence of characters that starts with an escape character.+ /// Returns [true] if the sequence was processed, [false] if it was not.+ bool _processEscape() {+ if (_queue.isEmpty) return false;++ final escapeChar = _queue.consume();+ final escapeHandler = _escHandlers[escapeChar];++ if (escapeHandler == null) {+ handler.unkownEscape(escapeChar);+ return true;+ }++ return escapeHandler();+ }++ late final _sbcHandlers = FastLookupTable<_SbcHandler>({+ 0x07: handler.bell,+ 0x08: handler.backspaceReturn,+ 0x09: handler.tab,+ 0x0a: handler.lineFeed,+ 0x0b: handler.lineFeed,+ 0x0c: handler.lineFeed,+ 0x0d: handler.carriageReturn,+ 0x0e: handler.shiftOut,+ 0x0f: handler.shiftIn,+ });++ late final _escHandlers = FastLookupTable<_EscHandler>({+ '['.charCode: _escHandleCSI,+ ']'.charCode: _escHandleOSC,+ '7'.charCode: _escHandleSaveCursor,+ '8'.charCode: _escHandleRestoreCursor,+ 'D'.charCode: _escHandleIndex,+ 'E'.charCode: _escHandleNextLine,+ 'H'.charCode: _escHandleTabSet,+ 'M'.charCode: _escHandleReverseIndex,+ 'P'.charCode: _escHandleStringSequence, // DCS (incl. Sixel, tmux passthrough)+ '_'.charCode: _escHandleStringSequence, // APC+ '^'.charCode: _escHandleStringSequence, // PM+ 'X'.charCode: _escHandleStringSequence, // SOS+ // 'c'.charCode: _unsupportedHandler,+ // '#'.charCode: _unsupportedHandler,+ '('.charCode: _escHandleDesignateCharset0, // SCS - G0+ ')'.charCode: _escHandleDesignateCharset1, // SCS - G1+ // '*'.charCode: _voidHandler(1), // TODO: G2 (vt220)+ // '+'.charCode: _voidHandler(1), // TODO: G3 (vt220)+ '>'.charCode: _escHandleResetAppKeypadMode, // TODO: Normal Keypad+ '='.charCode: _escHandleSetAppKeypadMode, // TODO: Application Keypad+ });++ /// `ESC P` DCS, and its siblings `ESC _` APC, `ESC ^` PM, `ESC X` SOS.+ ///+ /// We render none of them, but they still have to be SWALLOWED. Each carries a+ /// body that runs until String Terminator, and leaving that body to the normal+ /// parser puts it on screen as text.+ ///+ /// tmux wraps passthrough exactly this way — `ESC P tmux; <body> ESC \` — so a+ /// program asking the outer terminal for its background colour from inside tmux+ /// used to paint `tmux;]11;?` into the pane: `ESC P` was an unknown escape, then+ /// `tmux;` printed, then the body's doubled `ESC ESC` was eaten as another+ /// unknown escape, then `]11;?` printed too.+ bool _escHandleStringSequence() => _consumeStringSequence();++ /// Consumes a string sequence's body. Only `ESC \` (ST) ends it: tmux DOUBLES+ /// every ESC inside its body, so stopping at the first one would hand the rest+ /// back to the text path — the very bug this exists to close. BEL does not end+ /// it either, because an inner OSC's own BEL sits in the middle of that body.+ ///+ /// Returns false when the queue runs dry so the parser rolls back and waits for+ /// the rest, the same contract [_consumeOsc] keeps — a sequence can straddle+ /// two chunks of pty output.+ bool _consumeStringSequence() {+ while (true) {+ if (_queue.isEmpty) return false;+ if (_queue.consume() != Ascii.ESC) continue;+ if (_queue.isEmpty) return false;+ if (_queue.consume() == Ascii.backslash) return true;+ }+ }++ /// `ESC 7` Save Cursor (DECSC)+ ///+ /// https://terminalguide.namepad.de/seq/a_esc_a7/+ bool _escHandleSaveCursor() {+ handler.saveCursor();+ return true;+ }++ /// `ESC 8` Restore Cursor (DECRC)+ ///+ /// https://terminalguide.namepad.de/seq/a_esc_a8/+ bool _escHandleRestoreCursor() {+ handler.restoreCursor();+ return true;+ }++ /// `ESC D` Index (IND)+ ///+ /// https://terminalguide.namepad.de/seq/a_esc_cd/+ bool _escHandleIndex() {+ handler.index();+ return true;+ }++ /// `ESC E` Next Line (NEL)+ ///+ /// https://terminalguide.namepad.de/seq/a_esc_ce/+ bool _escHandleNextLine() {+ handler.nextLine();+ return true;+ }++ /// `ESC H` Horizontal Tab Set (HTS)+ ///+ /// https://terminalguide.namepad.de/seq/a_esc_ch/+ bool _escHandleTabSet() {+ handler.setTapStop();+ return true;+ }++ /// `ESC M` Reverse Index (RI)+ ///+ /// https://terminalguide.namepad.de/seq/a_esc_cm/+ bool _escHandleReverseIndex() {+ handler.reverseIndex();+ return true;+ }++ bool _escHandleDesignateCharset0() {+ if (_queue.isEmpty) return false;+ int name = _queue.consume();+ handler.designateCharset(0, name);+ return true;+ }++ bool _escHandleDesignateCharset1() {+ if (_queue.isEmpty) return false;+ int name = _queue.consume();+ handler.designateCharset(1, name);+ return true;+ }++ /// `ESC >` Reset Application Keypad Mode (DECKPNM)+ ///+ /// https://terminalguide.namepad.de/seq/a_esc_x3c_greater_than/+ bool _escHandleSetAppKeypadMode() {+ handler.setAppKeypadMode(true);+ return true;+ }++ /// `ESC =` Set Application Keypad Mode (DECKPAM)+ ///+ /// https://terminalguide.namepad.de/seq/a_esc_x3d_equals/+ bool _escHandleResetAppKeypadMode() {+ handler.setAppKeypadMode(false);+ return true;+ }++ bool _escHandleCSI() {+ final consumed = _consumeCsi();+ if (!consumed) return false;++ final csiHandler = _csiHandlers[_csi.finalByte];++ if (csiHandler == null) {+ handler.unknownCSI(_csi.finalByte);+ } else {+ csiHandler();+ }++ return true;+ }++ /// The last parsed [_Csi]. This is a mutable singletion by design to reduce+ /// object allocations.+ final _csi = _Csi(finalByte: 0, params: []);++ /// Parse a CSI from the head of the queue. Return false if the CSI isn't+ /// complete. After a CSI is successfully parsed, [_csi] is updated.+ bool _consumeCsi() {+ if (_queue.isEmpty) {+ return false;+ }++ _csi.params.clear();++ // test whether the csi is a `CSI ? Ps ...` or `CSI Ps ...`+ final prefix = _queue.peek();+ if (prefix >= Ascii.colon && prefix <= Ascii.questionMark) {+ _csi.prefix = prefix;+ _queue.consume();+ } else {+ _csi.prefix = null;+ }++ var param = 0;+ var hasParam = false;+ while (true) {+ // The sequence isn't completed, just ignore it.+ if (_queue.isEmpty) {+ return false;+ }++ final char = _queue.consume();++ if (char == Ascii.semicolon) {+ if (hasParam) {+ _csi.params.add(param);+ }+ param = 0;+ continue;+ }++ if (char >= Ascii.num0 && char <= Ascii.num9) {+ hasParam = true;+ param *= 10;+ param += char - Ascii.num0;+ continue;+ }++ if (char > Ascii.NULL && char < Ascii.num0) {+ // intermediates.add(char);+ continue;+ }++ if (char >= Ascii.atSign && char <= Ascii.tilde) {+ if (hasParam) {+ _csi.params.add(param);+ }++ _csi.finalByte = char;+ return true;+ }+ }+ }++ late final _csiHandlers = FastLookupTable<_CsiHandler>({+ // 'a'.codeUnitAt(0): _csiHandleCursorHorizontalRelative,+ 'b'.codeUnitAt(0): _csiHandleRepeatPreviousCharacter,+ 'c'.codeUnitAt(0): _csiHandleSendDeviceAttributes,+ 'd'.codeUnitAt(0): _csiHandleLinePositionAbsolute,+ 'f'.codeUnitAt(0): _csiHandleCursorPosition,+ 'g'.codeUnitAt(0): _csiHandelClearTabStop,+ 'h'.codeUnitAt(0): _csiHandleMode,+ 'l'.codeUnitAt(0): _csiHandleMode,+ 'm'.codeUnitAt(0): _csiHandleSgr,+ 'n'.codeUnitAt(0): _csiHandleDeviceStatusReport,+ 'r'.codeUnitAt(0): _csiHandleSetMargins,+ 't'.codeUnitAt(0): _csiWindowManipulation,+ 'A'.codeUnitAt(0): _csiHandleCursorUp,+ 'B'.codeUnitAt(0): _csiHandleCursorDown,+ 'C'.codeUnitAt(0): _csiHandleCursorForward,+ 'D'.codeUnitAt(0): _csiHandleCursorBackward,+ 'E'.codeUnitAt(0): _csiHandleCursorNextLine,+ 'F'.codeUnitAt(0): _csiHandleCursorPrecedingLine,+ 'G'.codeUnitAt(0): _csiHandleCursorHorizontalAbsolute,+ 'H'.codeUnitAt(0): _csiHandleCursorPosition,+ 'J'.codeUnitAt(0): _csiHandleEraseDisplay,+ 'K'.codeUnitAt(0): _csiHandleEraseLine,+ 'L'.codeUnitAt(0): _csiHandleInsertLines,+ 'M'.codeUnitAt(0): _csiHandleDeleteLines,+ 'P'.codeUnitAt(0): _csiHandleDelete,+ 'S'.codeUnitAt(0): _csiHandleScrollUp,+ 'T'.codeUnitAt(0): _csiHandleScrollDown,+ 'X'.codeUnitAt(0): _csiHandleEraseCharacters,+ '@'.codeUnitAt(0): _csiHandleInsertBlankCharacters,+ });++ /// `ESC [ Ps a` Cursor Horizontal Position Relative (HPR)+ ///+ /// https://terminalguide.namepad.de/seq/csi_sa/+ // void _csiHandleCursorHorizontalRelative() {+ // if (_csi.params.isEmpty) {+ // handler.cursorHorizontal(1);+ // } else {+ // handler.cursorHorizontal(_csi.params[0]);+ // }+ // }++ /// `ESC [ Ps b` Repeat Previous Character (REP)+ ///+ /// https://terminalguide.namepad.de/seq/csi_sb/+ void _csiHandleRepeatPreviousCharacter() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ if (amount == 0) amount = 1;+ }++ handler.repeatPreviousCharacter(amount);+ }++ /// `ESC [ Ps c` Device Attributes (DA)+ ///+ /// https://terminalguide.namepad.de/seq/csi_sc/+ void _csiHandleSendDeviceAttributes() {+ switch (_csi.prefix) {+ case Ascii.greaterThan:+ return handler.sendSecondaryDeviceAttributes();+ case Ascii.equal:+ return handler.sendTertiaryDeviceAttributes();+ default:+ handler.sendPrimaryDeviceAttributes();+ }+ }++ /// `ESC [ Ps d` Cursor Vertical Position Absolute (VPA)+ ///+ /// https://terminalguide.namepad.de/seq/csi_sd/+ void _csiHandleLinePositionAbsolute() {+ var y = 1;++ if (_csi.params.isNotEmpty) {+ y = _csi.params[0];+ }++ handler.setCursorY(y - 1);+ }++ /// `ESC [ Ps ; Ps f` Alias: Set Cursor Position+ ///+ /// https://terminalguide.namepad.de/seq/csi_sf/+ void _csiHandleCursorPosition() {+ var row = 1;+ var col = 1;++ if (_csi.params.length == 2) {+ row = _csi.params[0];+ col = _csi.params[1];+ }++ handler.setCursor(col - 1, row - 1);+ }++ /// `ESC [ Ps g` Tab Clear (TBC)+ ///+ /// https://terminalguide.namepad.de/seq/csi_sg/+ void _csiHandelClearTabStop() {+ var cmd = 0;++ if (_csi.params.length == 1) {+ cmd = _csi.params[0];+ }++ switch (cmd) {+ case 0:+ return handler.clearTabStopUnderCursor();+ default:+ return handler.clearAllTabStops();+ }+ }++ /// - `ESC [ [ Pm ] h Set Mode (SM)` https://terminalguide.namepad.de/seq/csi_sm/+ /// - `ESC [ ? [ Pm ] h` Set Mode (?) (SM) https://terminalguide.namepad.de/seq/csi_sh__p/+ /// - `ESC [ [ Pm ] l` Reset Mode (RM) https://terminalguide.namepad.de/seq/csi_rm/+ /// - `ESC [ ? [ Pm ] l` Reset Mode (?) (RM) https://terminalguide.namepad.de/seq/csi_sl__p/+ void _csiHandleMode() {+ final isEnabled = _csi.finalByte == Ascii.h;++ final isDecModes = _csi.prefix == Ascii.questionMark;++ if (isDecModes) {+ for (var mode in _csi.params) {+ _setDecMode(mode, isEnabled);+ }+ } else {+ for (var mode in _csi.params) {+ _setMode(mode, isEnabled);+ }+ }+ }++ /// `ESC [ [ Ps ] m` Select Graphic Rendition (SGR)+ ///+ /// https://terminalguide.namepad.de/seq/csi_sm/+ void _csiHandleSgr() {+ // SGR does not accept a private prefix. In particular, xterm/Gemini sends+ // `CSI > 4 ; 2 m` to configure its keyboard protocol. Treating that+ // private command as ordinary `CSI 4 ; 2 m` turns on underline + faint,+ // so every subsequently echoed input cell looks grey and underlined until+ // the next full keyframe. Consume it without changing the cursor style.+ if (_csi.prefix != null) return;++ final params = _csi.params;++ if (params.isEmpty) {+ return handler.resetCursorStyle();+ }++ // This is a workaround for a bug in the analyzer.+ // ignore: dead_code+ for (var i = 0; i < _csi.params.length; i++) {+ final param = params[i];+ switch (param) {+ case 0:+ handler.resetCursorStyle();+ continue;+ case 1:+ handler.setCursorBold();+ continue;+ case 2:+ handler.setCursorFaint();+ continue;+ case 3:+ handler.setCursorItalic();+ continue;+ case 4:+ handler.setCursorUnderline();+ continue;+ case 5:+ handler.setCursorBlink();+ continue;+ case 7:+ handler.setCursorInverse();+ continue;+ case 8:+ handler.setCursorInvisible();+ continue;+ case 9:+ handler.setCursorStrikethrough();+ continue;++ case 21:+ handler.unsetCursorBold();+ continue;+ case 22:+ // ECMA-48 SGR 22 restores normal intensity: it clears both+ // increased intensity (bold, SGR 1) and decreased intensity+ // (faint, SGR 2). Treating it as faint-only leaves incremental+ // terminal output stuck in bold until a full keyframe rebuild.+ handler.unsetCursorBold();+ handler.unsetCursorFaint();+ continue;+ case 23:+ handler.unsetCursorItalic();+ continue;+ case 24:+ handler.unsetCursorUnderline();+ continue;+ case 25:+ handler.unsetCursorBlink();+ continue;+ case 27:+ handler.unsetCursorInverse();+ continue;+ case 28:+ handler.unsetCursorInvisible();+ continue;+ case 29:+ handler.unsetCursorStrikethrough();+ continue;++ case 30:+ handler.setForegroundColor16(NamedColor.black);+ continue;+ case 31:+ handler.setForegroundColor16(NamedColor.red);+ continue;+ case 32:+ handler.setForegroundColor16(NamedColor.green);+ continue;+ case 33:+ handler.setForegroundColor16(NamedColor.yellow);+ continue;+ case 34:+ handler.setForegroundColor16(NamedColor.blue);+ continue;+ case 35:+ handler.setForegroundColor16(NamedColor.magenta);+ continue;+ case 36:+ handler.setForegroundColor16(NamedColor.cyan);+ continue;+ case 37:+ handler.setForegroundColor16(NamedColor.white);+ continue;+ case 38:+ final mode = params[i + 1];+ switch (mode) {+ case 2:+ final r = params[i + 2];+ final g = params[i + 3];+ final b = params[i + 4];+ handler.setForegroundColorRgb(r, g, b);+ i += 4;+ break;+ case 5:+ final index = params[i + 2];+ handler.setForegroundColor256(index);+ i += 2;+ break;+ }+ continue;+ case 39:+ handler.resetForeground();+ continue;++ case 40:+ handler.setBackgroundColor16(NamedColor.black);+ continue;+ case 41:+ handler.setBackgroundColor16(NamedColor.red);+ continue;+ case 42:+ handler.setBackgroundColor16(NamedColor.green);+ continue;+ case 43:+ handler.setBackgroundColor16(NamedColor.yellow);+ continue;+ case 44:+ handler.setBackgroundColor16(NamedColor.blue);+ continue;+ case 45:+ handler.setBackgroundColor16(NamedColor.magenta);+ continue;+ case 46:+ handler.setBackgroundColor16(NamedColor.cyan);+ continue;+ case 47:+ handler.setBackgroundColor16(NamedColor.white);+ continue;+ case 48:+ final mode = params[i + 1];+ switch (mode) {+ case 2:+ final r = params[i + 2];+ final g = params[i + 3];+ final b = params[i + 4];+ handler.setBackgroundColorRgb(r, g, b);+ i += 4;+ break;+ case 5:+ final index = params[i + 2];+ handler.setBackgroundColor256(index);+ i += 2;+ break;+ }+ continue;+ case 49:+ handler.resetBackground();+ continue;++ case 90:+ handler.setForegroundColor16(NamedColor.brightBlack);+ continue;+ case 91:+ handler.setForegroundColor16(NamedColor.brightRed);+ continue;+ case 92:+ handler.setForegroundColor16(NamedColor.brightGreen);+ continue;+ case 93:+ handler.setForegroundColor16(NamedColor.brightYellow);+ continue;+ case 94:+ handler.setForegroundColor16(NamedColor.brightBlue);+ continue;+ case 95:+ handler.setForegroundColor16(NamedColor.brightMagenta);+ continue;+ case 96:+ handler.setForegroundColor16(NamedColor.brightCyan);+ continue;+ case 97:+ handler.setForegroundColor16(NamedColor.brightWhite);+ continue;++ case 100:+ handler.setBackgroundColor16(NamedColor.brightBlack);+ continue;+ case 101:+ handler.setBackgroundColor16(NamedColor.brightRed);+ continue;+ case 102:+ handler.setBackgroundColor16(NamedColor.brightGreen);+ continue;+ case 103:+ handler.setBackgroundColor16(NamedColor.brightYellow);+ continue;+ case 104:+ handler.setBackgroundColor16(NamedColor.brightBlue);+ continue;+ case 105:+ handler.setBackgroundColor16(NamedColor.brightMagenta);+ continue;+ case 106:+ handler.setBackgroundColor16(NamedColor.brightCyan);+ continue;+ case 107:+ handler.setBackgroundColor16(NamedColor.brightWhite);+ continue;++ default:+ handler.unsupportedStyle(param);+ continue;+ }+ }+ }++ /// `ESC [ Ps n` Device Status Report [Dispatch] (DSR)+ ///+ /// https://terminalguide.namepad.de/seq/csi_sn/+ void _csiHandleDeviceStatusReport() {+ if (_csi.params.isEmpty) return;++ switch (_csi.params[0]) {+ case 5:+ return handler.sendOperatingStatus();+ case 6:+ return handler.sendCursorPosition();+ }+ }++ /// `ESC [ Ps ; Ps r` Set Top and Bottom Margins (DECSTBM)+ ///+ /// https://terminalguide.namepad.de/seq/csi_sr/+ void _csiHandleSetMargins() {+ var top = 1;+ int? bottom;++ if (_csi.params.length > 2) return;++ if (_csi.params.isNotEmpty) {+ top = _csi.params[0];++ if (_csi.params.length == 2) {+ bottom = _csi.params[1] - 1;+ }+ }++ handler.setMargins(top - 1, bottom);+ }++ /// `ESC [ Ps t` Window operations [DISPATCH]+ ///+ /// https://terminalguide.namepad.de/seq/csi_st/+ void _csiWindowManipulation() {+ // The sequence needs at least one parameter.+ if (_csi.params.isEmpty) {+ return;+ }+ // Most the commands in this group are either of the scope of this package,+ // or should be disabled for security risks.+ switch (_csi.params.first) {+ // Window handling is currently not in the scope of the package.+ case 1: // Restore Terminal Window (show window if minimized)+ case 2: // Minimize Terminal Window+ case 3: // Set Terminal Window Position+ case 4: // Set Terminal Window Size in Pixels+ case 5: // Raise Terminal Window+ case 6: // Lower Terminal Window+ case 7: // Refresh/Redraw Terminal Window+ return;+ case 8: // Set Terminal Window Size (in characters)+ // This CSI contains 2 more parameters: width and height.+ if (_csi.params.length != 3) {+ return;+ }+ final rows = _csi.params[1];+ final cols = _csi.params[2];+ handler.resize(cols, rows);+ return;+ // Window handling is currently no in the scope of the package.+ case 9: // Maximize Terminal Window+ case 10: // Alias: Maximize Terminal Window+ case 11: // Report Terminal Window State+ case 13: // Report Terminal Window Position+ case 14: // Report Terminal Window Size in Pixels+ case 15: // Report Screen Size in Pixels+ case 16: // Report Cell Size in Pixels+ return;+ case 18: // Report Terminal Size (in characters)+ handler.sendSize();+ return;+ // Screen handling is currently no in the scope of the package.+ case 19: // Report Screen Size (in characters)+ // Disabled as these can a security risk.+ case 20: // Get Icon Title+ case 21: // Get Terminal Title+ // Not implemented.+ case 22: // Push Terminal Title+ case 23: // Pop Terminal Title+ return;+ // Unknown CSI.+ default:+ return;+ }+ }++ /// `ESC [ Ps A` Cursor Up (CUU)+ ///+ /// https://terminalguide.namepad.de/seq/csi_ca/+ void _csiHandleCursorUp() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ if (amount == 0) amount = 1;+ }++ handler.moveCursorY(-amount);+ }++ /// `ESC [ Ps B` Cursor Down (CUD)+ ///+ /// https://terminalguide.namepad.de/seq/csi_cb/+ void _csiHandleCursorDown() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ if (amount == 0) amount = 1;+ }++ handler.moveCursorY(amount);+ }++ /// `ESC [ Ps C` Cursor Right (CUF)+ ///+ /// Cursor Right (CUF)+ void _csiHandleCursorForward() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ if (amount == 0) amount = 1;+ }++ handler.moveCursorX(amount);+ }++ /// `ESC [ Ps D` Cursor Left (CUB)+ ///+ /// https://terminalguide.namepad.de/seq/csi_cd/+ void _csiHandleCursorBackward() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ if (amount == 0) amount = 1;+ }++ handler.moveCursorX(-amount);+ }++ /// `ESC [ Ps E` Cursor Next Line (CNL)+ ///+ /// https://terminalguide.namepad.de/seq/csi_ce/+ void _csiHandleCursorNextLine() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ if (amount == 0) amount = 1;+ }++ handler.cursorNextLine(amount);+ }++ /// `ESC [ Ps F` Cursor Previous Line (CPL)+ ///+ /// https://terminalguide.namepad.de/seq/csi_cf/+ void _csiHandleCursorPrecedingLine() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ if (amount == 0) amount = 1;+ }++ handler.cursorPrecedingLine(amount);+ }++ void _csiHandleCursorHorizontalAbsolute() {+ var x = 1;++ if (_csi.params.isNotEmpty) {+ x = _csi.params[0];+ if (x == 0) x = 1;+ }++ handler.setCursorX(x - 1);+ }++ /// ESC [ Ps J Erase Display [Dispatch] (ED)+ ///+ /// https://terminalguide.namepad.de/seq/csi_cj/+ void _csiHandleEraseDisplay() {+ var cmd = 0;++ if (_csi.params.length == 1) {+ cmd = _csi.params[0];+ }++ switch (cmd) {+ case 0:+ return handler.eraseDisplayBelow();+ case 1:+ return handler.eraseDisplayAbove();+ case 2:+ return handler.eraseDisplay();+ case 3:+ return handler.eraseScrollbackOnly();+ }+ }++ /// `ESC [ Ps K` Erase Line [Dispatch] (EL)+ ///+ /// https://terminalguide.namepad.de/seq/csi_ck/+ void _csiHandleEraseLine() {+ var cmd = 0;++ if (_csi.params.length == 1) {+ cmd = _csi.params[0];+ }++ switch (cmd) {+ case 0:+ return handler.eraseLineRight();+ case 1:+ return handler.eraseLineLeft();+ case 2:+ return handler.eraseLine();+ }+ }++ /// `ESC [ Ps L` Insert Line (IL)+ ///+ /// https://terminalguide.namepad.de/seq/csi_cl/+ void _csiHandleInsertLines() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ }++ handler.insertLines(amount);+ }++ /// ESC [ Ps M Delete Line (DL)+ ///+ /// https://terminalguide.namepad.de/seq/csi_cm/+ void _csiHandleDeleteLines() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ }++ handler.deleteLines(amount);+ }++ /// ESC [ Ps P Delete Character (DCH)+ ///+ /// https://terminalguide.namepad.de/seq/csi_cp/+ void _csiHandleDelete() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ }++ handler.deleteChars(amount);+ }++ /// `ESC [ Ps S` Scroll Up (SU)+ ///+ /// https://terminalguide.namepad.de/seq/csi_cs/+ void _csiHandleScrollUp() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ }++ handler.scrollUp(amount);+ }++ /// `ESC [ Ps T `Scroll Down (SD)+ ///+ /// https://terminalguide.namepad.de/seq/csi_ct_1param/+ void _csiHandleScrollDown() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ }++ handler.scrollDown(amount);+ }++ /// `ESC [ Ps X` Erase Character (ECH)+ ///+ /// https://terminalguide.namepad.de/seq/csi_cx/+ void _csiHandleEraseCharacters() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ }++ handler.eraseChars(amount);+ }++ /// `ESC [ Ps @` Insert Blanks (ICH)+ ///+ /// https://terminalguide.namepad.de/seq/csi_x40_at/+ ///+ /// Inserts amount spaces at current cursor position moving existing cell+ /// contents to the right. The contents of the amount right-most columns in+ /// the scroll region are lost. The cursor position is not changed.+ void _csiHandleInsertBlankCharacters() {+ var amount = 1;++ if (_csi.params.isNotEmpty) {+ amount = _csi.params[0];+ }++ handler.insertBlankChars(amount);+ }++ void _setMode(int mode, bool enabled) {+ switch (mode) {+ case 4:+ return handler.setInsertMode(enabled);+ case 20:+ return handler.setLineFeedMode(enabled);+ default:+ return handler.setUnknownMode(mode, enabled);+ }+ }++ void _setDecMode(int mode, bool enabled) {+ switch (mode) {+ case 1:+ return handler.setCursorKeysMode(enabled);+ case 3:+ return handler.setColumnMode(enabled);+ case 5:+ return handler.setReverseDisplayMode(enabled);+ case 6:+ return handler.setOriginMode(enabled);+ case 7:+ return handler.setAutoWrapMode(enabled);+ case 9:+ return enabled+ ? handler.setMouseMode(MouseMode.clickOnly)+ : handler.setMouseMode(MouseMode.none);+ case 12:+ case 13:+ return handler.setCursorBlinkMode(enabled);+ case 25:+ return handler.setCursorVisibleMode(enabled);+ case 47:+ if (enabled) {+ return handler.useAltBuffer();+ } else {+ return handler.useMainBuffer();+ }+ case 66:+ return handler.setAppKeypadMode(enabled);+ case 1000:+ case 10061000:+ return enabled+ ? handler.setMouseMode(MouseMode.upDownScroll)+ : handler.setMouseMode(MouseMode.none);+ case 1001:+ return enabled+ ? handler.setMouseMode(MouseMode.upDownScroll)+ : handler.setMouseMode(MouseMode.none);+ case 1002:+ return enabled+ ? handler.setMouseMode(MouseMode.upDownScrollDrag)+ : handler.setMouseMode(MouseMode.none);+ case 1003:+ return enabled+ ? handler.setMouseMode(MouseMode.upDownScrollMove)+ : handler.setMouseMode(MouseMode.none);+ case 1004:+ return handler.setReportFocusMode(enabled);+ case 1005:+ return enabled+ ? handler.setMouseReportMode(MouseReportMode.utf)+ : handler.setMouseReportMode(MouseReportMode.normal);+ case 1006:+ return enabled+ ? handler.setMouseReportMode(MouseReportMode.sgr)+ : handler.setMouseReportMode(MouseReportMode.normal);+ case 1007:+ return handler.setAltBufferMouseScrollMode(enabled);+ case 1015:+ return enabled+ ? handler.setMouseReportMode(MouseReportMode.urxvt)+ : handler.setMouseReportMode(MouseReportMode.normal);+ case 1047:+ if (enabled) {+ handler.useAltBuffer();+ } else {+ handler.clearAltBuffer();+ handler.useMainBuffer();+ }+ return;+ case 1048:+ if (enabled) {+ return handler.saveCursor();+ } else {+ return handler.restoreCursor();+ }+ case 1049:+ if (enabled) {+ handler.saveCursor();+ handler.clearAltBuffer();+ handler.useAltBuffer();+ } else {+ handler.useMainBuffer();+ }+ return;+ case 2004:+ return handler.setBracketedPasteMode(enabled);+ default:+ return handler.setUnknownDecMode(mode, enabled);+ }+ }++ /// Parse a OSC sequence from the queue. Returns true if a sequence was+ /// found and handled.+ bool _escHandleOSC() {+ final consumed = _consumeOsc();+ if (!consumed) {+ return false;+ }++ if (_osc.isEmpty) {+ return true;+ }++ // Common OSCs+ if (_osc.length >= 2) {+ final ps = _osc[0];+ final pt = _osc[1];++ switch (ps) {+ case '0':+ handler.setTitle(pt);+ handler.setIconName(pt);+ return true;+ case '1':+ handler.setIconName(pt);+ return true;+ case '2':+ handler.setTitle(pt);+ return true;+ }+ }++ // Private extensions+ handler.unknownOSC(_osc[0], _osc.sublist(1));++ return true;+ }++ final _osc = <String>[];++ bool _consumeOsc() {+ _osc.clear();+ final param = StringBuffer();++ while (true) {+ if (_queue.isEmpty) {+ return false;+ }++ final char = _queue.consume();++ // OSC terminates with BEL+ if (char == Ascii.BEL) {+ _osc.add(param.toString());+ return true;+ }++ /// OSC terminates with ST+ if (char == Ascii.ESC) {+ if (_queue.isEmpty) {+ return false;+ }++ if (_queue.consume() == Ascii.backslash) {+ _osc.add(param.toString());+ }++ return true;+ }++ /// Parse next parameter+ if (char == Ascii.semicolon) {+ _osc.add(param.toString());+ param.clear();+ continue;+ }++ param.writeCharCode(char);+ }+ }+}++class _Csi {+ _Csi({+ required this.params,+ required this.finalByte,+ // required this.intermediates,+ });++ int? prefix;++ List<int> params;++ int finalByte;+ // final List<int> intermediates;++ @override+ String toString() {+ return params.join(';') + String.fromCharCode(finalByte);+ }+}++/// Function that handles a sequence of characters that starts with an escape.+/// Returns [true] if the sequence was processed, [false] if it was not.+typedef _EscHandler = bool Function();++typedef _SbcHandler = void Function();++typedef _CsiHandler = void Function();diff --git a/mobile/third_party/xterm/lib/src/core/input/handler.dart b/mobile/third_party/xterm/lib/src/core/input/handler.dartnew file mode 100644index 000000000..6a8ed70b4--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/input/handler.dart@@ -0,0 +1,210 @@+import 'package:xterm/src/core/input/keys.dart';+import 'package:xterm/src/core/input/keytab/keytab.dart';+import 'package:xterm/src/core/state.dart';+import 'package:xterm/src/core/platform.dart';++/// The key event received from the keyboard, along with the state of the+/// modifier keys and state of the terminal. Typically consumed by the+/// [TerminalInputHandler] to produce a escape sequence that can be recognized+/// by the terminal.+///+/// See also:+/// - [TerminalInputHandler]+class TerminalKeyboardEvent {+ final TerminalKey key;++ final bool shift;++ final bool ctrl;++ final bool alt;++ final TerminalState state;++ final bool altBuffer;++ final TerminalTargetPlatform platform;++ TerminalKeyboardEvent({+ required this.key,+ required this.shift,+ required this.ctrl,+ required this.alt,+ required this.state,+ required this.altBuffer,+ required this.platform,+ });++ TerminalKeyboardEvent copyWith({+ TerminalKey? key,+ bool? shift,+ bool? ctrl,+ bool? alt,+ TerminalState? state,+ bool? altBuffer,+ TerminalTargetPlatform? platform,+ }) {+ return TerminalKeyboardEvent(+ key: key ?? this.key,+ shift: shift ?? this.shift,+ ctrl: ctrl ?? this.ctrl,+ alt: alt ?? this.alt,+ state: state ?? this.state,+ altBuffer: altBuffer ?? this.altBuffer,+ platform: platform ?? this.platform,+ );+ }+}++/// TerminalInputHandler contains the logic for translating a [TerminalKeyboardEvent]+/// into escape sequences that can be recognized by the terminal.+abstract class TerminalInputHandler {+ /// Translates a [TerminalKeyboardEvent] into an escape sequence. If the event+ /// cannot be translated, null is returned.+ String? call(TerminalKeyboardEvent event);+}++/// A [TerminalInputHandler] that chains multiple handlers together. If any+/// handler returns a non-null value, it is returned. Otherwise, null is+/// returned.+class CascadeInputHandler implements TerminalInputHandler {+ final List<TerminalInputHandler> _handlers;++ const CascadeInputHandler(this._handlers);++ @override+ String? call(TerminalKeyboardEvent event) {+ for (var handler in _handlers) {+ final result = handler(event);+ if (result != null) {+ return result;+ }+ }+ return null;+ }+}++/// The default input handler for the terminal. That is composed of a+/// [KeytabInputHandler], a [CtrlInputHandler], and a [AltInputHandler].+///+/// It's possible to override the default input handler behavior by chaining+/// another input handler before or after the default input handler using+/// [CascadeInputHandler].+///+/// See also:+/// * [CascadeInputHandler]+const defaultInputHandler = CascadeInputHandler([+ KeytabInputHandler(),+ CtrlInputHandler(),+ AltInputHandler(),+]);++/// A [TerminalInputHandler] that translates key events according to a keytab+/// file. If no keytab is provided, [Keytab.defaultKeytab] is used.+class KeytabInputHandler implements TerminalInputHandler {+ const KeytabInputHandler([this.keytab]);++ final Keytab? keytab;++ @override+ String? call(TerminalKeyboardEvent event) {+ final keytab = this.keytab ?? Keytab.defaultKeytab;++ final record = keytab.find(+ event.key,+ ctrl: event.ctrl,+ alt: event.alt,+ shift: event.shift,+ newLineMode: event.state.lineFeedMode,+ appCursorKeys: event.state.appKeypadMode,+ appKeyPad: event.state.appKeypadMode,+ appScreen: event.altBuffer,+ macos: event.platform == TerminalTargetPlatform.macos,+ );++ if (record == null) {+ return null;+ }++ var result = record.action.unescapedValue();+ result = insertModifiers(event, result);+ return result;+ }++ String insertModifiers(TerminalKeyboardEvent event, String action) {+ String? code;++ if (event.shift && event.alt && event.ctrl) {+ code = '8';+ } else if (event.ctrl && event.alt) {+ code = '7';+ } else if (event.shift && event.ctrl) {+ code = '6';+ } else if (event.ctrl) {+ code = '5';+ } else if (event.shift && event.alt) {+ code = '4';+ } else if (event.alt) {+ code = '3';+ } else if (event.shift) {+ code = '2';+ }++ if (code != null) {+ return action.replaceAll('*', code);+ }++ return action;+ }+}++/// A [TerminalInputHandler] that translates ctrl + key events into escape+/// sequences. For example, ctrl + a becomes ^A.+class CtrlInputHandler implements TerminalInputHandler {+ const CtrlInputHandler();++ @override+ String? call(TerminalKeyboardEvent event) {+ if (!event.ctrl || event.shift || event.alt) {+ return null;+ }++ final key = event.key;++ if (key.index >= TerminalKey.keyA.index &&+ key.index <= TerminalKey.keyZ.index) {+ final input = key.index - TerminalKey.keyA.index + 1;+ return String.fromCharCode(input);+ }++ return null;+ }+}++/// A [TerminalInputHandler] that translates alt + key events into escape+/// sequences. For example, alt + a becomes ^[a.+class AltInputHandler implements TerminalInputHandler {+ const AltInputHandler();++ @override+ String? call(TerminalKeyboardEvent event) {+ if (!event.alt || event.ctrl || event.shift) {+ return null;+ }++ if (event.platform == TerminalTargetPlatform.macos) {+ return null;+ }++ final key = event.key;++ if (key.index >= TerminalKey.keyA.index &&+ key.index <= TerminalKey.keyZ.index) {+ final charCode = key.index - TerminalKey.keyA.index + 65;+ final input = [0x1b, charCode];+ return String.fromCharCodes(input);+ }++ return null;+ }+}diff --git a/mobile/third_party/xterm/lib/src/core/input/keys.dart b/mobile/third_party/xterm/lib/src/core/input/keys.dartnew file mode 100644index 000000000..ed26c2da4--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/input/keys.dart@@ -0,0 +1,835 @@+enum TerminalKey {+ /// Represents the logical "None" key on the keyboard.+ none,++ /// Represents the logical "Hyper" key on the keyboard.+ hyper,++ /// Represents the logical "Super Key" key on the keyboard.+ superKey,++ /// Represents the logical "Fn Lock" key on the keyboard.+ fnLock,++ /// Represents the logical "Suspend" key on the keyboard.+ suspend,++ /// Represents the logical "Resume" key on the keyboard.+ resume,++ /// Represents the logical "Turbo" key on the keyboard.+ turbo,++ /// Represents the logical "Privacy Screen Toggle" key on the keyboard.+ privacyScreenToggle,++ /// Represents the logical "Sleep" key on the keyboard.+ sleep,++ /// Represents the logical "Wake Up" key on the keyboard.+ wakeUp,++ /// Represents the logical "Display Toggle Int Ext" key on the keyboard.+ displayToggleIntExt,++ /// Represents the logical "Usb Reserved" key on the keyboard.+ usbReserved,++ /// Represents the logical "Usb Error Roll Over" key on the keyboard.+ usbErrorRollOver,++ /// Represents the logical "Usb Post Fail" key on the keyboard.+ usbPostFail,++ /// Represents the logical "Usb Error Undefined" key on the keyboard.+ usbErrorUndefined,++ /// Represents the logical "Key A" key on the keyboard.+ keyA,++ /// Represents the logical "Key B" key on the keyboard.+ keyB,++ /// Represents the logical "Key C" key on the keyboard.+ keyC,++ /// Represents the logical "Key D" key on the keyboard.+ keyD,++ /// Represents the logical "Key E" key on the keyboard.+ keyE,++ /// Represents the logical "Key F" key on the keyboard.+ keyF,++ /// Represents the logical "Key G" key on the keyboard.+ keyG,++ /// Represents the logical "Key H" key on the keyboard.+ keyH,++ /// Represents the logical "Key I" key on the keyboard.+ keyI,++ /// Represents the logical "Key J" key on the keyboard.+ keyJ,++ /// Represents the logical "Key K" key on the keyboard.+ keyK,++ /// Represents the logical "Key L" key on the keyboard.+ keyL,++ /// Represents the logical "Key M" key on the keyboard.+ keyM,++ /// Represents the logical "Key N" key on the keyboard.+ keyN,++ /// Represents the logical "Key O" key on the keyboard.+ keyO,++ /// Represents the logical "Key P" key on the keyboard.+ keyP,++ /// Represents the logical "Key Q" key on the keyboard.+ keyQ,++ /// Represents the logical "Key R" key on the keyboard.+ keyR,++ /// Represents the logical "Key S" key on the keyboard.+ keyS,++ /// Represents the logical "Key T" key on the keyboard.+ keyT,++ /// Represents the logical "Key U" key on the keyboard.+ keyU,++ /// Represents the logical "Key V" key on the keyboard.+ keyV,++ /// Represents the logical "Key W" key on the keyboard.+ keyW,++ /// Represents the logical "Key X" key on the keyboard.+ keyX,++ /// Represents the logical "Key Y" key on the keyboard.+ keyY,++ /// Represents the logical "Key Z" key on the keyboard.+ keyZ,++ /// Represents the logical "Digit 1" key on the keyboard.+ digit1,++ /// Represents the logical "Digit 2" key on the keyboard.+ digit2,++ /// Represents the logical "Digit 3" key on the keyboard.+ digit3,++ /// Represents the logical "Digit 4" key on the keyboard.+ digit4,++ /// Represents the logical "Digit 5" key on the keyboard.+ digit5,++ /// Represents the logical "Digit 6" key on the keyboard.+ digit6,++ /// Represents the logical "Digit 7" key on the keyboard.+ digit7,++ /// Represents the logical "Digit 8" key on the keyboard.+ digit8,++ /// Represents the logical "Digit 9" key on the keyboard.+ digit9,++ /// Represents the logical "Digit 0" key on the keyboard.+ digit0,++ /// Represents the logical "Enter" key on the keyboard.+ enter,++ /// Represents the logical "Escape" key on the keyboard.+ escape,++ /// Represents the logical "Backspace" key on the keyboard.+ backspace,++ /// Represents the logical "Tab" key on the keyboard.+ tab,++ /// Represents the logical "Space" key on the keyboard.+ space,++ /// Represents the logical "Minus" key on the keyboard.+ minus,++ /// Represents the logical "Equal" key on the keyboard.+ equal,++ /// Represents the logical "Bracket Left" key on the keyboard.+ bracketLeft,++ /// Represents the logical "Bracket Right" key on the keyboard.+ bracketRight,++ /// Represents the logical "Backslash" key on the keyboard.+ backslash,++ /// Represents the logical "Semicolon" key on the keyboard.+ semicolon,++ /// Represents the logical "Quote" key on the keyboard.+ quote,++ /// Represents the logical "Backquote" key on the keyboard.+ backquote,++ /// Represents the logical "Comma" key on the keyboard.+ comma,++ /// Represents the logical "Period" key on the keyboard.+ period,++ /// Represents the logical "Slash" key on the keyboard.+ slash,++ /// Represents the logical "Caps Lock" key on the keyboard.+ capsLock,++ /// Represents the logical "F1" key on the keyboard.+ f1,++ /// Represents the logical "F2" key on the keyboard.+ f2,++ /// Represents the logical "F3" key on the keyboard.+ f3,++ /// Represents the logical "F4" key on the keyboard.+ f4,++ /// Represents the logical "F5" key on the keyboard.+ f5,++ /// Represents the logical "F6" key on the keyboard.+ f6,++ /// Represents the logical "F7" key on the keyboard.+ f7,++ /// Represents the logical "F8" key on the keyboard.+ f8,++ /// Represents the logical "F9" key on the keyboard.+ f9,++ /// Represents the logical "F10" key on the keyboard.+ f10,++ /// Represents the logical "F11" key on the keyboard.+ f11,++ /// Represents the logical "F12" key on the keyboard.+ f12,++ /// Represents the logical "Print Screen" key on the keyboard.+ printScreen,++ /// Represents the logical "Scroll Lock" key on the keyboard.+ scrollLock,++ /// Represents the logical "Pause" key on the keyboard.+ pause,++ /// Represents the logical "Insert" key on the keyboard.+ insert,++ /// Represents the logical "Home" key on the keyboard.+ home,++ /// Represents the logical "Page Up" key on the keyboard.+ pageUp,++ /// Represents the logical "Delete" key on the keyboard.+ delete,++ /// Represents the logical "End" key on the keyboard.+ end,++ /// Represents the logical "Page Down" key on the keyboard.+ pageDown,++ /// Represents the logical "Arrow Right" key on the keyboard.+ arrowRight,++ /// Represents the logical "Arrow Left" key on the keyboard.+ arrowLeft,++ /// Represents the logical "Arrow Down" key on the keyboard.+ arrowDown,++ /// Represents the logical "Arrow Up" key on the keyboard.+ arrowUp,++ /// Represents the logical "Num Lock" key on the keyboard.+ numLock,++ /// Represents the logical "Numpad Divide" key on the keyboard.+ numpadDivide,++ /// Represents the logical "Numpad Multiply" key on the keyboard.+ numpadMultiply,++ /// Represents the logical "Numpad Subtract" key on the keyboard.+ numpadSubtract,++ /// Represents the logical "Numpad Add" key on the keyboard.+ numpadAdd,++ /// Represents the logical "Numpad Enter" key on the keyboard.+ numpadEnter,++ /// Represents the logical "Numpad 1" key on the keyboard.+ numpad1,++ /// Represents the logical "Numpad 2" key on the keyboard.+ numpad2,++ /// Represents the logical "Numpad 3" key on the keyboard.+ numpad3,++ /// Represents the logical "Numpad 4" key on the keyboard.+ numpad4,++ /// Represents the logical "Numpad 5" key on the keyboard.+ numpad5,++ /// Represents the logical "Numpad 6" key on the keyboard.+ numpad6,++ /// Represents the logical "Numpad 7" key on the keyboard.+ numpad7,++ /// Represents the logical "Numpad 8" key on the keyboard.+ numpad8,++ /// Represents the logical "Numpad 9" key on the keyboard.+ numpad9,++ /// Represents the logical "Numpad 0" key on the keyboard.+ numpad0,++ /// Represents the logical "Numpad Decimal" key on the keyboard.+ numpadDecimal,++ /// Represents the logical "Intl Backslash" key on the keyboard.+ intlBackslash,++ /// Represents the logical "Context Menu" key on the keyboard.+ contextMenu,++ /// Represents the logical "Power" key on the keyboard.+ power,++ /// Represents the logical "Numpad Equal" key on the keyboard.+ numpadEqual,++ /// Represents the logical "F13" key on the keyboard.+ f13,++ /// Represents the logical "F14" key on the keyboard.+ f14,++ /// Represents the logical "F15" key on the keyboard.+ f15,++ /// Represents the logical "F16" key on the keyboard.+ f16,++ /// Represents the logical "F17" key on the keyboard.+ f17,++ /// Represents the logical "F18" key on the keyboard.+ f18,++ /// Represents the logical "F19" key on the keyboard.+ f19,++ /// Represents the logical "F20" key on the keyboard.+ f20,++ /// Represents the logical "F21" key on the keyboard.+ f21,++ /// Represents the logical "F22" key on the keyboard.+ f22,++ /// Represents the logical "F23" key on the keyboard.+ f23,++ /// Represents the logical "F24" key on the keyboard.+ f24,++ /// Represents the logical "Open" key on the keyboard.+ open,++ /// Represents the logical "Help" key on the keyboard.+ help,++ /// Represents the logical "Select" key on the keyboard.+ select,++ /// Represents the logical "Again" key on the keyboard.+ again,++ /// Represents the logical "Undo" key on the keyboard.+ undo,++ /// Represents the logical "Cut" key on the keyboard.+ cut,++ /// Represents the logical "Copy" key on the keyboard.+ copy,++ /// Represents the logical "Paste" key on the keyboard.+ paste,++ /// Represents the logical "Find" key on the keyboard.+ find,++ /// Represents the logical "Audio Volume Mute" key on the keyboard.+ audioVolumeMute,++ /// Represents the logical "Audio Volume Up" key on the keyboard.+ audioVolumeUp,++ /// Represents the logical "Audio Volume Down" key on the keyboard.+ audioVolumeDown,++ /// Represents the logical "Numpad Comma" key on the keyboard.+ numpadComma,++ /// Represents the logical "Intl Ro" key on the keyboard.+ intlRo,++ /// Represents the logical "Kana Mode" key on the keyboard.+ kanaMode,++ /// Represents the logical "Intl Yen" key on the keyboard.+ intlYen,++ /// Represents the logical "Convert" key on the keyboard.+ convert,++ /// Represents the logical "Non Convert" key on the keyboard.+ nonConvert,++ /// Represents the logical "Lang 1" key on the keyboard.+ lang1,++ /// Represents the logical "Lang 2" key on the keyboard.+ lang2,++ /// Represents the logical "Lang 3" key on the keyboard.+ lang3,++ /// Represents the logical "Lang 4" key on the keyboard.+ lang4,++ /// Represents the logical "Lang 5" key on the keyboard.+ lang5,++ /// Represents the logical "Abort" key on the keyboard.+ abort,++ /// Represents the logical "Props" key on the keyboard.+ props,++ /// Represents the logical "Numpad Paren Left" key on the keyboard.+ numpadParenLeft,++ /// Represents the logical "Numpad Paren Right" key on the keyboard.+ numpadParenRight,++ /// Represents the logical "Numpad Backspace" key on the keyboard.+ numpadBackspace,++ /// Represents the logical "Numpad Memory Store" key on the keyboard.+ numpadMemoryStore,++ /// Represents the logical "Numpad Memory Recall" key on the keyboard.+ numpadMemoryRecall,++ /// Represents the logical "Numpad Memory Clear" key on the keyboard.+ numpadMemoryClear,++ /// Represents the logical "Numpad Memory Add" key on the keyboard.+ numpadMemoryAdd,++ /// Represents the logical "Numpad Memory Subtract" key on the keyboard.+ numpadMemorySubtract,++ /// Represents the logical "Numpad Sign Change" key on the keyboard.+ numpadSignChange,++ /// Represents the logical "Numpad Clear" key on the keyboard.+ numpadClear,++ /// Represents the logical "Numpad Clear Entry" key on the keyboard.+ numpadClearEntry,++ /// Represents the logical "Control Left" key on the keyboard.+ controlLeft,++ /// Represents the logical "Shift Left" key on the keyboard.+ shiftLeft,++ /// Represents the logical "Alt Left" key on the keyboard.+ altLeft,++ /// Represents the logical "Meta Left" key on the keyboard.+ metaLeft,++ /// Represents the logical "Control Right" key on the keyboard.+ controlRight,++ /// Represents the logical "Shift Right" key on the keyboard.+ shiftRight,++ /// Represents the logical "Alt Right" key on the keyboard.+ altRight,++ /// Represents the logical "Meta Right" key on the keyboard.+ metaRight,++ /// Represents the logical "Info" key on the keyboard.+ info,++ /// Represents the logical "Closed Caption Toggle" key on the keyboard.+ closedCaptionToggle,++ /// Represents the logical "Brightness Up" key on the keyboard.+ brightnessUp,++ /// Represents the logical "Brightness Down" key on the keyboard.+ brightnessDown,++ /// Represents the logical "Brightness Toggle" key on the keyboard.+ brightnessToggle,++ /// Represents the logical "Brightness Minimum" key on the keyboard.+ brightnessMinimum,++ /// Represents the logical "Brightness Maximum" key on the keyboard.+ brightnessMaximum,++ /// Represents the logical "Brightness Auto" key on the keyboard.+ brightnessAuto,++ /// Represents the logical "Media Last" key on the keyboard.+ mediaLast,++ /// Represents the logical "Launch Phone" key on the keyboard.+ launchPhone,++ /// Represents the logical "Program Guide" key on the keyboard.+ programGuide,++ /// Represents the logical "Exit" key on the keyboard.+ exit,++ /// Represents the logical "Channel Up" key on the keyboard.+ channelUp,++ /// Represents the logical "Channel Down" key on the keyboard.+ channelDown,++ /// Represents the logical "Media Play" key on the keyboard.+ mediaPlay,++ /// Represents the logical "Media Pause" key on the keyboard.+ mediaPause,++ /// Represents the logical "Media Record" key on the keyboard.+ mediaRecord,++ /// Represents the logical "Media Fast Forward" key on the keyboard.+ mediaFastForward,++ /// Represents the logical "Media Rewind" key on the keyboard.+ mediaRewind,++ /// Represents the logical "Media Track Next" key on the keyboard.+ mediaTrackNext,++ /// Represents the logical "Media Track Previous" key on the keyboard.+ mediaTrackPrevious,++ /// Represents the logical "Media Stop" key on the keyboard.+ mediaStop,++ /// Represents the logical "Eject" key on the keyboard.+ eject,++ /// Represents the logical "Media Play Pause" key on the keyboard.+ mediaPlayPause,++ /// Represents the logical "Speech Input Toggle" key on the keyboard.+ speechInputToggle,++ /// Represents the logical "Bass Boost" key on the keyboard.+ bassBoost,++ /// Represents the logical "Media Select" key on the keyboard.+ mediaSelect,++ /// Represents the logical "Launch Word Processor" key on the keyboard.+ launchWordProcessor,++ /// Represents the logical "Launch Spreadsheet" key on the keyboard.+ launchSpreadsheet,++ /// Represents the logical "Launch Mail" key on the keyboard.+ launchMail,++ /// Represents the logical "Launch Contacts" key on the keyboard.+ launchContacts,++ /// Represents the logical "Launch Calendar" key on the keyboard.+ launchCalendar,++ /// Represents the logical "Launch App2" key on the keyboard.+ launchApp2,++ /// Represents the logical "Launch App1" key on the keyboard.+ launchApp1,++ /// Represents the logical "Launch Internet Browser" key on the keyboard.+ launchInternetBrowser,++ /// Represents the logical "Log Off" key on the keyboard.+ logOff,++ /// Represents the logical "Lock Screen" key on the keyboard.+ lockScreen,++ /// Represents the logical "Launch Control Panel" key on the keyboard.+ launchControlPanel,++ /// Represents the logical "Select Task" key on the keyboard.+ selectTask,++ /// Represents the logical "Launch Documents" key on the keyboard.+ launchDocuments,++ /// Represents the logical "Spell Check" key on the keyboard.+ spellCheck,++ /// Represents the logical "Launch Keyboard Layout" key on the keyboard.+ launchKeyboardLayout,++ /// Represents the logical "Launch Screen Saver" key on the keyboard.+ launchScreenSaver,++ /// Represents the logical "Launch Assistant" key on the keyboard.+ launchAssistant,++ /// Represents the logical "Launch Audio Browser" key on the keyboard.+ launchAudioBrowser,++ /// Represents the logical "New Key" key on the keyboard.+ newKey,++ /// Represents the logical "Close" key on the keyboard.+ close,++ /// Represents the logical "Save" key on the keyboard.+ save,++ /// Represents the logical "Print" key on the keyboard.+ print,++ /// Represents the logical "Browser Search" key on the keyboard.+ browserSearch,++ /// Represents the logical "Browser Home" key on the keyboard.+ browserHome,++ /// Represents the logical "Browser Back" key on the keyboard.+ browserBack,++ /// Represents the logical "Browser Forward" key on the keyboard.+ browserForward,++ /// Represents the logical "Browser Stop" key on the keyboard.+ browserStop,++ /// Represents the logical "Browser Refresh" key on the keyboard.+ browserRefresh,++ /// Represents the logical "Browser Favorites" key on the keyboard.+ browserFavorites,++ /// Represents the logical "Zoom In" key on the keyboard.+ zoomIn,++ /// Represents the logical "Zoom Out" key on the keyboard.+ zoomOut,++ /// Represents the logical "Zoom Toggle" key on the keyboard.+ zoomToggle,++ /// Represents the logical "Redo" key on the keyboard.+ redo,++ /// Represents the logical "Mail Reply" key on the keyboard.+ mailReply,++ /// Represents the logical "Mail Forward" key on the keyboard.+ mailForward,++ /// Represents the logical "Mail Send" key on the keyboard.+ mailSend,++ /// Represents the logical "Keyboard Layout Select" key on the keyboard.+ keyboardLayoutSelect,++ /// Represents the logical "Show All Windows" key on the keyboard.+ showAllWindows,++ /// Represents the logical "Game Button 1" key on the keyboard.+ gameButton1,++ /// Represents the logical "Game Button 2" key on the keyboard.+ gameButton2,++ /// Represents the logical "Game Button 3" key on the keyboard.+ gameButton3,++ /// Represents the logical "Game Button 4" key on the keyboard.+ gameButton4,++ /// Represents the logical "Game Button 5" key on the keyboard.+ gameButton5,++ /// Represents the logical "Game Button 6" key on the keyboard.+ gameButton6,++ /// Represents the logical "Game Button 7" key on the keyboard.+ gameButton7,++ /// Represents the logical "Game Button 8" key on the keyboard.+ gameButton8,++ /// Represents the logical "Game Button 9" key on the keyboard.+ gameButton9,++ /// Represents the logical "Game Button 10" key on the keyboard.+ gameButton10,++ /// Represents the logical "Game Button 11" key on the keyboard.+ gameButton11,++ /// Represents the logical "Game Button 12" key on the keyboard.+ gameButton12,++ /// Represents the logical "Game Button 13" key on the keyboard.+ gameButton13,++ /// Represents the logical "Game Button 14" key on the keyboard.+ gameButton14,++ /// Represents the logical "Game Button 15" key on the keyboard.+ gameButton15,++ /// Represents the logical "Game Button 16" key on the keyboard.+ gameButton16,++ /// Represents the logical "Game Button A" key on the keyboard.+ gameButtonA,++ /// Represents the logical "Game Button B" key on the keyboard.+ gameButtonB,++ /// Represents the logical "Game Button C" key on the keyboard.+ gameButtonC,++ /// Represents the logical "Game Button Left 1" key on the keyboard.+ gameButtonLeft1,++ /// Represents the logical "Game Button Left 2" key on the keyboard.+ gameButtonLeft2,++ /// Represents the logical "Game Button Mode" key on the keyboard.+ gameButtonMode,++ /// Represents the logical "Game Button Right 1" key on the keyboard.+ gameButtonRight1,++ /// Represents the logical "Game Button Right 2" key on the keyboard.+ gameButtonRight2,++ /// Represents the logical "Game Button Select" key on the keyboard.+ gameButtonSelect,++ /// Represents the logical "Game Button Start" key on the keyboard.+ gameButtonStart,++ /// Represents the logical "Game Button Thumb Left" key on the keyboard.+ gameButtonThumbLeft,++ /// Represents the logical "Game Button Thumb Right" key on the keyboard.+ gameButtonThumbRight,++ /// Represents the logical "Game Button X" key on the keyboard.+ gameButtonX,++ /// Represents the logical "Game Button Y" key on the keyboard.+ gameButtonY,++ /// Represents the logical "Game Button Z" key on the keyboard.+ gameButtonZ,++ /// Represents the logical "Fn" key on the keyboard.+ fn,++ /// Represents the logical "Shift" key on the keyboard.+ ///+ /// This key represents the union of the keys {shiftLeft, shiftRight} when+ /// comparing keys. This key will never be generated directly, its main use is+ /// in defining key maps.+ shift,++ /// Represents the logical "Meta" key on the keyboard.+ ///+ /// This key represents the union of the keys {metaLeft, metaRight} when+ /// comparing keys. This key will never be generated directly, its main use is+ /// in defining key maps.+ meta,++ /// Represents the logical "Alt" key on the keyboard.+ ///+ /// This key represents the union of the keys {altLeft, altRight} when+ /// comparing keys. This key will never be generated directly, its main use is+ /// in defining key maps.+ alt,++ /// Represents the logical "Control" key on the keyboard.+ ///+ /// This key represents the union of the keys {controlLeft, controlRight} when+ /// comparing keys. This key will never be generated directly, its main use is+ /// in defining key maps.+ control,++ // Missing flutter keys.++ backtab,+ returnKey,+}diff --git a/mobile/third_party/xterm/lib/src/core/input/keytab/keytab.dart b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab.dartnew file mode 100644index 000000000..0999366f1--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab.dart@@ -0,0 +1,113 @@+import 'package:xterm/src/core/input/keys.dart';+import 'package:xterm/src/core/input/keytab/keytab_default.dart';+import 'package:xterm/src/core/input/keytab/keytab_parse.dart';+import 'package:xterm/src/core/input/keytab/keytab_record.dart';+import 'package:xterm/src/core/input/keytab/keytab_token.dart';++class Keytab {+ Keytab({+ required this.name,+ required this.records,+ });++ factory Keytab.parse(String source) {+ final tokens = tokenize(source).toList();+ final parser = KeytabParser()..addTokens(tokens);+ return parser.result;+ }++ static final defaultKeytab = Keytab.parse(kDefaultKeytab);++ final String? name;++ final List<KeytabRecord> records;++ KeytabRecord? find(+ TerminalKey key, {+ bool ctrl = false,+ bool alt = false,+ bool shift = false,+ bool newLineMode = false,+ bool appCursorKeys = false,+ bool appKeyPad = false,+ bool keyPad = false,+ bool appScreen = false,+ bool macos = false,+ // bool meta,+ }) {+ for (var record in records) {+ if (record.key != key) {+ continue;+ }++ if (record.anyModifier == true) {+ if (ctrl == false && alt == false && shift == false) {+ continue;+ }+ } else if (record.anyModifier == false) {+ if (ctrl != false || alt != false || shift != false) {+ continue;+ }+ } else {+ if (record.ctrl != null && record.ctrl != ctrl) {+ continue;+ }++ if (record.shift != null && record.shift != shift) {+ continue;+ }++ if (record.alt != null && record.alt != alt) {+ continue;+ }+ }++ if (record.newLine != null && record.newLine != newLineMode) {+ continue;+ }++ if (record.appCursorKeys != null &&+ record.appCursorKeys != appCursorKeys) {+ continue;+ }++ if (record.appKeyPad != null && record.appKeyPad != appKeyPad) {+ continue;+ }++ if (record.keyPad != null && record.keyPad != keyPad) {+ continue;+ }++ if (record.appScreen != null && record.appScreen != appScreen) {+ continue;+ }++ if (record.macos != null && record.macos != macos) {+ continue;+ }++ // TODO: support VT52+ if (record.ansi == false) {+ continue;+ }++ return record;+ }++ return null;+ }++ @override+ String toString() {+ final buffer = StringBuffer();++ buffer.writeln('keyboard "$name"');++ for (var record in records) {+ buffer.writeln(record);+ }++ return buffer.toString();+ }+}diff --git a/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_default.dart b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_default.dartnew file mode 100644index 000000000..000217586--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_default.dart@@ -0,0 +1,215 @@+import 'package:xterm/src/core/input/keytab/keytab_parse.dart';+import 'package:xterm/src/core/input/keytab/keytab_token.dart';++const kDefaultKeytab = r'''+# [README.default.Keytab] Default Keyboard Table+#+# To customize your keyboard, copy this file to something ending with+# .keytab and change it to meet you needs.+#+# Please read the README-KeyTab and the doc/user/README.keyboard files+# in this case.+#+# --------------------------------------------------------------++keyboard "Default (XFree 4)"++# --------------------------------------------------------------+#+# Note that this particular table is a "risc" version made to+# ease customization without bothering with obsolete details.+# See VT100.keytab for the more hairy stuff.+#+# --------------------------------------------------------------++# common keys++key Escape : "\E"++key Tab -Shift : "\t"+key Tab +Shift+Ansi : "\E[Z"+key Tab +Shift-Ansi : "\t"+key Backtab +Ansi : "\E[Z"+key Backtab -Ansi : "\t"++key Return-Shift-NewLine : "\r"+key Return-Shift+NewLine : "\r\n"++key Return+Shift : "\EOM"++key Backspace +Alt : "\x17"++# Backspace and Delete codes are preserving CTRL-H.+#+# Backspace without CTRL sends '^?'; this matches XTerm behaviour, so that+# pressing Alt+Backspace will send \E + Del, which is the expected behaviour+# in some apps (e.g. emacs), and it was the behaviour before the commit+# that add the Backspace +Control rule+key Backspace -Control : "\x7f"++# Match xterm behaviour: Backspace sends '^H' when Control is pressed+# BS, hex \x08, \b+key Backspace +Control : "\b"++# Arrow keys in VT52 mode+# Shift up/down retain their normal-screen scrolling bindings below.++key Up -Shift-Ansi : "\EA"+key Down -Shift-Ansi : "\EB"+key Right-Shift-Ansi : "\EC"+key Left -Shift-Ansi : "\ED"++# Arrow keys in ANSI mode with Application - and Normal Cursor Mode)++key Up -Shift-AnyMod+Ansi+AppCuKeys : "\EOA"+key Down -Shift-AnyMod+Ansi+AppCuKeys : "\EOB"+key Right -Shift-AnyMod+Ansi+AppCuKeys : "\EOC"+key Left -Shift-AnyMod+Ansi+AppCuKeys : "\EOD"++key Up -Shift-AnyMod+Ansi-AppCuKeys : "\E[A"+key Down -Shift-AnyMod+Ansi-AppCuKeys : "\E[B"+key Right -Shift-AnyMod+Ansi-AppCuKeys : "\E[C"+key Left -Shift-AnyMod+Ansi-AppCuKeys : "\E[D"++key Up -Shift+AnyMod+Ansi : "\E[1;5A"+key Down -Shift+AnyMod+Ansi : "\E[1;5B"++# Right / Left with Control+key Right -Shift-Alt+Control+Ansi : "\E[1;5C"+key Left -Shift-Alt+Control+Ansi : "\E[1;5D"++# Right / Left with Alt not on a Mac+key Right -Shift+Alt-Control+Ansi-Mac : "\E[1;5C"+key Left -Shift+Alt-Control+Ansi-Mac : "\E[1;5D"++# Right / Left with Alt on a Mac+key Right -Shift+Alt-Control+Ansi+Mac : "\Ef"+key Left -Shift+Alt-Control+Ansi+Mac : "\Eb"++key Up +Shift+AppScreen : "\E[1;*A"+key Down +Shift+AppScreen : "\E[1;*B"++# Horizontal Shift arrows belong to the TUI in either screen buffer.+# Codex opens queued questions with Shift+Left in the normal screen.+key Left +Shift+Ansi : "\E[1;*D"+key Right +Shift+Ansi : "\E[1;*C"++# Keypad keys with NumLock ON+# (see https://web.archive.org/web/20070807181942/http://www.nw.com/nw/WWW/products/wizcon/vt100.html+# https://vt100.net/docs/vt100-ug/chapter3.html)+#+# Not enabled for now because it breaks the keypad in Vim.+#+#key 0 +KeyPad+AppKeyPad : "\EOp"+#key 1 +KeyPad+AppKeyPad : "\EOq"+#key 2 +KeyPad+AppKeyPad : "\EOr"+#key 3 +KeyPad+AppKeyPad : "\EOs"+#key 4 +KeyPad+AppKeyPad : "\EOt"+#key 5 +KeyPad+AppKeyPad : "\EOu"+#key 6 +KeyPad+AppKeyPad : "\EOv"+#key 7 +KeyPad+AppKeyPad : "\EOw"+#key 8 +KeyPad+AppKeyPad : "\EOx"+#key 9 +KeyPad+AppKeyPad : "\EOy"+#key + +KeyPad+AppKeyPad : "\EOl"+#key - +KeyPad+AppKeyPad : "\EOm"+#key . +KeyPad+AppKeyPad : "\EOn"+#key * +KeyPad+AppKeyPad : "\EOM"+#key Enter +KeyPad+AppKeyPad : "\r"++# Keypad keys with NumLock Off+key Up -Shift+Ansi+AppCuKeys+KeyPad : "\EOA"+key Down -Shift+Ansi+AppCuKeys+KeyPad : "\EOB"+key Right -Shift+Ansi+AppCuKeys+KeyPad : "\EOC"+key Left -Shift+Ansi+AppCuKeys+KeyPad : "\EOD"++key Up -Shift+Ansi-AppCuKeys+KeyPad : "\E[A"+key Down -Shift+Ansi-AppCuKeys+KeyPad : "\E[B"+key Right -Shift+Ansi-AppCuKeys+KeyPad : "\E[C"+key Left -Shift+Ansi-AppCuKeys+KeyPad : "\E[D"++key Home +AppCuKeys+KeyPad : "\EOH"+key End +AppCuKeys+KeyPad : "\EOF"+key Home -AppCuKeys+KeyPad : "\E[H"+key End -AppCuKeys+KeyPad : "\E[F"++key Insert +KeyPad : "\E[2~"+key Delete +KeyPad : "\E[3~"+key PgUp -Shift+KeyPad : "\E[5~"+key PgDown -Shift+KeyPad : "\E[6~"++# the key labelled 5 on the Keypad, is Qt::Key_Clear (a very intuitive+# and discoverable name...)+key Clear +KeyPad : "\E[E"++# other grey PC keys++key Enter+NewLine : "\r\n"+key Enter-NewLine : "\r"++key NumEnter+NewLine : "\r\n"+key NumEnter-NewLine : "\r"++key Home -AnyMod-AppCuKeys : "\E[H"+key End -AnyMod-AppCuKeys : "\E[F"+key Home -AnyMod+AppCuKeys : "\EOH"+key End -AnyMod+AppCuKeys : "\EOF"+key Home +AnyMod : "\E[1;*H"+key End +AnyMod : "\E[1;*F"++key Insert -AnyMod : "\E[2~"+key Delete -AnyMod : "\E[3~"+key Insert +AnyMod : "\E[2;*~"+key Delete +AnyMod : "\E[3;*~"++key PgUp -Shift-AnyMod : "\E[5~"+key PgDown -Shift-AnyMod : "\E[6~"+key PgUp -Shift+AnyMod : "\E[5;*~"+key PgDown -Shift+AnyMod : "\E[6;*~"++# Function keys+key F1 -AnyMod : "\EOP"+key F2 -AnyMod : "\EOQ"+key F3 -AnyMod : "\EOR"+key F4 -AnyMod : "\EOS"+key F5 -AnyMod : "\E[15~"+key F6 -AnyMod : "\E[17~"+key F7 -AnyMod : "\E[18~"+key F8 -AnyMod : "\E[19~"+key F9 -AnyMod : "\E[20~"+key F10 -AnyMod : "\E[21~"+key F11 -AnyMod : "\E[23~"+key F12 -AnyMod : "\E[24~"++key F1 +AnyMod : "\EO*P"+key F2 +AnyMod : "\EO*Q"+key F3 +AnyMod : "\EO*R"+key F4 +AnyMod : "\EO*S"+key F5 +AnyMod : "\E[15;*~"+key F6 +AnyMod : "\E[17;*~"+key F7 +AnyMod : "\E[18;*~"+key F8 +AnyMod : "\E[19;*~"+key F9 +AnyMod : "\E[20;*~"+key F10 +AnyMod : "\E[21;*~"+key F11 +AnyMod : "\E[23;*~"+key F12 +AnyMod : "\E[24;*~"++# Work around dead keys++key Space +Control : "\x00"++# Some keys are used by konsole to cause operations.+# The scroll* operations refer to the history buffer.++key Up +Shift-AppScreen : scrollLineUp+key PgUp +Shift-AppScreen : scrollPageUp+key Home +Shift-AppScreen : scrollUpToTop+key Down +Shift-AppScreen : scrollLineDown+key PgDown +Shift-AppScreen : scrollPageDown+key End +Shift-AppScreen : scrollDownToBottom+''';++void main() {+ final tokens = tokenize(kDefaultKeytab).toList();+ final parser = KeytabParser()..addTokens(tokens);+ print(parser.result);+}diff --git a/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_escape.dart b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_escape.dartnew file mode 100644index 000000000..5375bc34b--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_escape.dart@@ -0,0 +1,21 @@+final _esc = String.fromCharCode(0x1b);++String keytabUnescape(String str) {+ str = str+ .replaceAll(r'\E', _esc)+ .replaceAll(r'\\', '\\')+ .replaceAll(r'\"', '"')+ .replaceAll(r'\t', '\t')+ .replaceAll(r'\r', '\r')+ .replaceAll(r'\n', '\n')+ .replaceAll(r'\b', '\b');++ final hexPattern = RegExp(r'\\x([0-9a-fA-F][0-9a-fA-F])');+ str = str.replaceAllMapped(hexPattern, (match) {+ final hexString = match.group(1)!;+ final hexValue = int.parse(hexString, radix: 16);+ return String.fromCharCode(hexValue);+ });++ return str;+}diff --git a/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_parse.dart b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_parse.dartnew file mode 100644index 000000000..96f803589--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_parse.dart@@ -0,0 +1,186 @@+import 'package:xterm/src/core/input/keytab/keytab.dart';+import 'package:xterm/src/core/input/keytab/keytab_record.dart';+import 'package:xterm/src/core/input/keytab/keytab_token.dart';+import 'package:xterm/src/core/input/keytab/qt_keyname.dart';++class ParseError {}++class TokensReader {+ TokensReader(this.tokens);++ final List<KeytabToken> tokens;++ var _pos = 0;++ bool get done => _pos > tokens.length - 1;++ KeytabToken? take() {+ final result = peek();+ _pos += 1;+ return result;+ }++ KeytabToken? peek() {+ if (done) return null;+ return tokens[_pos];+ }+}++class KeytabParser {+ String? _name;+ final _records = <KeytabRecord>[];++ void addTokens(List<KeytabToken> tokens) {+ final reader = TokensReader(tokens);++ while (!reader.done) {+ if (reader.peek()!.type == KeytabTokenType.keyboard) {+ _parseName(reader);+ continue;+ }++ if (reader.peek()!.type == KeytabTokenType.keyDefine) {+ _parseKeyDefine(reader);+ continue;+ }++ throw ParseError();+ }+ }++ Keytab get result {+ return Keytab(name: _name, records: _records);+ }++ void _parseName(TokensReader reader) {+ if (reader.take()!.type != KeytabTokenType.keyboard) {+ throw ParseError();+ }++ final name = reader.take()!;+ if (name.type != KeytabTokenType.input) {+ throw ParseError();+ }++ _name = name.value;+ }++ void _parseKeyDefine(TokensReader reader) {+ if (reader.take()!.type != KeytabTokenType.keyDefine) {+ throw ParseError();+ }++ final keyName = reader.take()!;++ if (keyName.type != KeytabTokenType.keyName) {+ throw ParseError();+ }++ final key = qtKeynameMap[keyName.value];+ if (key == null) {+ throw ParseError();+ }++ bool? alt;+ bool? ctrl;+ bool? shift;+ bool? anyModifier;+ bool? ansi;+ bool? appScreen;+ bool? keyPad;+ bool? appCursorKeys;+ bool? appKeyPad;+ bool? newLine;+ bool? mac;++ while (reader.peek()!.type == KeytabTokenType.modeStatus) {+ bool modeStatus;+ switch (reader.take()!.value) {+ case '+':+ modeStatus = true;+ break;+ case '-':+ modeStatus = false;+ break;+ default:+ throw ParseError();+ }++ final mode = reader.take();+ if (mode!.type != KeytabTokenType.mode) {+ throw ParseError();+ }++ switch (mode.value) {+ case 'Alt':+ alt = modeStatus;+ break;+ case 'Control':+ ctrl = modeStatus;+ break;+ case 'Shift':+ shift = modeStatus;+ break;+ case 'AnyMod':+ anyModifier = modeStatus;+ break;+ case 'Ansi':+ ansi = modeStatus;+ break;+ case 'AppScreen':+ appScreen = modeStatus;+ break;+ case 'KeyPad':+ keyPad = modeStatus;+ break;+ case 'AppCuKeys':+ appCursorKeys = modeStatus;+ break;+ case 'AppKeyPad':+ appKeyPad = modeStatus;+ break;+ case 'NewLine':+ newLine = modeStatus;+ break;+ case 'Mac':+ mac = modeStatus;+ break;+ default:+ throw ParseError();+ }+ }++ if (reader.take()!.type != KeytabTokenType.colon) {+ throw ParseError();+ }++ final actionToken = reader.take()!;+ KeytabAction action;+ if (actionToken.type == KeytabTokenType.input) {+ action = KeytabAction(KeytabActionType.input, actionToken.value);+ } else if (actionToken.type == KeytabTokenType.shortcut) {+ action = KeytabAction(KeytabActionType.shortcut, actionToken.value);+ } else {+ throw ParseError();+ }++ final record = KeytabRecord(+ qtKeyName: keyName.value,+ key: key,+ action: action,+ alt: alt,+ ctrl: ctrl,+ shift: shift,+ anyModifier: anyModifier,+ ansi: ansi,+ appScreen: appScreen,+ keyPad: keyPad,+ appCursorKeys: appCursorKeys,+ appKeyPad: appKeyPad,+ newLine: newLine,+ macos: mac,+ );++ _records.add(record);+ }+}diff --git a/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_record.dart b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_record.dartnew file mode 100644index 000000000..7ba3caeb5--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_record.dart@@ -0,0 +1,134 @@+import 'package:xterm/src/core/input/keys.dart';+import 'package:xterm/src/core/input/keytab/keytab_escape.dart';++enum KeytabActionType {+ input,+ shortcut,+}++class KeytabAction {+ KeytabAction(this.type, this.value);++ final KeytabActionType type;++ final String value;++ String unescapedValue() {+ if (type == KeytabActionType.input) {+ return keytabUnescape(value);+ } else {+ return value;+ }+ }++ @override+ String toString() {+ switch (type) {+ case KeytabActionType.input:+ return '"$value"';+ case KeytabActionType.shortcut:+ return value;+ }+ }+}++class KeytabRecord {+ KeytabRecord({+ required this.qtKeyName,+ required this.key,+ required this.action,+ required this.alt,+ required this.ctrl,+ required this.shift,+ required this.anyModifier,+ required this.ansi,+ required this.appScreen,+ required this.keyPad,+ required this.appCursorKeys,+ required this.appKeyPad,+ required this.newLine,+ required this.macos,+ });++ String qtKeyName;+ TerminalKey key;+ KeytabAction action;++ bool? alt;+ bool? ctrl;+ bool? shift;+ bool? anyModifier;+ bool? ansi;+ bool? appScreen;+ bool? keyPad;+ bool? appCursorKeys;+ bool? appKeyPad;+ bool? newLine;+ bool? macos;++ @override+ String toString() {+ final buffer = StringBuffer();+ buffer.write('$qtKeyName ');++ if (alt != null) {+ buffer.write(_toMode(alt!, 'Alt'));+ }++ if (ctrl != null) {+ buffer.write(_toMode(ctrl!, 'Control'));+ }++ if (shift != null) {+ buffer.write(_toMode(shift!, 'Shift'));+ }++ if (anyModifier != null) {+ buffer.write(_toMode(anyModifier!, 'AnyMod'));+ }++ if (ansi != null) {+ buffer.write(_toMode(ansi!, 'Ansi'));+ }++ if (appScreen != null) {+ buffer.write(_toMode(appScreen!, 'AppScreen'));+ }++ if (keyPad != null) {+ buffer.write(_toMode(keyPad!, 'KeyPad'));+ }++ if (appCursorKeys != null) {+ buffer.write(_toMode(appCursorKeys!, 'AppCuKeys'));+ }++ if (appKeyPad != null) {+ buffer.write(_toMode(appKeyPad!, 'AppKeyPad'));+ }++ if (newLine != null) {+ buffer.write(_toMode(newLine!, 'NewLine'));+ }++ if (macos != null) {+ buffer.write(_toMode(macos!, 'Mac'));+ }++ buffer.write(' : $action');++ return buffer.toString();+ }++ static String _toMode(bool status, String mode) {+ if (status == true) {+ return '+$mode';+ }++ if (status == false) {+ return '-$mode';+ }++ return '';+ }+}diff --git a/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_token.dart b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_token.dartnew file mode 100644index 000000000..a8ab87065--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/input/keytab/keytab_token.dart@@ -0,0 +1,179 @@+import 'dart:math' show min;++enum KeytabTokenType {+ keyDefine,+ keyboard,+ keyName,+ mode,+ modeStatus,+ colon,+ input,+ shortcut,+}++class KeytabToken {+ KeytabToken(this.type, this.value);++ final KeytabTokenType type;+ final String value;++ @override+ String toString() {+ return '$type<$value>';+ }+}++class LineReader {+ LineReader(this.line);++ final String line;++ var _pos = 0;++ bool get done => _pos > line.length - 1;++ String? take([int count = 1]) {+ final result = peek(count);+ _pos += count;+ return result;+ }++ String? peek([int count = 1]) {+ if (done) return null;+ final end = min(_pos + count, line.length);+ final result = line.substring(_pos, end);+ return result;+ }++ void skipWhitespace() {+ while (peek() == ' ' || peek() == '\t') {+ _pos += 1;+ }+ }++ String readString() {+ final buffer = StringBuffer();+ final pattern = RegExp(r'\w|_');++ while (!done && line[_pos].contains(pattern)) {+ buffer.write(line[_pos]);+ _pos++;+ }++ return buffer.toString();+ }++ String readUntil(Pattern pattern, {bool inclusive = false}) {+ final buffer = StringBuffer();++ while (!done && !line[_pos].contains(pattern)) {+ buffer.write(line[_pos]);+ _pos++;+ }++ if (!done && inclusive) {+ buffer.write(line[_pos]);+ _pos++;+ }++ return buffer.toString();+ }+}++class TokenizeError {}++Iterable<KeytabToken> tokenize(String source) sync* {+ final lines = source.split('\n');++ for (var i = 0; i < lines.length; i++) {+ var line = lines[i].trim();+ line = line.replaceFirst(RegExp('#.*'), '');++ if (line == '') {+ continue;+ }++ if (_isKeyboardNameDefine(line)) {+ yield* _parseKeyboardNameDefine(line);+ }++ if (_isKeyDefine(line)) {+ yield* _parseKeyDefine(line);+ }+ }+}++bool _isKeyboardNameDefine(String line) {+ return line.startsWith('keyboard ');+}++bool _isKeyDefine(String line) {+ return line.startsWith('key ');+}++Iterable<KeytabToken> _parseKeyboardNameDefine(String line) sync* {+ final reader = LineReader(line.trim());++ if (reader.readString() == 'keyboard') {+ yield KeytabToken(KeytabTokenType.keyboard, 'keyboard');+ } else {+ throw TokenizeError();+ }++ reader.skipWhitespace();++ yield _readInput(reader);+}++Iterable<KeytabToken> _parseKeyDefine(String line) sync* {+ final reader = LineReader(line.trim());++ if (reader.readString() == 'key') {+ yield KeytabToken(KeytabTokenType.keyDefine, 'key');+ } else {+ throw TokenizeError();+ }++ reader.skipWhitespace();++ final keyName = reader.readString();+ yield KeytabToken(KeytabTokenType.keyName, keyName);++ reader.skipWhitespace();++ while (reader.peek() == '+' || reader.peek() == '-') {+ final modeStatus = reader.take()!;+ yield KeytabToken(KeytabTokenType.modeStatus, modeStatus);+ final mode = reader.readString();+ yield KeytabToken(KeytabTokenType.mode, mode);+ reader.skipWhitespace();+ }++ if (reader.take() == ':') {+ yield KeytabToken(KeytabTokenType.colon, ':');+ } else {+ throw TokenizeError();+ }++ reader.skipWhitespace();++ if (reader.peek() == '"') {+ yield _readInput(reader);+ } else {+ final action = reader.readString();+ yield KeytabToken(KeytabTokenType.shortcut, action);+ }+}++KeytabToken _readInput(LineReader reader) {+ reader.skipWhitespace();++ if (reader.take() != '"') {+ throw TokenizeError();+ }++ final value = reader.readUntil('"');+ reader.take();++ return KeytabToken(KeytabTokenType.input, value);+}diff --git a/mobile/third_party/xterm/lib/src/core/input/keytab/qt_keyname.dart b/mobile/third_party/xterm/lib/src/core/input/keytab/qt_keyname.dartnew file mode 100644index 000000000..4eca3e634--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/input/keytab/qt_keyname.dart@@ -0,0 +1,477 @@+import 'package:xterm/src/core/input/keys.dart';++/// See: https://doc.qt.io/qt-5/qt.html#Key-enum+const qtKeynameMap = <String, TerminalKey>{+ 'Escape': TerminalKey.escape,+ 'Tab': TerminalKey.tab,+ 'Backtab': TerminalKey.backtab,+ 'Backspace': TerminalKey.backspace,+ 'Return': TerminalKey.returnKey,+ 'Enter': TerminalKey.enter,+ 'NumEnter': TerminalKey.numpadEnter,+ 'Insert': TerminalKey.insert,+ 'Delete': TerminalKey.delete,+ 'Pause': TerminalKey.pause,+ 'Print': TerminalKey.print,+// 'SysReq': TerminalKey.sysReq,+ 'Clear': TerminalKey.numpadClear,+ 'Home': TerminalKey.home,+ 'End': TerminalKey.end,+ 'Left': TerminalKey.arrowLeft,+ 'Up': TerminalKey.arrowUp,+ 'Right': TerminalKey.arrowRight,+ 'Down': TerminalKey.arrowDown,+ 'PageUp': TerminalKey.pageUp,+ 'PageDown': TerminalKey.pageDown,+ 'PgUp': TerminalKey.pageUp,+ 'PgDown': TerminalKey.pageDown,+ 'Shift': TerminalKey.shift,+ 'Control': TerminalKey.control,+ 'Meta': TerminalKey.meta,+ 'Alt': TerminalKey.alt,+// 'AltGr': TerminalKey.altGr,+ 'CapsLock': TerminalKey.capsLock,+ 'NumLock': TerminalKey.numLock,+ 'ScrollLock': TerminalKey.scrollLock,+ 'F1': TerminalKey.f1,+ 'F2': TerminalKey.f2,+ 'F3': TerminalKey.f3,+ 'F4': TerminalKey.f4,+ 'F5': TerminalKey.f5,+ 'F6': TerminalKey.f6,+ 'F7': TerminalKey.f7,+ 'F8': TerminalKey.f8,+ 'F9': TerminalKey.f9,+ 'F10': TerminalKey.f10,+ 'F11': TerminalKey.f11,+ 'F12': TerminalKey.f12,+ 'F13': TerminalKey.f13,+ 'F14': TerminalKey.f14,+ 'F15': TerminalKey.f15,+ 'F16': TerminalKey.f16,+ 'F17': TerminalKey.f17,+ 'F18': TerminalKey.f18,+ 'F19': TerminalKey.f19,+ 'F20': TerminalKey.f20,+ 'F21': TerminalKey.f21,+ 'F22': TerminalKey.f22,+ 'F23': TerminalKey.f23,+ 'F24': TerminalKey.f24,+// 'F25': TerminalKey.f25,+// 'F26': TerminalKey.f26,+// 'F27': TerminalKey.f27,+// 'F28': TerminalKey.f28,+// 'F29': TerminalKey.f29,+// 'F30': TerminalKey.f30,+// 'F31': TerminalKey.f31,+// 'F32': TerminalKey.f32,+// 'F33': TerminalKey.f33,+// 'F34': TerminalKey.f34,+// 'F35': TerminalKey.f35,+// 'Super_L': TerminalKey.super_L,+// 'Super_R': TerminalKey.super_R,+// 'Menu': TerminalKey.menu,+// 'Hyper_L': TerminalKey.hyper_L,+// 'Hyper_R': TerminalKey.hyper_R,+ 'Help': TerminalKey.help,+// 'Direction_L': TerminalKey.direction_L,+// 'Direction_R': TerminalKey.direction_R,+ 'Space': TerminalKey.space,+ // 'Any': TerminalKey.any,+ // 'Exclam': TerminalKey.exclam,+ // 'QuoteDbl': TerminalKey.quoteDbl,+ // 'NumberSign': TerminalKey.numberSign,+ // 'Dollar': TerminalKey.dollar,+ // 'Percent': TerminalKey.percent,+ // 'Ampersand': TerminalKey.ampersand,+ // 'Apostrophe': TerminalKey.apostrophe,+ 'ParenLeft': TerminalKey.numpadParenLeft,+ 'ParenRight': TerminalKey.numpadParenRight,+ // 'Asterisk': TerminalKey.asterisk,+ // 'Plus': TerminalKey.plus,+ 'Comma': TerminalKey.comma,+ 'Minus': TerminalKey.minus,+ 'Period': TerminalKey.period,+ 'Slash': TerminalKey.slash,+ '0': TerminalKey.digit0,+ '1': TerminalKey.digit1,+ '2': TerminalKey.digit2,+ '3': TerminalKey.digit3,+ '4': TerminalKey.digit4,+ '5': TerminalKey.digit5,+ '6': TerminalKey.digit6,+ '7': TerminalKey.digit7,+ '8': TerminalKey.digit8,+ '9': TerminalKey.digit9,+// 'Colon': TerminalKey.colon,+ 'Semicolon': TerminalKey.semicolon,+// 'Less': TerminalKey.less,+// 'Equal': TerminalKey.equal,+// 'Greater': TerminalKey.greater,+// 'Question': TerminalKey.question,+// 'At': TerminalKey.at,+ 'A': TerminalKey.keyA,+ 'B': TerminalKey.keyB,+ 'C': TerminalKey.keyC,+ 'D': TerminalKey.keyD,+ 'E': TerminalKey.keyE,+ 'F': TerminalKey.keyF,+ 'G': TerminalKey.keyG,+ 'H': TerminalKey.keyH,+ 'I': TerminalKey.keyI,+ 'J': TerminalKey.keyJ,+ 'K': TerminalKey.keyK,+ 'L': TerminalKey.keyL,+ 'M': TerminalKey.keyM,+ 'N': TerminalKey.keyN,+ 'O': TerminalKey.keyO,+ 'P': TerminalKey.keyP,+ 'Q': TerminalKey.keyQ,+ 'R': TerminalKey.keyR,+ 'S': TerminalKey.keyS,+ 'T': TerminalKey.keyT,+ 'U': TerminalKey.keyU,+ 'V': TerminalKey.keyV,+ 'W': TerminalKey.keyW,+ 'X': TerminalKey.keyX,+ 'Y': TerminalKey.keyY,+ 'Z': TerminalKey.keyZ,+ 'BracketLeft': TerminalKey.bracketLeft,+ 'Backslash': TerminalKey.backslash,+ 'BracketRight': TerminalKey.bracketRight,+// 'AsciiCircum': TerminalKey.asciiCircum,+ // 'Underscore': TerminalKey.underscore,+ // 'QuoteLeft': TerminalKey.quoteLeft,+// 'BraceLeft': TerminalKey.braceLeft,+ // 'Bar': TerminalKey.bar,+// 'BraceRight': TerminalKey.braceRight,+ // 'AsciiTilde': TerminalKey.asciiTilde,+// 'nobreakspace': TerminalKey.nobreakspace,+// 'exclamdown': TerminalKey.exclamdown,+// 'cent': TerminalKey.cent,+// 'sterling': TerminalKey.sterling,+// 'currency': TerminalKey.currency,+// 'yen': TerminalKey.yen,+// 'brokenbar': TerminalKey.brokenbar,+// 'section': TerminalKey.section,+// 'diaeresis': TerminalKey.diaeresis,+// 'copyright': TerminalKey.copyright,+// 'ordfeminine': TerminalKey.ordfeminine,+// 'guillemotleft': TerminalKey.guillemotleft,+// 'notsign': TerminalKey.notsign,+// 'hyphen': TerminalKey.hyphen,+// 'registered': TerminalKey.registered,+// 'macron': TerminalKey.macron,+// 'degree': TerminalKey.degree,+// 'plusminus': TerminalKey.plusminus,+// 'twosuperior': TerminalKey.twosuperior,+// 'threesuperior': TerminalKey.threesuperior,+// 'acute': TerminalKey.acute,+// // 'mu': TerminalKey.mu,+// 'paragraph': TerminalKey.paragraph,+// 'periodcentered': TerminalKey.periodcentered,+// 'cedilla': TerminalKey.cedilla,+// 'onesuperior': TerminalKey.onesuperior,+// 'masculine': TerminalKey.masculine,+// 'guillemotright': TerminalKey.guillemotright,+// 'onequarter': TerminalKey.onequarter,+// 'onehalf': TerminalKey.onehalf,+// 'threequarters': TerminalKey.threequarters,+// 'questiondown': TerminalKey.questiondown,+// 'Agrave': TerminalKey.agrave,+// 'Aacute': TerminalKey.aacute,+// 'Acircumflex': TerminalKey.acircumflex,+// 'Atilde': TerminalKey.atilde,+// 'Adiaeresis': TerminalKey.adiaeresis,+// 'Aring': TerminalKey.aring,+// 'AE': TerminalKey.aE,+// 'Ccedilla': TerminalKey.ccedilla,+// 'Egrave': TerminalKey.egrave,+// 'Eacute': TerminalKey.eacute,+// 'Ecircumflex': TerminalKey.ecircumflex,+// 'Ediaeresis': TerminalKey.ediaeresis,+// 'Igrave': TerminalKey.igrave,+// 'Iacute': TerminalKey.iacute,+// 'Icircumflex': TerminalKey.icircumflex,+// 'Idiaeresis': TerminalKey.idiaeresis,+// 'ETH': TerminalKey.eTH,+// 'Ntilde': TerminalKey.ntilde,+// 'Ograve': TerminalKey.ograve,+// 'Oacute': TerminalKey.oacute,+// 'Ocircumflex': TerminalKey.ocircumflex,+// 'Otilde': TerminalKey.otilde,+// 'Odiaeresis': TerminalKey.odiaeresis,+// 'multiply': TerminalKey.multiply,+// 'Ooblique': TerminalKey.ooblique,+// 'Ugrave': TerminalKey.ugrave,+// 'Uacute': TerminalKey.uacute,+// 'Ucircumflex': TerminalKey.ucircumflex,+// 'Udiaeresis': TerminalKey.udiaeresis,+// 'Yacute': TerminalKey.yacute,+// 'THORN': TerminalKey.tHORN,+// 'ssharp': TerminalKey.ssharp,+// 'division': TerminalKey.division,+// 'ydiaeresis': TerminalKey.ydiaeresis,+// 'Multi_key': TerminalKey.multi_key,+// 'Codeinput': TerminalKey.codeinput,+// 'SingleCandidate': TerminalKey.singleCandidate,+// 'MultipleCandidate': TerminalKey.multipleCandidate,+// 'PreviousCandidate': TerminalKey.previousCandidate,+// 'Mode_switch': TerminalKey.mode_switch,+// 'Kanji': TerminalKey.kanji,+// 'Muhenkan': TerminalKey.muhenkan,+// 'Henkan': TerminalKey.henkan,+// 'Romaji': TerminalKey.romaji,+// 'Hiragana': TerminalKey.hiragana,+// 'Katakana': TerminalKey.katakana,+// 'Hiragana_Katakana': TerminalKey.hiragana_Katakana,+// 'Zenkaku': TerminalKey.zenkaku,+// 'Hankaku': TerminalKey.hankaku,+// 'Zenkaku_Hankaku': TerminalKey.zenkaku_Hankaku,+// 'Touroku': TerminalKey.touroku,+// 'Massyo': TerminalKey.massyo,+// 'Kana_Lock': TerminalKey.kana_Lock,+// 'Kana_Shift': TerminalKey.kana_Shift,+// 'Eisu_Shift': TerminalKey.eisu_Shift,+// 'Eisu_toggle': TerminalKey.eisu_toggle,+// 'Hangul': TerminalKey.hangul,+// 'Hangul_Start': TerminalKey.hangul_Start,+// 'Hangul_End': TerminalKey.hangul_End,+// 'Hangul_Hanja': TerminalKey.hangul_Hanja,+// 'Hangul_Jamo': TerminalKey.hangul_Jamo,+// 'Hangul_Romaja': TerminalKey.hangul_Romaja,+// 'Hangul_Jeonja': TerminalKey.hangul_Jeonja,+// 'Hangul_Banja': TerminalKey.hangul_Banja,+// 'Hangul_PreHanja': TerminalKey.hangul_PreHanja,+// 'Hangul_PostHanja': TerminalKey.hangul_PostHanja,+// 'Hangul_Special': TerminalKey.hangul_Special,+// 'Dead_Grave': TerminalKey.dead_Grave,+// 'Dead_Acute': TerminalKey.dead_Acute,+// 'Dead_Circumflex': TerminalKey.dead_Circumflex,+// 'Dead_Tilde': TerminalKey.dead_Tilde,+// 'Dead_Macron': TerminalKey.dead_Macron,+// 'Dead_Breve': TerminalKey.dead_Breve,+// 'Dead_Abovedot': TerminalKey.dead_Abovedot,+// 'Dead_Diaeresis': TerminalKey.dead_Diaeresis,+// 'Dead_Abovering': TerminalKey.dead_Abovering,+// 'Dead_Doubleacute': TerminalKey.dead_Doubleacute,+// 'Dead_Caron': TerminalKey.dead_Caron,+// 'Dead_Cedilla': TerminalKey.dead_Cedilla,+// 'Dead_Ogonek': TerminalKey.dead_Ogonek,+// 'Dead_Iota': TerminalKey.dead_Iota,+// 'Dead_Voiced_Sound': TerminalKey.dead_Voiced_Sound,+// 'Dead_Semivoiced_Sound': TerminalKey.dead_Semivoiced_Sound,+// 'Dead_Belowdot': TerminalKey.dead_Belowdot,+// 'Dead_Hook': TerminalKey.dead_Hook,+// 'Dead_Horn': TerminalKey.dead_Horn,+// 'Dead_Stroke': TerminalKey.dead_Stroke,+// 'Dead_Abovecomma': TerminalKey.dead_Abovecomma,+// 'Dead_Abovereversedcomma': TerminalKey.dead_Abovereversedcomma,+// 'Dead_Doublegrave': TerminalKey.dead_Doublegrave,+// 'Dead_Belowring': TerminalKey.dead_Belowring,+// 'Dead_Belowmacron': TerminalKey.dead_Belowmacron,+// 'Dead_Belowcircumflex': TerminalKey.dead_Belowcircumflex,+// 'Dead_Belowtilde': TerminalKey.dead_Belowtilde,+// 'Dead_Belowbreve': TerminalKey.dead_Belowbreve,+// 'Dead_Belowdiaeresis': TerminalKey.dead_Belowdiaeresis,+// 'Dead_Invertedbreve': TerminalKey.dead_Invertedbreve,+// 'Dead_Belowcomma': TerminalKey.dead_Belowcomma,+// 'Dead_Currency': TerminalKey.dead_Currency,+// 'Dead_a': TerminalKey.dead_a,+// 'Dead_A': TerminalKey.dead_A,+// 'Dead_e': TerminalKey.dead_e,+// 'Dead_E': TerminalKey.dead_E,+// 'Dead_i': TerminalKey.dead_i,+// 'Dead_I': TerminalKey.dead_I,+// 'Dead_o': TerminalKey.dead_o,+// 'Dead_O': TerminalKey.dead_O,+// 'Dead_u': TerminalKey.dead_u,+// 'Dead_U': TerminalKey.dead_U,+// 'Dead_Small_Schwa': TerminalKey.dead_Small_Schwa,+// 'Dead_Capital_Schwa': TerminalKey.dead_Capital_Schwa,+// 'Dead_Greek': TerminalKey.dead_Greek,+// 'Dead_Lowline': TerminalKey.dead_Lowline,+// 'Dead_Aboveverticalline': TerminalKey.dead_Aboveverticalline,+// 'Dead_Belowverticalline': TerminalKey.dead_Belowverticalline,+// 'Dead_Longsolidusoverlay': TerminalKey.dead_Longsolidusoverlay,+// 'Back': TerminalKey.back,+// 'Forward': TerminalKey.forward,+// 'Stop': TerminalKey.stop,+// 'Refresh': TerminalKey.refresh,+ 'VolumeDown': TerminalKey.audioVolumeDown,+ 'VolumeMute': TerminalKey.audioVolumeMute,+ 'VolumeUp': TerminalKey.audioVolumeUp,+ 'BassBoost': TerminalKey.bassBoost,+// 'BassUp': TerminalKey.bassUp,+// 'BassDown': TerminalKey.bassDown,+// 'TrebleUp': TerminalKey.trebleUp,+// 'TrebleDown': TerminalKey.trebleDown,+ 'MediaPlay': TerminalKey.mediaPlay,+ 'MediaStop': TerminalKey.mediaStop,+// 'MediaPrevious': TerminalKey.mediaPrevious,+// 'MediaNext': TerminalKey.mediaNext,+ 'MediaRecord': TerminalKey.mediaRecord,+ 'MediaPause': TerminalKey.mediaPause,+ 'MediaTogglePlayPause': TerminalKey.mediaPlayPause,+ 'HomePage': TerminalKey.browserHome,+// 'Favorites': TerminalKey.favorites,+// 'Search': TerminalKey.search,+// 'Standby': TerminalKey.standby,+// 'OpenUrl': TerminalKey.openUrl,+// 'LaunchMail': TerminalKey.launchMail,+// 'LaunchMedia': TerminalKey.launchMedia,+// 'Launch0': TerminalKey.launch0,+// 'Launch1': TerminalKey.launch1,+// 'Launch2': TerminalKey.launch2,+// 'Launch3': TerminalKey.launch3,+// 'Launch4': TerminalKey.launch4,+// 'Launch5': TerminalKey.launch5,+// 'Launch6': TerminalKey.launch6,+// 'Launch7': TerminalKey.launch7,+// 'Launch8': TerminalKey.launch8,+// 'Launch9': TerminalKey.launch9,+// 'LaunchA': TerminalKey.launchA,+// 'LaunchB': TerminalKey.launchB,+// 'LaunchC': TerminalKey.launchC,+// 'LaunchD': TerminalKey.launchD,+// 'LaunchE': TerminalKey.launchE,+// 'LaunchF': TerminalKey.launchF,+// 'LaunchG': TerminalKey.launchG,+// 'LaunchH': TerminalKey.launchH,+ 'MonBrightnessUp': TerminalKey.brightnessUp,+ 'MonBrightnessDown': TerminalKey.brightnessDown,+// 'KeyboardLightOnOff': TerminalKey.keyboardLightOnOff,+// 'KeyboardBrightnessUp': TerminalKey.keyboardBrightnessUp,+// 'KeyboardBrightnessDown': TerminalKey.keyboardBrightnessDown,+ 'PowerOff': TerminalKey.power,+ 'WakeUp': TerminalKey.wakeUp,+ 'Eject': TerminalKey.eject,+// 'ScreenSaver': TerminalKey.screenSaver,+// 'WWW': TerminalKey.wWW,+// 'Memo': TerminalKey.memo,+// 'LightBulb': TerminalKey.lightBulb,+// 'Shop': TerminalKey.shop,+// 'History': TerminalKey.history,+// 'AddFavorite': TerminalKey.addFavorite,+// 'HotLinks': TerminalKey.hotLinks,+// 'BrightnessAdjust': TerminalKey.brightnessAdjust,+// 'Finance': TerminalKey.finance,+// 'Community': TerminalKey.community,+// 'AudioRewind': TerminalKey.audioRewind,+// 'BackForward': TerminalKey.backForward,+// 'ApplicationLeft': TerminalKey.applicationLeft,+// 'ApplicationRight': TerminalKey.applicationRight,+// 'Book': TerminalKey.book,+// 'CD': TerminalKey.cD,+// 'Calculator': TerminalKey.calculator,+// 'ToDoList': TerminalKey.toDoList,+// 'ClearGrab': TerminalKey.clearGrab,+ 'Close': TerminalKey.close,+ 'Copy': TerminalKey.copy,+ 'Cut': TerminalKey.cut,+// 'Display': TerminalKey.display,+// 'DOS': TerminalKey.dOS,+// 'Documents': TerminalKey.documents,+// 'Excel': TerminalKey.excel,+// 'Explorer': TerminalKey.explorer,+// 'Game': TerminalKey.game,+// 'Go': TerminalKey.go,+// 'iTouch': TerminalKey.iTouch,+// 'LogOff': TerminalKey.logOff,+// 'Market': TerminalKey.market,+// 'Meeting': TerminalKey.meeting,+// 'MenuKB': TerminalKey.menuKB,+// 'MenuPB': TerminalKey.menuPB,+// 'MySites': TerminalKey.mySites,+// 'News': TerminalKey.news,+// 'OfficeHome': TerminalKey.officeHome,+// 'Option': TerminalKey.option,+// 'Paste': TerminalKey.paste,+// 'Phone': TerminalKey.phone,+// 'Calendar': TerminalKey.calendar,+// 'Reply': TerminalKey.reply,+// 'Reload': TerminalKey.reload,+// 'RotateWindows': TerminalKey.rotateWindows,+// 'RotationPB': TerminalKey.rotationPB,+// 'RotationKB': TerminalKey.rotationKB,+ 'Save': TerminalKey.save,+// 'Send': TerminalKey.send,+// 'Spell': TerminalKey.spell,+// 'SplitScreen': TerminalKey.splitScreen,+// 'Support': TerminalKey.support,+// 'TaskPane': TerminalKey.taskPane,+// 'Terminal': TerminalKey.terminal,+// 'Tools': TerminalKey.tools,+// 'Travel': TerminalKey.travel,+// 'Video': TerminalKey.video,+// 'Word': TerminalKey.word,+// 'Xfer': TerminalKey.xfer,+ 'ZoomIn': TerminalKey.zoomIn,+ 'ZoomOut': TerminalKey.zoomOut,+// 'Away': TerminalKey.away,+// 'Messenger': TerminalKey.messenger,+// 'WebCam': TerminalKey.webCam,+// 'MailForward': TerminalKey.mailForward,+// 'Pictures': TerminalKey.pictures,+// 'Music': TerminalKey.music,+// 'Battery': TerminalKey.battery,+// 'Bluetooth': TerminalKey.bluetooth,+// 'WLAN': TerminalKey.wLAN,+// 'UWB': TerminalKey.uWB,+// 'AudioForward': TerminalKey.audioForward,+// 'AudioRepeat': TerminalKey.audioRepeat,+// 'AudioRandomPlay': TerminalKey.audioRandomPlay,+// 'Subtitle': TerminalKey.subtitle,+// 'AudioCycleTrack': TerminalKey.audioCycleTrack,+// 'Time': TerminalKey.time,+// 'Hibernate': TerminalKey.hibernate,+// 'View': TerminalKey.view,+// 'TopMenu': TerminalKey.topMenu,+// 'PowerDown': TerminalKey.powerDown,+// 'Suspend': TerminalKey.suspend,+// 'ContrastAdjust': TerminalKey.contrastAdjust,+// 'TouchpadToggle': TerminalKey.touchpadToggle,+// 'TouchpadOn': TerminalKey.touchpadOn,+// 'TouchpadOff': TerminalKey.touchpadOff,+// 'MicMute': TerminalKey.micMute,+// 'Red': TerminalKey.red,+// 'Green': TerminalKey.green,+// 'Yellow': TerminalKey.yellow,+// 'Blue': TerminalKey.blue,+ 'ChannelUp': TerminalKey.channelUp,+ 'ChannelDown': TerminalKey.channelDown,+// 'Guide': TerminalKey.guide,+ 'Info': TerminalKey.info,+// 'Settings': TerminalKey.settings,+// 'MicVolumeUp': TerminalKey.micVolumeUp,+// 'MicVolumeDown': TerminalKey.micVolumeDown,+// 'New': TerminalKey.new,+ 'Open': TerminalKey.open,+ 'Find': TerminalKey.find,+ 'Undo': TerminalKey.undo,+ 'Redo': TerminalKey.redo,+ 'MediaLast': TerminalKey.mediaLast,+// 'unknown': TerminalKey.unknown,+// 'Call': TerminalKey.call,+// 'Camera': TerminalKey.camera,+// 'CameraFocus': TerminalKey.cameraFocus,+// 'Context1': TerminalKey.context1,+// 'Context2': TerminalKey.context2,+// 'Context3': TerminalKey.context3,+// 'Context4': TerminalKey.context4,+// 'Flip': TerminalKey.flip,+// 'Hangup': TerminalKey.hangup,+// 'No': TerminalKey.no,+ 'Select': TerminalKey.select,+// 'Yes': TerminalKey.yes,+// 'ToggleCallHangup': TerminalKey.toggleCallHangup,+// 'VoiceDial': TerminalKey.voiceDial,+// 'LastNumberRedial': TerminalKey.lastNumberRedial,+// 'Execute': TerminalKey.execute,+// 'Printer': TerminalKey.printer,+// 'Play': TerminalKey.play,+ 'Sleep': TerminalKey.sleep,+// 'Zoom': TerminalKey.zoom,+ 'Exit': TerminalKey.exit,+// 'Cancel': TerminalKey.cancel,+};diff --git a/mobile/third_party/xterm/lib/src/core/mouse/button.dart b/mobile/third_party/xterm/lib/src/core/mouse/button.dartnew file mode 100644index 000000000..a3d0fbee4--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/mouse/button.dart@@ -0,0 +1,33 @@+enum TerminalMouseButton {+ left(id: 0),++ middle(id: 1),++ right(id: 2),++ wheelUp(id: 64, isWheel: true),++ wheelDown(id: 65, isWheel: true),++ wheelLeft(id: 66, isWheel: true),++ wheelRight(id: 67, isWheel: true),+ ;++ /// The id that is used to report a button press or release to the terminal.+ ///+ /// Per the xterm mouse-tracking spec, wheel events reuse the button-1/button-2 event codes+ /// (0 and 1) with 64 added — i.e. wheel-up=64, wheel-down=65 (and, by the same extension used for+ /// horizontal wheel/tilt, wheel-left=66, wheel-right=67). These are NOT "id 4"/"id 5" (the+ /// conventional 1-based wheel button numbers) plus 64 — that produced 68/69/70/71, codes outside+ /// what any real terminal program's mouse-report parser recognizes as a wheel event, so a program+ /// that owns its own mouse-tracking (e.g. the Claude Code CLI) silently ignored every wheel report+ /// this emitted. Confirmed against a real program: identical bytes with Cb=64/65 scroll it+ /// correctly; Cb=68/69 do nothing.+ final int id;++ /// Whether this button is a mouse wheel button.+ final bool isWheel;++ const TerminalMouseButton({required this.id, this.isWheel = false});+}diff --git a/mobile/third_party/xterm/lib/src/core/mouse/button_state.dart b/mobile/third_party/xterm/lib/src/core/mouse/button_state.dartnew file mode 100644index 000000000..9c8dc4c2e--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/mouse/button_state.dart@@ -0,0 +1,5 @@+enum TerminalMouseButtonState {+ up,++ down,+}diff --git a/mobile/third_party/xterm/lib/src/core/mouse/handler.dart b/mobile/third_party/xterm/lib/src/core/mouse/handler.dartnew file mode 100644index 000000000..bb0438863--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/mouse/handler.dart@@ -0,0 +1,114 @@+import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/mouse/button_state.dart';+import 'package:xterm/src/core/mouse/mode.dart';+import 'package:xterm/src/core/mouse/button.dart';+import 'package:xterm/src/core/mouse/reporter.dart';+import 'package:xterm/src/core/platform.dart';+import 'package:xterm/src/core/state.dart';++class TerminalMouseEvent {+ /// The button that is pressed or released.+ final TerminalMouseButton button;++ /// The current state of the button.+ final TerminalMouseButtonState buttonState;++ /// The position of button state change.+ final CellOffset position;++ /// The state of the terminal.+ final TerminalState state;++ /// The platform of the terminal.+ final TerminalTargetPlatform platform;++ TerminalMouseEvent({+ required this.button,+ required this.buttonState,+ required this.position,+ required this.state,+ required this.platform,+ });+}++const defaultMouseHandler = CascadeMouseHandler([+ ClickMouseHandler(),+ UpDownMouseHandler(),+]);++abstract class TerminalMouseHandler {+ const TerminalMouseHandler();++ String? call(TerminalMouseEvent event);+}++class CascadeMouseHandler implements TerminalMouseHandler {+ final List<TerminalMouseHandler> _handlers;++ const CascadeMouseHandler(this._handlers);++ @override+ String? call(TerminalMouseEvent event) {+ for (var handler in _handlers) {+ final result = handler(event);+ if (result != null) {+ return result;+ }+ }+ return null;+ }+}++class ClickMouseHandler implements TerminalMouseHandler {+ const ClickMouseHandler();++ @override+ String? call(TerminalMouseEvent event) {+ switch (event.state.mouseMode) {+ case MouseMode.clickOnly:+ // Only clicks and only the first 3 buttons are reported.+ if (event.buttonState == TerminalMouseButtonState.down &&+ (event.button.id < 3)) {+ return MouseReporter.report(+ event.button,+ event.buttonState,+ event.position,+ event.state.mouseReportMode,+ );+ }+ return null;+ case MouseMode.none:+ case MouseMode.upDownScroll:+ case MouseMode.upDownScrollDrag:+ case MouseMode.upDownScrollMove:+ return null;+ }+ }+}++class UpDownMouseHandler implements TerminalMouseHandler {+ const UpDownMouseHandler();++ @override+ String? call(TerminalMouseEvent event) {+ switch (event.state.mouseMode) {+ case MouseMode.none:+ case MouseMode.clickOnly:+ return null;+ case MouseMode.upDownScroll:+ case MouseMode.upDownScrollDrag:+ case MouseMode.upDownScrollMove:+ // Up events are never reported for mouse wheel buttons.+ if (event.button.isWheel &&+ event.buttonState == TerminalMouseButtonState.up) {+ return null;+ }+ return MouseReporter.report(+ event.button,+ event.buttonState,+ event.position,+ event.state.mouseReportMode,+ );+ }+ }+}diff --git a/mobile/third_party/xterm/lib/src/core/mouse/mode.dart b/mobile/third_party/xterm/lib/src/core/mouse/mode.dartnew file mode 100644index 000000000..ecd006b01--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/mouse/mode.dart@@ -0,0 +1,36 @@+/// https://terminalguide.namepad.de/mouse/+enum MouseMode {+ none,++ clickOnly,++ upDownScroll(reportScroll: true),++ upDownScrollDrag(reportScroll: true),++ upDownScrollMove(reportScroll: true),+ ;++ const MouseMode({this.reportScroll = false});++ final bool reportScroll;+}++/// https://terminalguide.namepad.de/mouse/+enum MouseReportMode {+ /// The default mouse reporting mode where digits are encoded as bytes with+ /// `32 + code`. This mode has a range from 1 to 223.+ normal,++ /// When code < 96 this is the same as [normal], otherwise the `code + 32` is+ /// encoded as 2 bytes in UTF-8. This mode has a range from 1 to 2015.+ utf,++ /// In this mode the code are encoded as 10-based numbers. Tha range is+ /// unlimited.+ sgr,++ /// Similar to [sgr], the difference is that the button id is encoded as+ /// `32 + code`.+ urxvt,+}diff --git a/mobile/third_party/xterm/lib/src/core/mouse/reporter.dart b/mobile/third_party/xterm/lib/src/core/mouse/reporter.dartnew file mode 100644index 000000000..3417b6342--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/mouse/reporter.dart@@ -0,0 +1,48 @@+import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/mouse/mode.dart';+import 'package:xterm/src/core/mouse/button.dart';+import 'package:xterm/src/core/mouse/button_state.dart';++abstract class MouseReporter {+ static String report(+ TerminalMouseButton button,+ TerminalMouseButtonState state,+ CellOffset position,+ MouseReportMode reportMode,+ ) {+ // x and y offsets have to be incremented by 1 as the offset if 0-based,+ // The position has to be reported using 1-based coordinates.+ final x = position.x + 1;+ final y = position.y + 1;+ switch (reportMode) {+ case MouseReportMode.normal:+ case MouseReportMode.utf:+ // Button ID 3 is used to signal a button release.+ final buttonID = state == TerminalMouseButtonState.up ? 3 : button.id;+ // The button ID is reported as shifted by 32 to produce a printable+ // character.+ final btn = String.fromCharCode(32 + buttonID);+ // Normal mode only supports a maximum position of 223, while utf+ // supports positions up to 2015. Both modes send a null byte if the+ // position exceeds that limit.+ final col = (reportMode == MouseReportMode.normal && x > 223) ||+ (reportMode == MouseReportMode.utf && x > 2015)+ ? '\x00'+ : String.fromCharCode(32 + x);+ final row = (reportMode == MouseReportMode.normal && y > 223) ||+ (reportMode == MouseReportMode.utf && y > 2015)+ ? '\x00'+ : String.fromCharCode(32 + y + 1);+ return "\x1b[M$btn$col$row";+ case MouseReportMode.sgr:+ final buttonID = button.id;+ final upDown = state == TerminalMouseButtonState.down ? 'M' : 'm';+ return "\x1b[<$buttonID;$x;$y$upDown";+ case MouseReportMode.urxvt:+ // The button ID uses the same id as to report it as in normal mode.+ final buttonID =+ 32 + (state == TerminalMouseButtonState.up ? 3 : button.id);+ return "\x1b[$buttonID;$x;${y}M";+ }+ }+}diff --git a/mobile/third_party/xterm/lib/src/core/platform.dart b/mobile/third_party/xterm/lib/src/core/platform.dartnew file mode 100644index 000000000..3c955fd84--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/platform.dart@@ -0,0 +1,17 @@+enum TerminalTargetPlatform {+ unknown,++ android,++ ios,++ fuchsia,++ linux,++ macos,++ windows,++ web,+}diff --git a/mobile/third_party/xterm/lib/src/core/reflow.dart b/mobile/third_party/xterm/lib/src/core/reflow.dartnew file mode 100644index 000000000..06e326e6a--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/reflow.dart@@ -0,0 +1,197 @@+import 'package:xterm/src/core/buffer/line.dart';+import 'package:xterm/src/utils/circular_buffer.dart';++class _LineBuilder {+ _LineBuilder([this._capacity = 80]) {+ _result = BufferLine(_capacity);+ }++ final int _capacity;++ late BufferLine _result;++ int _length = 0;++ int get length => _length;++ bool get isEmpty => _length == 0;++ bool get isNotEmpty => _length != 0;++ /// Adds a range of cells from [src] to the builder. Anchors within the range+ /// will be reparented to the new line returned by [take].+ void add(BufferLine src, int start, int length) {+ _result.copyFrom(src, start, _length, length);+ _length += length;+ }++ /// Reuses the given [line] as the initial buffer for this builder.+ void setBuffer(BufferLine line, int length) {+ _result = line;+ _length = length;+ }++ void addAnchor(CellAnchor anchor, int offset) {+ anchor.reparent(_result, _length + offset);+ }++ BufferLine take({required bool wrapped}) {+ final result = _result;+ result.isWrapped = wrapped;+ // result.resize(_length);++ _result = BufferLine(_capacity);+ _length = 0;++ return result;+ }+}++/// Holds a the state of reflow operation of a single logical line.+class _LineReflow {+ final int oldWidth;++ final int newWidth;++ _LineReflow(this.oldWidth, this.newWidth);++ final _lines = <BufferLine>[];++ late final _builder = _LineBuilder(newWidth);++ /// Adds a line to the reflow operation. This method will try to reuse the+ /// given line if possible.+ void add(BufferLine line) {+ final trimmedLength = line.getTrimmedLength(oldWidth);++ // A fast path for empty lines+ if (trimmedLength == 0) {+ _lines.add(line);+ return;+ }++ // We already have some content in the buffer, so we copy the content into+ // the builder instead of reusing the line.+ if (_lines.isNotEmpty || _builder.isNotEmpty) {+ _addPart(line, from: 0, to: trimmedLength);+ return;+ }++ if (newWidth >= oldWidth) {+ // Reuse the line to avoid copying the content and object allocation.+ _builder.setBuffer(line, trimmedLength);+ } else {+ _lines.add(line);++ if (trimmedLength > newWidth) {+ if (line.getWidth(newWidth - 1) == 2) {+ _addPart(line, from: newWidth - 1, to: trimmedLength);+ } else {+ _addPart(line, from: newWidth, to: trimmedLength);+ }+ }+ }++ line.resize(newWidth);++ if (line.getWidth(newWidth - 1) == 2) {+ line.resetCell(newWidth - 1);+ }+ }++ /// Adds part of [line] from [from] to [to] to the reflow operation.+ /// Anchors within the range will be removed from [line] and reparented to+ /// the new line(s) returned by [finish].+ void _addPart(BufferLine line, {required int from, required int to}) {+ var cellsLeft = to - from;++ while (cellsLeft > 0) {+ final bufferRemainingCells = newWidth - _builder.length;++ // How many cells we should copy in this iteration.+ var cellsToCopy = cellsLeft;++ // Whether the buffer is filled up in this iteration.+ var lineFilled = false;++ if (cellsToCopy >= bufferRemainingCells) {+ cellsToCopy = bufferRemainingCells;+ lineFilled = true;+ }++ // Leave the last cell to the next iteration if it's a wide char.+ if (lineFilled && line.getWidth(from + cellsToCopy - 1) == 2) {+ cellsToCopy--;+ }++ for (var anchor in line.anchors.toList()) {+ if (anchor.x >= from && anchor.x <= from + cellsToCopy) {+ _builder.addAnchor(anchor, anchor.x - from);+ }+ }++ _builder.add(line, from, cellsToCopy);++ from += cellsToCopy;+ cellsLeft -= cellsToCopy;++ // Create a new line if the buffer is filled up.+ if (lineFilled) {+ _lines.add(_builder.take(wrapped: _lines.isNotEmpty));+ }+ }++ if (line.anchors.isNotEmpty) {+ for (var anchor in line.anchors.toList()) {+ if (anchor.x >= to) {+ _builder.addAnchor(anchor, anchor.x - to);+ }+ }+ }+ }++ /// Finalizes the reflow operation and returns the result.+ List<BufferLine> finish() {+ if (_builder.isNotEmpty) {+ _lines.add(_builder.take(wrapped: _lines.isNotEmpty));+ }++ return _lines;+ }+}++List<BufferLine> reflow(+ IndexAwareCircularBuffer<BufferLine> lines,+ int oldWidth,+ int newWidth,+) {+ final result = <BufferLine>[];++ for (var i = 0; i < lines.length; i++) {+ final line = lines[i];++ final reflow = _LineReflow(oldWidth, newWidth);++ reflow.add(line);++ for (var offset = i + 1; offset < lines.length; offset++) {+ final nextLine = lines[offset];++ if (!nextLine.isWrapped) {+ break;+ }++ i++;++ reflow.add(nextLine);+ }++ result.addAll(reflow.finish());+ }++ for (var line in result) {+ line.resize(newWidth);+ }++ return result;+}diff --git a/mobile/third_party/xterm/lib/src/core/snapshot.dart b/mobile/third_party/xterm/lib/src/core/snapshot.dartnew file mode 100644index 000000000..319fc4a24--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/snapshot.dart@@ -0,0 +1,3 @@+abstract class TerminalSnapshot {+ void trimScrollback();+}diff --git a/mobile/third_party/xterm/lib/src/core/state.dart b/mobile/third_party/xterm/lib/src/core/state.dartnew file mode 100644index 000000000..85684f863--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/state.dart@@ -0,0 +1,44 @@+import 'package:xterm/src/core/cursor.dart';+import 'package:xterm/src/core/mouse/mode.dart';++abstract class TerminalState {+ int get viewWidth;++ int get viewHeight;++ CursorStyle get cursor;++ bool get reflowEnabled;++ /* Modes */++ bool get insertMode;++ bool get lineFeedMode;++ /* DEC Private modes */++ bool get cursorKeysMode;++ bool get reverseDisplayMode;++ bool get originMode;++ bool get autoWrapMode;++ MouseMode get mouseMode;++ MouseReportMode get mouseReportMode;++ bool get cursorBlinkMode;++ bool get cursorVisibleMode;++ bool get appKeypadMode;++ bool get reportFocusMode;++ bool get altBufferMouseScrollMode;++ bool get bracketedPasteMode;+}diff --git a/mobile/third_party/xterm/lib/src/core/tabs.dart b/mobile/third_party/xterm/lib/src/core/tabs.dartnew file mode 100644index 000000000..385f94998--- /dev/null+++ b/mobile/third_party/xterm/lib/src/core/tabs.dart@@ -0,0 +1,68 @@+import 'dart:math' show min;++const _kMaxColumns = 1024;++/// Manages the tab stop state for a terminal.+class TabStops {+ final _stops = List<bool>.filled(_kMaxColumns, false);++ TabStops() {+ _initialize();+ }++ /// Initializes the tab stops to the default 8 column intervals.+ void _initialize() {+ const interval = 8;+ for (var i = 0; i < _kMaxColumns; i += interval) {+ _stops[i] = true;+ }+ }++ /// Finds the next tab stop index, which satisfies [start] <= index < [end].+ int? find(int start, int end) {+ if (start >= end) {+ return null;+ }+ end = min(end, _stops.length);+ for (var i = start; i < end; i++) {+ if (_stops[i]) {+ return i;+ }+ }+ return null;+ }++ /// Sets the tab stop at [index]. If there is already a tab stop at [index],+ /// this method does nothing.+ ///+ /// See also:+ /// * [clearAt] which does the opposite.+ void setAt(int index) {+ assert(index >= 0 && index < _kMaxColumns);+ _stops[index] = true;+ }++ /// Clears the tab stop at [index]. If there is no tab stop at [index], this+ /// method does nothing.+ void clearAt(int index) {+ assert(index >= 0 && index < _kMaxColumns);+ _stops[index] = false;+ }++ /// Clears all tab stops without resetting them to the default 8 column+ /// intervals.+ void clearAll() {+ _stops.fillRange(0, _kMaxColumns, false);+ }++ /// Returns true if there is a tab stop at [index].+ bool isSetAt(int index) {+ return _stops[index];+ }++ /// Resets the tab stops to the default 8 column intervals.+ void reset() {+ clearAll();+ _initialize();+ }+}diff --git a/mobile/third_party/xterm/lib/src/terminal.dart b/mobile/third_party/xterm/lib/src/terminal.dartnew file mode 100644index 000000000..0c174438e--- /dev/null+++ b/mobile/third_party/xterm/lib/src/terminal.dart@@ -0,0 +1,920 @@+import 'dart:math' show max;++import 'package:xterm/src/base/observable.dart';+import 'package:xterm/src/core/buffer/buffer.dart';+import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/buffer/line.dart';+import 'package:xterm/src/core/cursor.dart';+import 'package:xterm/src/core/escape/emitter.dart';+import 'package:xterm/src/core/escape/handler.dart';+import 'package:xterm/src/core/escape/parser.dart';+import 'package:xterm/src/core/input/handler.dart';+import 'package:xterm/src/core/input/keys.dart';+import 'package:xterm/src/core/mouse/button.dart';+import 'package:xterm/src/core/mouse/button_state.dart';+import 'package:xterm/src/core/mouse/handler.dart';+import 'package:xterm/src/core/mouse/mode.dart';+import 'package:xterm/src/core/platform.dart';+import 'package:xterm/src/core/state.dart';+import 'package:xterm/src/core/tabs.dart';+import 'package:xterm/src/utils/ascii.dart';+import 'package:xterm/src/utils/circular_buffer.dart';++/// [Terminal] is an interface to interact with command line applications. It+/// translates escape sequences from the application into updates to the+/// [buffer] and events such as [onTitleChange] or [onBell], as well as+/// translating user input into escape sequences that the application can+/// understand.+class Terminal with Observable implements TerminalState, EscapeHandler {+ /// The number of lines that the scrollback buffer can hold. If the buffer+ /// exceeds this size, the lines at the top of the buffer will be removed.+ final int maxLines;++ /// Function that is called when the program requests the terminal to ring+ /// the bell. If not set, the terminal will do nothing.+ void Function()? onBell;++ /// Function that is called when the program requests the terminal to change+ /// the title of the window to [title].+ void Function(String title)? onTitleChange;++ /// Function that is called when the program requests the terminal to change+ /// the icon of the window. [icon] is the name of the icon.+ void Function(String icon)? onIconChange;++ /// Function that is called when the terminal emits data to the underlying+ /// program. This is typically caused by user inputs from [textInput],+ /// [keyInput], [mouseInput], or [paste].+ void Function(String data)? onOutput;++ /// Function that is called when the dimensions of the terminal change.+ void Function(int width, int height, int pixelWidth, int pixelHeight)?+ onResize;++ /// The [TerminalInputHandler] used by this terminal. [defaultInputHandler] is+ /// used when not specified. User of this class can provide their own+ /// implementation of [TerminalInputHandler] or extend [defaultInputHandler]+ /// with [CascadeInputHandler].+ TerminalInputHandler? inputHandler;++ TerminalMouseHandler? mouseHandler;++ /// The callback that is called when the terminal receives a unrecognized+ /// escape sequence.+ void Function(String code, List<String> args)? onPrivateOSC;++ /// Flag to toggle os specific behaviors.+ final TerminalTargetPlatform platform;++ /// Characters that break selection when double clicking. If not set, the+ /// [Buffer.defaultWordSeparators] will be used.+ final Set<int>? wordSeparators;++ Terminal({+ this.maxLines = 1000,+ this.onBell,+ this.onTitleChange,+ this.onIconChange,+ this.onOutput,+ this.onResize,+ this.platform = TerminalTargetPlatform.unknown,+ this.inputHandler = defaultInputHandler,+ this.mouseHandler = defaultMouseHandler,+ this.onPrivateOSC,+ this.reflowEnabled = true,+ this.wordSeparators,+ });++ late final _parser = EscapeParser(this);++ final _emitter = const EscapeEmitter();++ late var _buffer = _mainBuffer;++ late final _mainBuffer = Buffer(+ this,+ maxLines: maxLines,+ isAltBuffer: false,+ wordSeparators: wordSeparators,+ );++ late final _altBuffer = Buffer(+ this,+ maxLines: maxLines,+ isAltBuffer: true,+ wordSeparators: wordSeparators,+ );++ final _tabStops = TabStops();++ /// The last character written to the buffer. Used to implement some escape+ /// sequences that repeat the last character.+ var _precedingCodepoint = 0;++ /* TerminalState */++ int _viewWidth = 80;++ int _viewHeight = 24;++ final _cursorStyle = CursorStyle();++ bool _insertMode = false;++ bool _lineFeedMode = false;++ bool _cursorKeysMode = false;++ bool _reverseDisplayMode = false;++ bool _originMode = false;++ bool _autoWrapMode = true;++ MouseMode _mouseMode = MouseMode.none;++ MouseReportMode _mouseReportMode = MouseReportMode.normal;++ bool _cursorBlinkMode = false;++ bool _cursorVisibleMode = true;++ bool _appKeypadMode = false;++ bool _reportFocusMode = false;++ bool _altBufferMouseScrollMode = false;++ bool _bracketedPasteMode = false;++ /* State getters */++ /// Number of cells in a terminal row.+ @override+ int get viewWidth => _viewWidth;++ /// Number of rows in this terminal.+ @override+ int get viewHeight => _viewHeight;++ @override+ CursorStyle get cursor => _cursorStyle;++ @override+ bool get insertMode => _insertMode;++ @override+ bool get lineFeedMode => _lineFeedMode;++ @override+ bool get cursorKeysMode => _cursorKeysMode;++ @override+ bool get reverseDisplayMode => _reverseDisplayMode;++ @override+ bool get originMode => _originMode;++ @override+ bool get autoWrapMode => _autoWrapMode;++ @override+ MouseMode get mouseMode => _mouseMode;++ @override+ MouseReportMode get mouseReportMode => _mouseReportMode;++ @override+ bool get cursorBlinkMode => _cursorBlinkMode;++ @override+ bool get cursorVisibleMode => _cursorVisibleMode;++ @override+ bool get appKeypadMode => _appKeypadMode;++ @override+ bool get reportFocusMode => _reportFocusMode;++ @override+ bool get altBufferMouseScrollMode => _altBufferMouseScrollMode;++ @override+ bool get bracketedPasteMode => _bracketedPasteMode;++ /// Current active buffer of the terminal. This is initially [mainBuffer] and+ /// can be switched back and forth from [altBuffer] to [mainBuffer] when+ /// the underlying program requests it.+ Buffer get buffer => _buffer;++ Buffer get mainBuffer => _mainBuffer;++ Buffer get altBuffer => _altBuffer;++ bool get isUsingAltBuffer => _buffer == _altBuffer;++ /// Lines of the active buffer.+ IndexAwareCircularBuffer<BufferLine> get lines => _buffer.lines;++ /// Whether the terminal performs reflow when the viewport size changes or+ /// simply truncates lines. true by default.+ @override+ bool reflowEnabled;++ /// Writes the data from the underlying program to the terminal. Calling this+ /// updates the states of the terminal and emits events such as [onBell] or+ /// [onTitleChange] when the escape sequences in [data] request it.+ void write(String data) {+ _parser.write(data);+ notifyListeners();+ }++ /// Sends a key event to the underlying program.+ ///+ /// See also:+ /// - [charInput]+ /// - [textInput]+ /// - [paste]+ bool keyInput(+ TerminalKey key, {+ bool shift = false,+ bool alt = false,+ bool ctrl = false,+ }) {+ final output = inputHandler?.call(+ TerminalKeyboardEvent(+ key: key,+ shift: shift,+ alt: alt,+ ctrl: ctrl,+ state: this,+ altBuffer: isUsingAltBuffer,+ platform: platform,+ ),+ );++ if (output != null) {+ onOutput?.call(output);+ return true;+ }++ return false;+ }++ /// Similary to [keyInput], but takes a character as input instead of a+ /// [TerminalKey].+ ///+ /// See also:+ /// - [keyInput]+ /// - [textInput]+ /// - [paste]+ bool charInput(+ int charCode, {+ bool alt = false,+ bool ctrl = false,+ }) {+ if (ctrl) {+ // a(97) ~ z(122)+ if (charCode >= Ascii.a && charCode <= Ascii.z) {+ final output = charCode - Ascii.a + 1;+ onOutput?.call(String.fromCharCode(output));+ return true;+ }++ // [(91) ~ _(95)+ if (charCode >= Ascii.openBracket && charCode <= Ascii.underscore) {+ final output = charCode - Ascii.openBracket + 27;+ onOutput?.call(String.fromCharCode(output));+ return true;+ }+ }++ if (alt && platform != TerminalTargetPlatform.macos) {+ if (charCode >= Ascii.a && charCode <= Ascii.z) {+ final code = charCode - Ascii.a + 65;+ final input = [0x1b, code];+ onOutput?.call(String.fromCharCodes(input));+ return true;+ }+ }++ return false;+ }++ /// Sends regular text input to the underlying program.+ ///+ /// See also:+ /// - [keyInput]+ /// - [charInput]+ /// - [paste]+ void textInput(String text) {+ onOutput?.call(text);+ }++ /// Similar to [textInput], except that when the program tells the terminal+ /// that it supports [bracketedPasteMode], the text is wrapped in escape+ /// sequences to indicate that it is a paste operation. Prefer this method+ /// over [textInput] when pasting text.+ ///+ /// See also:+ /// - [textInput]+ void paste(String text) {+ if (_bracketedPasteMode) {+ onOutput?.call(_emitter.bracketedPaste(text));+ } else {+ textInput(text);+ }+ }++ // Handle a mouse event and return true if it was handled.+ bool mouseInput(+ TerminalMouseButton button,+ TerminalMouseButtonState buttonState,+ CellOffset position,+ ) {+ final output = mouseHandler?.call(TerminalMouseEvent(+ button: button,+ buttonState: buttonState,+ position: position,+ state: this,+ platform: platform,+ ));+ if (output != null) {+ onOutput?.call(output);+ return true;+ }+ return false;+ }++ Set<void Function()>? _resizeListeners;++ /// Observes completed local buffer reflow without replacing the transport's+ /// onResize callback. No observer set is retained when the last user leaves.+ void addResizeListener(void Function() listener) {+ (_resizeListeners ??= {}).add(listener);+ }++ void removeResizeListener(void Function() listener) {+ _resizeListeners?.remove(listener);+ if (_resizeListeners?.isEmpty == true) _resizeListeners = null;+ }++ /// Resize the screen and notify local observers after buffer reflow.+ @override+ void resize(+ int newWidth,+ int newHeight, [+ int? pixelWidth,+ int? pixelHeight,+ ]) {+ newWidth = max(newWidth, 1);+ newHeight = max(newHeight, 1);++ onResize?.call(newWidth, newHeight, pixelWidth ?? 0, pixelHeight ?? 0);++ //we need to resize both buffers so that they are ready when we switch between them+ _altBuffer.resize(_viewWidth, _viewHeight, newWidth, newHeight);+ _mainBuffer.resize(_viewWidth, _viewHeight, newWidth, newHeight);++ _viewWidth = newWidth;+ _viewHeight = newHeight;++ if (buffer == _altBuffer) {+ buffer.clearScrollback();+ }++ _altBuffer.resetVerticalMargins();+ _mainBuffer.resetVerticalMargins();+ for (final listener in _resizeListeners ?? const <void Function()>{}) {+ listener();+ }+ }++ @override+ String toString() {+ return 'Terminal(#$hashCode, $_viewWidth x $_viewHeight, ${_buffer.height} lines)';+ }++ /* Handlers */++ @override+ void writeChar(int char) {+ _precedingCodepoint = char;+ _buffer.writeChar(char);+ }++ /* SBC */++ @override+ void bell() {+ onBell?.call();+ }++ @override+ void backspaceReturn() {+ _buffer.moveCursorX(-1);+ }++ @override+ void tab() {+ final nextStop = _tabStops.find(_buffer.cursorX + 1, _viewWidth);++ if (nextStop != null) {+ _buffer.setCursorX(nextStop);+ } else {+ _buffer.setCursorX(_viewWidth);+ _buffer.cursorGoForward(); // Enter pending-wrap state+ }+ }++ @override+ void lineFeed() {+ _buffer.lineFeed();+ }++ @override+ void carriageReturn() {+ _buffer.setCursorX(0);+ }++ @override+ void shiftOut() {+ _buffer.charset.use(1);+ }++ @override+ void shiftIn() {+ _buffer.charset.use(0);+ }++ @override+ void unknownSBC(int char) {+ // no-op+ }++ /* ANSI sequence */++ @override+ void saveCursor() {+ _buffer.saveCursor();+ }++ @override+ void restoreCursor() {+ _buffer.restoreCursor();+ }++ @override+ void index() {+ _buffer.index();+ }++ @override+ void nextLine() {+ _buffer.index();+ _buffer.setCursorX(0);+ }++ @override+ void setTapStop() {+ _tabStops.isSetAt(_buffer.cursorX);+ }++ @override+ void reverseIndex() {+ _buffer.reverseIndex();+ }++ @override+ void designateCharset(int charset, int name) {+ _buffer.charset.designate(charset, name);+ }++ @override+ void unkownEscape(int char) {+ // no-op+ }++ /* CSI */++ @override+ void repeatPreviousCharacter(int count) {+ if (_precedingCodepoint == 0) {+ return;+ }++ for (var i = 0; i < count; i++) {+ _buffer.writeChar(_precedingCodepoint);+ }+ }++ @override+ void setCursor(int x, int y) {+ _buffer.setCursor(x, y);+ }++ @override+ void setCursorX(int x) {+ _buffer.setCursorX(x);+ }++ @override+ void setCursorY(int y) {+ _buffer.setCursorY(y);+ }++ @override+ void moveCursorX(int offset) {+ _buffer.moveCursorX(offset);+ }++ @override+ void moveCursorY(int n) {+ _buffer.moveCursorY(n);+ }++ @override+ void clearTabStopUnderCursor() {+ _tabStops.clearAt(_buffer.cursorX);+ }++ @override+ void clearAllTabStops() {+ _tabStops.clearAll();+ }++ @override+ void sendPrimaryDeviceAttributes() {+ onOutput?.call(_emitter.primaryDeviceAttributes());+ }++ @override+ void sendSecondaryDeviceAttributes() {+ onOutput?.call(_emitter.secondaryDeviceAttributes());+ }++ @override+ void sendTertiaryDeviceAttributes() {+ onOutput?.call(_emitter.tertiaryDeviceAttributes());+ }++ @override+ void sendOperatingStatus() {+ onOutput?.call(_emitter.operatingStatus());+ }++ @override+ void sendCursorPosition() {+ onOutput?.call(_emitter.cursorPosition(_buffer.cursorX, _buffer.cursorY));+ }++ @override+ void setMargins(int top, [int? bottom]) {+ _buffer.setVerticalMargins(top, bottom ?? viewHeight - 1);+ }++ @override+ void cursorNextLine(int amount) {+ _buffer.moveCursorY(amount);+ _buffer.setCursorX(0);+ }++ @override+ void cursorPrecedingLine(int amount) {+ _buffer.moveCursorY(-amount);+ _buffer.setCursorX(0);+ }++ @override+ void eraseDisplayBelow() {+ _buffer.eraseDisplayFromCursor();+ }++ @override+ void eraseDisplayAbove() {+ _buffer.eraseDisplayToCursor();+ }++ @override+ void eraseDisplay() {+ _buffer.eraseDisplay();+ }++ @override+ void eraseScrollbackOnly() {+ _buffer.clearScrollback();+ }++ @override+ void eraseLineRight() {+ _buffer.eraseLineFromCursor();+ }++ @override+ void eraseLineLeft() {+ _buffer.eraseLineToCursor();+ }++ @override+ void eraseLine() {+ _buffer.eraseLine();+ }++ @override+ void insertLines(int amount) {+ _buffer.insertLines(amount);+ }++ @override+ void deleteLines(int amount) {+ _buffer.deleteLines(amount);+ }++ @override+ void deleteChars(int amount) {+ _buffer.deleteChars(amount);+ }++ @override+ void scrollUp(int amount) {+ _buffer.scrollUp(amount);+ }++ @override+ void scrollDown(int amount) {+ _buffer.scrollDown(amount);+ }++ @override+ void eraseChars(int amount) {+ _buffer.eraseChars(amount);+ }++ @override+ void insertBlankChars(int amount) {+ _buffer.insertBlankChars(amount);+ }++ @override+ void sendSize() {+ onOutput?.call(_emitter.size(viewHeight, viewWidth));+ }++ @override+ void unknownCSI(int finalByte) {+ // no-op+ }++ /* Modes */++ @override+ void setInsertMode(bool enabled) {+ _insertMode = enabled;+ }++ @override+ void setLineFeedMode(bool enabled) {+ _lineFeedMode = enabled;+ }++ @override+ void setUnknownMode(int mode, bool enabled) {+ // no-op+ }++ /* DEC Private modes */++ @override+ void setCursorKeysMode(bool enabled) {+ _cursorKeysMode = enabled;+ }++ @override+ void setReverseDisplayMode(bool enabled) {+ _reverseDisplayMode = enabled;+ }++ @override+ void setOriginMode(bool enabled) {+ _originMode = enabled;+ }++ @override+ void setColumnMode(bool enabled) {+ // no-op+ }++ @override+ void setAutoWrapMode(bool enabled) {+ _autoWrapMode = enabled;+ }++ @override+ void setMouseMode(MouseMode mode) {+ _mouseMode = mode;+ }++ @override+ void setCursorBlinkMode(bool enabled) {+ _cursorBlinkMode = enabled;+ }++ @override+ void setCursorVisibleMode(bool enabled) {+ _cursorVisibleMode = enabled;+ }++ @override+ void useAltBuffer() {+ _buffer = _altBuffer;+ }++ @override+ void useMainBuffer() {+ _buffer = _mainBuffer;+ }++ @override+ void clearAltBuffer() {+ _altBuffer.clear();+ }++ @override+ void setAppKeypadMode(bool enabled) {+ _appKeypadMode = enabled;+ }++ @override+ void setReportFocusMode(bool enabled) {+ _reportFocusMode = enabled;+ }++ @override+ void setMouseReportMode(MouseReportMode mode) {+ _mouseReportMode = mode;+ }++ @override+ void setAltBufferMouseScrollMode(bool enabled) {+ _altBufferMouseScrollMode = enabled;+ }++ @override+ void setBracketedPasteMode(bool enabled) {+ _bracketedPasteMode = enabled;+ }++ @override+ void setUnknownDecMode(int mode, bool enabled) {+ // no-op+ }++ /* Select Graphic Rendition (SGR) */++ @override+ void resetCursorStyle() {+ _cursorStyle.reset();+ }++ @override+ void setCursorBold() {+ _cursorStyle.setBold();+ }++ @override+ void setCursorFaint() {+ _cursorStyle.setFaint();+ }++ @override+ void setCursorItalic() {+ _cursorStyle.setItalic();+ }++ @override+ void setCursorUnderline() {+ _cursorStyle.setUnderline();+ }++ @override+ void setCursorBlink() {+ _cursorStyle.setBlink();+ }++ @override+ void setCursorInverse() {+ _cursorStyle.setInverse();+ }++ @override+ void setCursorInvisible() {+ _cursorStyle.setInvisible();+ }++ @override+ void setCursorStrikethrough() {+ _cursorStyle.setStrikethrough();+ }++ @override+ void unsetCursorBold() {+ _cursorStyle.unsetBold();+ }++ @override+ void unsetCursorFaint() {+ _cursorStyle.unsetFaint();+ }++ @override+ void unsetCursorItalic() {+ _cursorStyle.unsetItalic();+ }++ @override+ void unsetCursorUnderline() {+ _cursorStyle.unsetUnderline();+ }++ @override+ void unsetCursorBlink() {+ _cursorStyle.unsetBlink();+ }++ @override+ void unsetCursorInverse() {+ _cursorStyle.unsetInverse();+ }++ @override+ void unsetCursorInvisible() {+ _cursorStyle.unsetInvisible();+ }++ @override+ void unsetCursorStrikethrough() {+ _cursorStyle.unsetStrikethrough();+ }++ @override+ void setForegroundColor16(int color) {+ _cursorStyle.setForegroundColor16(color);+ }++ @override+ void setForegroundColor256(int index) {+ _cursorStyle.setForegroundColor256(index);+ }++ @override+ void setForegroundColorRgb(int r, int g, int b) {+ _cursorStyle.setForegroundColorRgb(r, g, b);+ }++ @override+ void resetForeground() {+ _cursorStyle.resetForegroundColor();+ }++ @override+ void setBackgroundColor16(int color) {+ _cursorStyle.setBackgroundColor16(color);+ }++ @override+ void setBackgroundColor256(int index) {+ _cursorStyle.setBackgroundColor256(index);+ }++ @override+ void setBackgroundColorRgb(int r, int g, int b) {+ _cursorStyle.setBackgroundColorRgb(r, g, b);+ }++ @override+ void resetBackground() {+ _cursorStyle.resetBackgroundColor();+ }++ @override+ void unsupportedStyle(int param) {+ // no-op+ }++ /* OSC */++ @override+ void setTitle(String name) {+ onTitleChange?.call(name);+ }++ @override+ void setIconName(String name) {+ onIconChange?.call(name);+ }++ @override+ void unknownOSC(String ps, List<String> pt) {+ onPrivateOSC?.call(ps, pt);+ }+}diff --git a/mobile/third_party/xterm/lib/src/terminal_view.dart b/mobile/third_party/xterm/lib/src/terminal_view.dartnew file mode 100644index 000000000..2269071c6--- /dev/null+++ b/mobile/third_party/xterm/lib/src/terminal_view.dart@@ -0,0 +1,752 @@+import 'package:flutter/cupertino.dart';+import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:xterm/src/core/buffer/cell_offset.dart';++import 'package:xterm/src/core/input/keys.dart';+import 'package:xterm/src/terminal.dart';+import 'package:xterm/src/ui/controller.dart';+import 'package:xterm/src/ui/cursor_type.dart';+import 'package:xterm/src/ui/custom_text_edit.dart';+import 'package:xterm/src/ui/gesture/gesture_handler.dart';+import 'package:xterm/src/ui/input_map.dart';+import 'package:xterm/src/ui/keyboard_listener.dart';+import 'package:xterm/src/ui/keyboard_visibility.dart';+import 'package:xterm/src/ui/render.dart';+import 'package:xterm/src/ui/scroll_handler.dart';+import 'package:xterm/src/ui/shortcut/actions.dart';+import 'package:xterm/src/ui/shortcut/shortcuts.dart';+import 'package:xterm/src/ui/terminal_text_style.dart';+import 'package:xterm/src/ui/terminal_theme.dart';+import 'package:xterm/src/ui/themes.dart';++class TerminalView extends StatefulWidget {+ const TerminalView(+ this.terminal, {+ super.key,+ this.controller,+ this.theme = TerminalThemes.defaultTheme,+ this.textStyle = const TerminalStyle(),+ this.textScaler,+ this.padding,+ this.scrollController,+ this.autoResize = true,+ this.resizeBuffer = true,+ this.renderingEnabled = true,+ this.backgroundOpacity = 1,+ this.focusNode,+ this.autofocus = false,+ this.onTapDown,+ this.onTapUp,+ this.onSecondaryTapDown,+ this.onSecondaryTapUp,+ this.mouseCursor = SystemMouseCursors.text,+ this.keyboardType = TextInputType.text,+ this.keyboardAppearance = Brightness.dark,+ this.cursorType = TerminalCursorType.block,+ this.alwaysShowCursor = false,+ this.deleteDetection = false,+ this.shortcuts,+ this.onKeyEvent,+ this.readOnly = false,+ this.hardwareKeyboardOnly = false,+ this.simulateScroll = true,+ this.onAltBufferScroll,+ });++ /// The underlying terminal that this widget renders.+ final Terminal terminal;++ final TerminalController? controller;++ /// The theme to use for this terminal.+ final TerminalTheme theme;++ /// The style to use for painting characters.+ final TerminalStyle textStyle;++ final TextScaler? textScaler;++ /// Padding around the inner [Scrollable] widget.+ final EdgeInsets? padding;++ /// Scroll controller for the inner [Scrollable] widget.+ final ScrollController? scrollController;++ /// Should this widget automatically notify the underlying terminal when its+ /// size changes. [true] by default.+ final bool autoResize;++ /// Resize the emulator together with the viewport. Set false for a remote+ /// grid: report the requested size through Terminal.onResize and retain the+ /// captured cells until the remote side supplies its resized screen.+ final bool resizeBuffer;++ /// Whether output should schedule renderer layout/paint work. Disable while+ /// retaining a hidden view; the terminal buffer continues receiving output.+ /// Re-enabling reconciles geometry and scroll position on the next layout.+ /// An enclosing disabled [TickerMode] also suspends rendering updates.+ final bool renderingEnabled;++ /// Opacity of the terminal background. Set to 0 to make the terminal+ /// background transparent.+ final double backgroundOpacity;++ /// An optional focus node to use as the focus node for this widget.+ final FocusNode? focusNode;++ /// True if this widget will be selected as the initial focus when no other+ /// node in its scope is currently focused.+ final bool autofocus;++ /// Return true to handle this primary click in the host instead of sending+ /// mouse reports to the terminal or clearing its selection. The matching+ /// tap up still calls [onTapUp]; dragging does not complete a click.+ final bool Function(TapDownDetails, CellOffset)? onTapDown;++ /// Callback for a primary click handled locally, including [onTapDown].+ final void Function(TapUpDetails, CellOffset)? onTapUp;++ /// Function called when the user taps on the terminal with a secondary+ /// button.+ final void Function(TapDownDetails, CellOffset)? onSecondaryTapDown;++ /// Function called when the user stops holding down a secondary button.+ final void Function(TapUpDetails, CellOffset)? onSecondaryTapUp;++ /// The mouse cursor for mouse pointers that are hovering over the terminal.+ /// [SystemMouseCursors.text] by default.+ final MouseCursor mouseCursor;++ /// The type of information for which to optimize the text input control.+ /// [TextInputType.text] by default so native IMEs can compose text.+ final TextInputType keyboardType;++ /// The appearance of the keyboard. [Brightness.dark] by default.+ ///+ /// This setting is only honored on iOS devices.+ final Brightness keyboardAppearance;++ /// The type of cursor to use. [TerminalCursorType.block] by default.+ final TerminalCursorType cursorType;++ /// Whether to always show the cursor. This is useful for debugging.+ /// [false] by default.+ final bool alwaysShowCursor;++ /// Workaround to detect delete key for platforms and IMEs that does not+ /// emit hardware delete event. Prefered on mobile platforms. [false] by+ /// default.+ final bool deleteDetection;++ /// Shortcuts for this terminal. This has higher priority than input handler+ /// of the terminal If not provided, [defaultTerminalShortcuts] will be used.+ final Map<ShortcutActivator, Intent>? shortcuts;++ /// Keyboard event handler of the terminal. This has higher priority than+ /// [shortcuts] and input handler of the terminal.+ final FocusOnKeyEventCallback? onKeyEvent;++ /// True if no input should send to the terminal.+ final bool readOnly;++ /// True if only hardware keyboard events should be used as input. This will+ /// also prevent any on-screen keyboard to be shown.+ final bool hardwareKeyboardOnly;++ /// If true, when the terminal is in alternate buffer (for example running+ /// vim, man, etc), if the application does not declare that it can handle+ /// scrolling, the terminal will simulate scrolling by sending up/down arrow+ /// keys to the application. This is standard behavior for most terminal+ /// emulators. True by default.+ final bool simulateScroll;++ /// See `TerminalScrollGestureHandler.onAltBufferScroll` for why a caller would ever supply this —+ /// a program that owns terminal mouse-tracking but doesn't correctly handle wheel reports needs a+ /// backend-native way to scroll instead of the emulator's own mouse/key simulation.+ final void Function(bool up)? onAltBufferScroll;++ @override+ State<TerminalView> createState() => TerminalViewState();+}++class TerminalViewState extends State<TerminalView> {+ late FocusNode _focusNode;++ late final ShortcutManager _shortcutManager;++ final _customTextEditKey = GlobalKey<CustomTextEditState>();++ final _scrollableKey = GlobalKey<ScrollableState>();++ final _viewportKey = GlobalKey();++ String? _composingText;++ int _composingBacktrackCells = 0;++ late TerminalController _controller;++ late ScrollController _scrollController;++ RenderTerminal get renderTerminal =>+ _viewportKey.currentContext!.findRenderObject() as RenderTerminal;++ @override+ void initState() {+ _focusNode = widget.focusNode ?? FocusNode();+ _controller = widget.controller ?? TerminalController();+ _scrollController = widget.scrollController ?? ScrollController();+ widget.terminal.addListener(_onTerminalChanged);+ _shortcutManager = ShortcutManager(+ shortcuts: widget.shortcuts ?? defaultTerminalShortcuts,+ );+ super.initState();+ }++ @override+ void didUpdateWidget(TerminalView oldWidget) {+ if (!identical(oldWidget.terminal, widget.terminal)) {+ oldWidget.terminal.removeListener(_onTerminalChanged);+ widget.terminal.addListener(_onTerminalChanged);+ // A marked string is owned by the old native input session. TerminalView+ // states are reused while switching agents, so never carry that overlay+ // or editing buffer into the newly selected terminal.+ _composingText = null;+ _composingBacktrackCells = 0;+ final currentTerminal = widget.terminal;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || !identical(widget.terminal, currentTerminal)) return;+ _customTextEditKey.currentState?.resetEditingState();+ });+ }+ if (oldWidget.focusNode != widget.focusNode) {+ if (oldWidget.focusNode == null) {+ _focusNode.dispose();+ }+ _focusNode = widget.focusNode ?? FocusNode();+ }+ if (oldWidget.controller != widget.controller) {+ if (oldWidget.controller == null) {+ _controller.dispose();+ }+ _controller = widget.controller ?? TerminalController();+ }+ if (oldWidget.scrollController != widget.scrollController) {+ if (oldWidget.scrollController == null) {+ _scrollController.dispose();+ }+ _scrollController = widget.scrollController ?? ScrollController();+ }+ _shortcutManager.shortcuts = widget.shortcuts ?? defaultTerminalShortcuts;+ super.didUpdateWidget(oldWidget);+ }++ @override+ void dispose() {+ widget.terminal.removeListener(_onTerminalChanged);+ if (widget.focusNode == null) {+ _focusNode.dispose();+ }+ if (widget.controller == null) {+ _controller.dispose();+ }+ if (widget.scrollController == null) {+ _scrollController.dispose();+ }+ _shortcutManager.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ Widget child = Scrollable(+ key: _scrollableKey,+ controller: _scrollController,+ viewportBuilder: (context, offset) {+ return _TerminalView(+ key: _viewportKey,+ terminal: widget.terminal,+ controller: _controller,+ offset: offset,+ padding: MediaQuery.of(context).padding,+ autoResize: widget.autoResize,+ resizeBuffer: widget.resizeBuffer,+ renderingEnabled: widget.renderingEnabled,+ textStyle: widget.textStyle,+ textScaler: widget.textScaler ?? MediaQuery.textScalerOf(context),+ theme: widget.theme,+ focusNode: _focusNode,+ cursorType: widget.cursorType,+ alwaysShowCursor: widget.alwaysShowCursor,+ onEditableRect: _onEditableRect,+ composingText: _composingText,+ composingBacktrackCells: _composingBacktrackCells,+ );+ },+ );++ child = TerminalScrollGestureHandler(+ terminal: widget.terminal,+ simulateScroll: widget.simulateScroll,+ onAltBufferScroll: widget.onAltBufferScroll,+ getCellOffset: (offset) => renderTerminal.getCellOffset(offset),+ getLineHeight: () => renderTerminal.lineHeight,+ child: child,+ );++ if (!widget.hardwareKeyboardOnly) {+ child = CustomTextEdit(+ key: _customTextEditKey,+ focusNode: _focusNode,+ autofocus: widget.autofocus,+ inputType: widget.keyboardType,+ keyboardAppearance: widget.keyboardAppearance,+ deleteDetection: widget.deleteDetection,+ onInsert: _onInsert,+ onDelete: (count) {+ _scrollToBottom();+ for (var index = 0; index < count; index++) {+ widget.terminal.keyInput(TerminalKey.backspace);+ }+ },+ onComposing: _onComposing,+ onAction: (action) {+ _scrollToBottom();+ if (action == TextInputAction.done ||+ action == TextInputAction.newline) {+ widget.terminal.keyInput(TerminalKey.enter);+ _customTextEditKey.currentState?.resetEditingState();+ }+ },+ onKeyEvent: _handleKeyEvent,+ readOnly: widget.readOnly,+ child: child,+ );+ } else if (!widget.readOnly) {+ // Only listen for key input from a hardware keyboard.+ child = CustomKeyboardListener(+ child: child,+ focusNode: _focusNode,+ autofocus: widget.autofocus,+ onInsert: _onInsert,+ onComposing: (text) => _onComposing(text, 0),+ onKeyEvent: _handleKeyEvent,+ );+ }++ child = TerminalActions(+ terminal: widget.terminal,+ controller: _controller,+ child: child,+ );++ child = KeyboardVisibilty(+ onKeyboardShow: _onKeyboardShow,+ child: child,+ );++ child = TerminalGestureHandler(+ terminalView: this,+ terminalController: _controller,+ onTapUp: _onTapUp,+ onTapDown: _onTapDown,+ onSecondaryTapDown:+ widget.onSecondaryTapDown != null ? _onSecondaryTapDown : null,+ onSecondaryTapUp:+ widget.onSecondaryTapUp != null ? _onSecondaryTapUp : null,+ readOnly: widget.readOnly,+ child: child,+ );++ child = MouseRegion(+ cursor: widget.mouseCursor,+ child: child,+ );++ child = Container(+ color: widget.theme.background.withOpacity(widget.backgroundOpacity),+ padding: widget.padding,+ child: child,+ );++ return child;+ }++ void requestKeyboard() {+ _customTextEditKey.currentState?.requestKeyboard();+ }++ void closeKeyboard() {+ _customTextEditKey.currentState?.closeKeyboard();+ }++ Rect get cursorRect {+ return renderTerminal.cursorOffset & renderTerminal.cellSize;+ }++ Rect get globalCursorRect {+ return renderTerminal.localToGlobal(renderTerminal.cursorOffset) &+ renderTerminal.cellSize;+ }++ void _onTapUp(TapUpDetails details) {+ final offset = renderTerminal.getCellOffset(+ renderTerminal.globalToLocal(details.globalPosition),+ );+ widget.onTapUp?.call(details, offset);+ }++ bool _onTapDown(TapDownDetails details) {+ final offset = renderTerminal.getCellOffset(+ renderTerminal.globalToLocal(details.globalPosition),+ );+ if (widget.onTapDown?.call(details, offset) ?? false) return true;+ if (_controller.selection != null) {+ _controller.clearSelection();+ } else {+ if (!widget.hardwareKeyboardOnly) {+ _customTextEditKey.currentState?.requestKeyboard();+ } else {+ _focusNode.requestFocus();+ }+ }+ return false;+ }++ void _onSecondaryTapDown(TapDownDetails details) {+ final offset = renderTerminal.getCellOffset(details.localPosition);+ widget.onSecondaryTapDown?.call(details, offset);+ }++ void _onSecondaryTapUp(TapUpDetails details) {+ final offset = renderTerminal.getCellOffset(details.localPosition);+ widget.onSecondaryTapUp?.call(details, offset);+ }++ bool get hasInputConnection {+ return _customTextEditKey.currentState?.hasInputConnection == true;+ }++ void _onInsert(String text) {+ if (text.isEmpty) return;++ final key = charToTerminalKey(text.trim());++ // On mobile platforms there is no guarantee that virtual keyboard will+ // generate hardware key events. So we need first try to send the key+ // as a hardware key event. If it fails, then we send it as a text input.+ final consumed = key == null ? false : widget.terminal.keyInput(key);++ if (!consumed) {+ widget.terminal.textInput(text);+ }++ _scrollToBottom();+ }++ void _onComposing(String? text, int backtrackCells) {+ if (text != null && _terminalAlreadyEchoes(text)) {+ text = null;+ backtrackCells = 0;+ }+ if (!mounted ||+ (_composingText == text &&+ _composingBacktrackCells == backtrackCells)) {+ return;+ }+ setState(() {+ _composingText = text;+ _composingBacktrackCells = backtrackCells;+ });+ }++ /// The native macOS input client keeps a marked range while a remote TUI+ /// has already echoed the exact same characters. Keeping our own preview in+ /// that case duplicates the cells and makes them look underlined/stale until+ /// the next keyframe. A real CJK pre-edit has not reached the PTY yet, so it+ /// does not match the cells before the cursor and remains visible.+ bool _terminalAlreadyEchoes(String text) {+ if (text.isEmpty) return false;+ final buffer = widget.terminal.buffer;+ if (buffer.cursorX <= 0) return false;+ return buffer.currentLine.getText(0, buffer.cursorX).endsWith(text);+ }++ void _onTerminalChanged() {+ final text = _composingText;+ if (!mounted || text == null || !_terminalAlreadyEchoes(text)) return;+ setState(() {+ _composingText = null;+ _composingBacktrackCells = 0;+ });+ }++ @visibleForTesting+ String? get debugComposingText => _composingText;++ /// Live input-client composition, independent of its visual preview (which+ /// may already match echoed terminal cells). Workspace shortcuts must let+ /// the IME finish its marked text before claiming a key.+ bool get isComposing {+ final range =+ _customTextEditKey.currentState?.currentTextEditingValue?.composing;+ return range != null && range.isValid && !range.isCollapsed;+ }++ KeyEventResult _handleKeyEvent(FocusNode focusNode, KeyEvent event) {+ final resultOverride = widget.onKeyEvent?.call(focusNode, event);+ if (resultOverride != null && resultOverride != KeyEventResult.ignored) {+ return resultOverride;+ }++ // ignore: invalid_use_of_protected_member+ final shortcutResult = _shortcutManager.handleKeypress(+ focusNode.context!,+ event,+ );++ if (shortcutResult != KeyEventResult.ignored) {+ return shortcutResult;+ }++ if (event is KeyUpEvent) {+ return KeyEventResult.ignored;+ }++ final key = keyToTerminalKey(event.logicalKey);+ final reservesTerminalKey = HardwareKeyboard.instance.isControlPressed ||+ HardwareKeyboard.instance.isMetaPressed;++ // Let the native text input client process Backspace while editable. Some+ // IMEs emit it internally to replace an earlier committed letter (Telex+ // does this for transformations such as `u` to `ư`).+ //+ // ONLY WHERE THE EMBEDDER HOLDS UP ITS END. This hands the key to the+ // platform and sends nothing, which is a bargain only Apple's embedder+ // keeps: AppKit turns Backspace into `deleteBackward:` and ships the+ // selector to Dart over `TextInputClient.performSelectors`, which+ // CustomTextEdit answers (see its performSelector). The GTK embedder has+ // no performSelectors channel method at all, and its key handler names+ // GDK_KEY_BackSpace explicitly to do NOTHING with it — "already handled+ // inside the framework in RenderEditable", which is true of an+ // EditableText and false of the bare TextInputClient below. So on Linux+ // the key was dropped here, dropped again by the engine, and no byte ever+ // reached the pty: everything typed except Backspace.+ //+ // Everywhere else the key falls through to keyInput() at the bottom, where+ // the keytab turns it into ^? (\x7f). Composition is not at risk either+ // way — while an IME is composing, CustomTextEdit._onKeyEvent never calls+ // this method.+ final nativeClientOwnsBackspace =+ defaultTargetPlatform == TargetPlatform.macOS ||+ defaultTargetPlatform == TargetPlatform.iOS;+ if (key == TerminalKey.backspace &&+ nativeClientOwnsBackspace &&+ !widget.hardwareKeyboardOnly &&+ !reservesTerminalKey) {+ return KeyEventResult.skipRemainingHandlers;+ }++ // On macOS a physical key arrives before the platform text-input client+ // reports its composing value. Forwarding printable keys here therefore+ // leaks IME pre-edit input (for example `ni`) to the PTY before the final+ // committed text (`に`) arrives. Let TextInputClient own all text without+ // Control/Command; it will call _onInsert exactly once on commit.+ final isTextInput = _isPrintableText(event.character);+ if (isTextInput && !reservesTerminalKey) {+ // Do not let another Flutter shortcut consume this before macOS gets a+ // chance to update the native text-input client.+ return KeyEventResult.skipRemainingHandlers;+ }++ if (key == null) {+ return KeyEventResult.ignored;+ }++ // ⌘ IS THE APP'S MODIFIER, NEVER THE TERMINAL'S. No terminal emulator sends+ // a Command chord to the pty — Terminal.app and iTerm both reserve it for+ // themselves — but this fell through to keyInput() below, which is not even+ // given `meta`, so ⌘] arrived as a bare bracketRight: it typed "]" into the+ // shell AND returned handled, which stopped the chord from ever reaching+ // the app's own Shortcuts above. That is one bug wearing two faces, and it+ // ate every app shortcut whose base key has a terminal mapping — moving+ // between panes, closing one, opening an agent, reloading.+ //+ // Returning `ignored` (not skipRemainingHandlers) is the point: the event+ // keeps travelling UP the focus chain to those Shortcuts. xterm's own+ // ⌘C/⌘V/⌘A are matched earlier, by the shortcut map, so they still work.+ //+ // Not gated on Apple: ⌘ is this app's modifier on every desktop it runs on+ // (app_shortcuts.dart declares every one of them `meta: true`, which is+ // the Super key on Linux). Gating it there meant a focused terminal on+ // Linux swallowed Super+key — typing the bare letter into the shell — and+ // the app's own Shortcuts never saw a single chord.+ if (HardwareKeyboard.instance.isMetaPressed) {+ return KeyEventResult.ignored;+ }++ // ⌃⇥ IS THE APP'S, EVERYWHERE. Ctrl generally belongs to the terminal — it+ // is how a shell gets ^C, ^D, ^Z — so this is a single named exception+ // rather than a rule about Ctrl: no shell or tmux binding uses Ctrl+Tab,+ // and it is the chord every tabbed app moves between views with, so the+ // hand reaches for it here too. Without this the terminal answered it and+ // the app's Shortcuts never saw the key.+ if (key == TerminalKey.tab && HardwareKeyboard.instance.isControlPressed) {+ return KeyEventResult.ignored;+ }++ final handled = widget.terminal.keyInput(+ key,+ ctrl: HardwareKeyboard.instance.isControlPressed,+ alt: HardwareKeyboard.instance.isAltPressed,+ shift: HardwareKeyboard.instance.isShiftPressed,+ );++ if (handled) {+ _scrollToBottom();+ if (key == TerminalKey.enter) {+ _customTextEditKey.currentState?.resetEditingState();+ }+ }++ return handled ? KeyEventResult.handled : KeyEventResult.ignored;+ }++ bool _isPrintableText(String? text) {+ if (text == null || text.isEmpty) return false;++ // Backspace, Enter, Tab, Escape, Delete and macOS function/navigation+ // keys can all carry a `character` value. They remain terminal controls;+ // only actual printable text is deferred to the native IME.+ return text.runes.every(+ (rune) =>+ rune >= 0x20 && rune != 0x7f && (rune < 0xf700 || rune > 0xf8ff),+ );+ }++ void _onKeyboardShow() {+ if (_focusNode.hasFocus) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ _scrollToBottom();+ });+ }+ }++ void _onEditableRect(Rect rect, Rect caretRect) {+ _customTextEditKey.currentState?.setEditableRect(rect, caretRect);+ }++ /// Show the latest output when the current buffer and viewport are laid out.+ void scrollToBottom() {+ // A resize can land between ticks of a fling or driven scroll. Cancelling+ // that activity is part of returning to live output; otherwise its next+ // tick overwrites the freshly aligned offset with an old history position.+ final position = _scrollableKey.currentState?.position;+ if (position is ScrollPositionWithSingleContext) position.goIdle();+ renderTerminal.scrollToBottom();+ }++ void _scrollToBottom() => scrollToBottom();+}++class _TerminalView extends LeafRenderObjectWidget {+ const _TerminalView({+ super.key,+ required this.terminal,+ required this.controller,+ required this.offset,+ required this.padding,+ required this.autoResize,+ required this.resizeBuffer,+ required this.renderingEnabled,+ required this.textStyle,+ required this.textScaler,+ required this.theme,+ required this.focusNode,+ required this.cursorType,+ required this.alwaysShowCursor,+ this.onEditableRect,+ this.composingText,+ this.composingBacktrackCells = 0,+ });++ final Terminal terminal;++ final TerminalController controller;++ final ViewportOffset offset;++ final EdgeInsets padding;++ final bool autoResize;++ final bool resizeBuffer;++ final bool renderingEnabled;++ final TerminalStyle textStyle;++ final TextScaler textScaler;++ final TerminalTheme theme;++ final FocusNode focusNode;++ final TerminalCursorType cursorType;++ final bool alwaysShowCursor;++ final EditableRectCallback? onEditableRect;++ final String? composingText;++ final int composingBacktrackCells;++ @override+ RenderTerminal createRenderObject(BuildContext context) {+ return RenderTerminal(+ terminal: terminal,+ controller: controller,+ offset: offset,+ padding: padding,+ autoResize: autoResize,+ resizeBuffer: resizeBuffer,+ renderingEnabled:+ renderingEnabled && TickerMode.valuesOf(context).enabled,+ textStyle: textStyle,+ textScaler: textScaler,+ theme: theme,+ focusNode: focusNode,+ cursorType: cursorType,+ alwaysShowCursor: alwaysShowCursor,+ onEditableRect: onEditableRect,+ composingText: composingText,+ composingBacktrackCells: composingBacktrackCells,+ );+ }++ @override+ void updateRenderObject(BuildContext context, RenderTerminal renderObject) {+ renderObject+ ..renderingEnabled =+ renderingEnabled && TickerMode.valuesOf(context).enabled+ ..terminal = terminal+ ..controller = controller+ ..offset = offset+ ..padding = padding+ ..autoResize = autoResize+ ..resizeBuffer = resizeBuffer+ ..textStyle = textStyle+ ..textScaler = textScaler+ ..theme = theme+ ..focusNode = focusNode+ ..cursorType = cursorType+ ..alwaysShowCursor = alwaysShowCursor+ ..onEditableRect = onEditableRect+ ..composingText = composingText+ ..composingBacktrackCells = composingBacktrackCells;+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/char_metrics.dart b/mobile/third_party/xterm/lib/src/ui/char_metrics.dartnew file mode 100644index 000000000..e35439d47--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/char_metrics.dart@@ -0,0 +1,21 @@+import 'dart:ui';++import 'package:flutter/painting.dart';+import 'package:xterm/src/ui/terminal_text_style.dart';++Size calcCharSize(TerminalStyle style, TextScaler textScaler) {+ const test = 'mmmmmmmmmm';++ final textStyle = style.toTextStyle();+ final builder = ParagraphBuilder(textStyle.getParagraphStyle());+ builder.pushStyle(textStyle.getTextStyle(textScaler: textScaler));+ builder.addText(test);++ final paragraph = builder.build();+ paragraph.layout(ParagraphConstraints(width: double.infinity));++ return Size(+ paragraph.maxIntrinsicWidth / test.length,+ paragraph.height,+ );+}diff --git a/mobile/third_party/xterm/lib/src/ui/controller.dart b/mobile/third_party/xterm/lib/src/ui/controller.dartnew file mode 100644index 000000000..1e107c2de--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/controller.dart@@ -0,0 +1,174 @@+import 'package:flutter/material.dart';+import 'package:meta/meta.dart';+import 'package:xterm/src/base/disposable.dart';+import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/buffer/line.dart';+import 'package:xterm/src/core/buffer/range.dart';+import 'package:xterm/src/core/buffer/range_block.dart';+import 'package:xterm/src/core/buffer/range_line.dart';+import 'package:xterm/src/ui/pointer_input.dart';+import 'package:xterm/src/ui/selection_mode.dart';++class TerminalController with ChangeNotifier {+ TerminalController({+ SelectionMode selectionMode = SelectionMode.line,+ PointerInputs pointerInputs = const PointerInputs({PointerInput.tap}),+ bool suspendPointerInput = false,+ }) : _selectionMode = selectionMode,+ _pointerInputs = pointerInputs,+ _suspendPointerInputs = suspendPointerInput;++ CellAnchor? _selectionBase;+ CellAnchor? _selectionExtent;++ SelectionMode get selectionMode => _selectionMode;+ SelectionMode _selectionMode;++ /// The set of pointer events which will be used as mouse input for the terminal.+ PointerInputs get pointerInput => _pointerInputs;+ PointerInputs _pointerInputs;++ /// True if sending pointer events to the terminal is suspended.+ bool get suspendedPointerInputs => _suspendPointerInputs;+ bool _suspendPointerInputs;++ List<TerminalHighlight> get highlights => _highlights;+ final _highlights = <TerminalHighlight>[];++ BufferRange? get selection {+ final base = _selectionBase;+ final extent = _selectionExtent;++ if (base == null || extent == null) {+ return null;+ }++ if (!base.attached || !extent.attached) {+ return null;+ }++ return _createRange(base.offset, extent.offset);+ }++ /// Set selection on the terminal from [base] to [extent]. This method takes+ /// the ownership of [base] and [extent] and will dispose them when the+ /// selection is cleared or changed.+ void setSelection(CellAnchor base, CellAnchor extent, {SelectionMode? mode}) {+ _selectionBase?.dispose();+ _selectionBase = base;++ _selectionExtent?.dispose();+ _selectionExtent = extent;++ if (mode != null) {+ _selectionMode = mode;+ }++ notifyListeners();+ }++ BufferRange _createRange(CellOffset begin, CellOffset end) {+ switch (selectionMode) {+ case SelectionMode.line:+ return BufferRangeLine(begin, end);+ case SelectionMode.block:+ return BufferRangeBlock(begin, end);+ }+ }++ /// Controls how the terminal behaves when the user selects a range of text.+ /// The default is [SelectionMode.line]. Setting this to [SelectionMode.block]+ /// enables block selection mode.+ void setSelectionMode(SelectionMode newSelectionMode) {+ // If the new mode is the same as the old mode,+ // nothing has to be changed.+ if (_selectionMode == newSelectionMode) {+ return;+ }+ // Set the new mode.+ _selectionMode = newSelectionMode;+ notifyListeners();+ }++ /// Clears the current selection.+ void clearSelection() {+ _selectionBase?.dispose();+ _selectionBase = null;+ _selectionExtent?.dispose();+ _selectionExtent = null;+ notifyListeners();+ }++ // Select which type of pointer events are send to the terminal.+ void setPointerInputs(PointerInputs pointerInput) {+ _pointerInputs = pointerInput;+ notifyListeners();+ }++ // Toggle sending pointer events to the terminal.+ void setSuspendPointerInput(bool suspend) {+ _suspendPointerInputs = suspend;+ notifyListeners();+ }++ // Returns true if this type of PointerInput should be send to the Terminal.+ @internal+ bool shouldSendPointerInput(PointerInput pointerInput) {+ // Always return false if pointer input is suspended.+ return _suspendPointerInputs+ ? false+ : _pointerInputs.inputs.contains(pointerInput);+ }++ /// Creates a new highlight on the terminal from [p1] to [p2] with the given+ /// [color]. The highlight will be removed when the returned object is+ /// disposed.+ TerminalHighlight highlight({+ required CellAnchor p1,+ required CellAnchor p2,+ required Color color,+ }) {+ final highlight = TerminalHighlight(+ this,+ p1: p1,+ p2: p2,+ color: color,+ );++ _highlights.add(highlight);+ notifyListeners();++ highlight.registerCallback(() {+ _highlights.remove(highlight);+ notifyListeners();+ });++ return highlight;+ }+}++class TerminalHighlight with Disposable {+ final TerminalController owner;++ final CellAnchor p1;++ final CellAnchor p2;++ final Color color;++ TerminalHighlight(+ this.owner, {+ required this.p1,+ required this.p2,+ required this.color,+ });++ /// Returns the range of the highlight. May be null if the anchors that+ /// define the highlight are not attached to the terminal.+ BufferRange? get range {+ if (!p1.attached || !p2.attached) {+ return null;+ }+ return BufferRangeLine(p1.offset, p2.offset);+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/cursor_type.dart b/mobile/third_party/xterm/lib/src/ui/cursor_type.dartnew file mode 100644index 000000000..0af0a58d6--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/cursor_type.dart@@ -0,0 +1,7 @@+enum TerminalCursorType {+ block,++ underline,++ verticalBar,+}diff --git a/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dart b/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dartnew file mode 100644index 000000000..858617ce3--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dart@@ -0,0 +1,463 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:xterm/src/utils/unicode_v11.dart';++class CustomTextEdit extends StatefulWidget {+ CustomTextEdit({+ super.key,+ required this.child,+ required this.onInsert,+ required this.onDelete,+ required this.onComposing,+ required this.onAction,+ required this.onKeyEvent,+ required this.focusNode,+ this.autofocus = false,+ this.readOnly = false,+ // this.initEditingState = TextEditingValue.empty,+ this.inputType = TextInputType.text,+ this.inputAction = TextInputAction.newline,+ this.keyboardAppearance = Brightness.light,+ this.deleteDetection = false,+ });++ final Widget child;++ final void Function(String) onInsert;++ final void Function(int count) onDelete;++ final void Function(String? text, int backtrackCells) onComposing;++ final void Function(TextInputAction) onAction;++ final KeyEventResult Function(FocusNode, KeyEvent) onKeyEvent;++ final FocusNode focusNode;++ final bool autofocus;++ final bool readOnly;++ final TextInputType inputType;++ final TextInputAction inputAction;++ final Brightness keyboardAppearance;++ final bool deleteDetection;++ @override+ CustomTextEditState createState() => CustomTextEditState();+}++class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {+ TextInputConnection? _connection;++ @override+ void initState() {+ widget.focusNode.addListener(_onFocusChange);+ super.initState();+ }++ @override+ void didUpdateWidget(CustomTextEdit oldWidget) {+ super.didUpdateWidget(oldWidget);++ if (widget.focusNode != oldWidget.focusNode) {+ oldWidget.focusNode.removeListener(_onFocusChange);+ widget.focusNode.addListener(_onFocusChange);+ }++ if (!_shouldCreateInputConnection) {+ _closeInputConnectionIfNeeded();+ } else {+ if (oldWidget.readOnly && widget.focusNode.hasFocus) {+ _openInputConnection();+ }+ }+ }++ @override+ void dispose() {+ widget.focusNode.removeListener(_onFocusChange);+ _closeInputConnectionIfNeeded();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ return Focus(+ focusNode: widget.focusNode,+ autofocus: widget.autofocus,+ onKeyEvent: _onKeyEvent,+ child: widget.child,+ );+ }++ bool get hasInputConnection => _connection != null && _connection!.attached;++ void requestKeyboard() {+ if (widget.focusNode.hasFocus) {+ _openInputConnection();+ } else {+ widget.focusNode.requestFocus();+ }+ }++ void closeKeyboard() {+ if (hasInputConnection) {+ _connection?.close();+ }+ }++ void setEditingState(TextEditingValue value) {+ _cancelPendingDeletes();+ _currentEditingState = value;+ _terminalText = value.text;+ _connection?.setEditingState(value);+ }++ /// Clears the native input buffer after the terminal accepts a command.+ /// It intentionally stays intact between ordinary key presses: Vietnamese+ /// Telex needs the preceding `u` available to convert it into `ư`.+ void resetEditingState() {+ _cancelPendingDeletes();+ _currentEditingState = _initEditingState.copyWith();+ _terminalText = _currentEditingState.text;+ widget.onComposing(null, 0);+ _connection?.setEditingState(_currentEditingState);+ }++ void setEditableRect(Rect rect, Rect caretRect) {+ if (!hasInputConnection) {+ return;+ }++ _connection?.setEditableSizeAndTransform(+ rect.size,+ Matrix4.translationValues(0, 0, 0),+ );++ _connection?.setCaretRect(caretRect);+ }++ void _onFocusChange() {+ _openOrCloseInputConnectionIfNeeded();+ }++ KeyEventResult _onKeyEvent(FocusNode focusNode, KeyEvent event) {+ if (_currentEditingState.composing.isCollapsed) {+ return widget.onKeyEvent(focusNode, event);+ }++ return KeyEventResult.skipRemainingHandlers;+ }++ void _openOrCloseInputConnectionIfNeeded() {+ if (widget.focusNode.hasFocus && widget.focusNode.consumeKeyboardToken()) {+ _openInputConnection();+ } else if (!widget.focusNode.hasFocus) {+ _closeInputConnectionIfNeeded();+ }+ }++ bool get _shouldCreateInputConnection => kIsWeb || !widget.readOnly;++ void _openInputConnection() {+ if (!_shouldCreateInputConnection) {+ return;+ }++ if (hasInputConnection) {+ _connection!.show();+ } else {+ final config = TextInputConfiguration(+ inputType: widget.inputType,+ inputAction: widget.inputAction,+ keyboardAppearance: widget.keyboardAppearance,+ autocorrect: false,+ enableSuggestions: false,+ enableIMEPersonalizedLearning: false,+ );++ _connection = TextInput.attach(this, config);++ _connection!.show();++ // setEditableRect(Rect.zero, Rect.zero);++ _connection!.setEditingState(_initEditingState);+ }+ }++ void _closeInputConnectionIfNeeded() {+ if (_connection != null && _connection!.attached) {+ _connection!.close();+ _connection = null;+ }++ // An IME can still have a pre-edit string while focus moves to another+ // terminal. That text belongs to the old native input connection and must+ // never remain painted (or be committed) in the newly focused terminal.+ resetEditingState();+ }++ TextEditingValue get _initEditingState => widget.deleteDetection+ ? const TextEditingValue(+ text: ' ',+ selection: TextSelection.collapsed(offset: 2),+ )+ : const TextEditingValue(+ text: '',+ selection: TextSelection.collapsed(offset: 0),+ );++ late var _currentEditingState = _initEditingState.copyWith();++ /// Text that has already been mirrored to the PTY. This deliberately stays+ /// separate from [_currentEditingState], whose composing range can contain+ /// marked text that must not reach the terminal before the IME commits it.+ late String _terminalText = _initEditingState.text;++ int _pendingDeleteSelectors = 0;+ Timer? _deleteSelectorTimer;++ @override+ TextEditingValue? get currentTextEditingValue {+ return _currentEditingState;+ }++ @override+ AutofillScope? get currentAutofillScope {+ return null;+ }++ @override+ void updateEditingValue(TextEditingValue value) {+ _applyEditingValue(+ value,+ hasTextMutation: value.text != _currentEditingState.text,+ );+ }++ void _applyEditingValue(+ TextEditingValue value, {+ required bool hasTextMutation,+ }) {+ final wasComposing = !_currentEditingState.composing.isCollapsed;+ _currentEditingState = value;+ final isComposing = !_currentEditingState.composing.isCollapsed;++ if (hasTextMutation || wasComposing || isComposing) {+ // A text delta is authoritative. Any delete selector queued during the+ // same native input transaction is part of that replacement/composition+ // and must not be forwarded to the PTY a second time.+ _cancelPendingDeletes();+ }++ if (isComposing) {+ final text = _currentEditingState.text;+ final composingText = _currentEditingState.composing.textInside(text);++ // macOS can keep the whole editable buffer marked even after that exact+ // value has already been mirrored to the PTY. Painting it again leaves+ // a stale IME overlay (previously visible as an underline) until the+ // terminal is rebuilt. Only preview text that is genuinely ahead of the+ // terminal state; CJK/Japanese pre-edit text still takes this path.+ if (text == _terminalText) {+ widget.onComposing(null, 0);+ return;+ }++ widget.onComposing(+ composingText,+ _composingBacktrackCells(_currentEditingState.composing.start),+ );+ return;+ }++ widget.onComposing(null, 0);++ if (hasTextMutation || wasComposing || value.text != _terminalText) {+ _syncTerminalText(value.text);+ }+ }++ void _syncTerminalText(String value) {+ final edit = _TextEdit.between(_terminalText, value);+ if (edit.removed.isNotEmpty) {+ widget.onDelete(edit.removed.runes.length);+ }+ if (edit.inserted.isNotEmpty) {+ widget.onInsert(edit.inserted);+ }+ _terminalText = value;+ }++ int _composingBacktrackCells(int composingStart) {+ if (composingStart < 0 || composingStart >= _terminalText.length) return 0;++ var width = 0;+ for (final rune in _terminalText.substring(composingStart).runes) {+ final runeWidth = unicodeV11.wcwidth(rune);+ if (runeWidth > 0) width += runeWidth;+ }+ return width;+ }++ @override+ void performAction(TextInputAction action) {+ // print('performAction $action');+ widget.onAction(action);+ }++ @override+ void performSelector(String selectorName) {+ if (!selectorName.startsWith('deleteBackward')) return;++ // A marked string belongs entirely to the IME. It will send a fresh+ // editing value after changing the pre-edit text, so nothing reaches the+ // terminal yet.+ if (!_currentEditingState.composing.isCollapsed) return;++ _pendingDeleteSelectors++;+ _deleteSelectorTimer ??= Timer(+ Duration.zero,+ _flushPendingDeleteSelectors,+ );+ }++ void _flushPendingDeleteSelectors() {+ _deleteSelectorTimer = null;+ final count = _pendingDeleteSelectors;+ _pendingDeleteSelectors = 0;++ if (count == 0 || !_currentEditingState.composing.isCollapsed) return;++ for (var index = 0; index < count; index++) {+ _applyNativeBackspace();+ }+ }++ void _applyNativeBackspace() {+ final value = _currentEditingState;+ final selection = value.selection.isValid+ ? value.selection+ : TextSelection.collapsed(offset: value.text.length);+ final end = selection.end;+ final start = selection.isCollapsed+ ? _previousCodePointBoundary(value.text, end)+ : selection.start;++ if (start < end) {+ final next = value.copyWith(+ text: value.text.replaceRange(start, end, ''),+ selection: TextSelection.collapsed(offset: start),+ composing: TextRange.empty,+ );+ _currentEditingState = next;+ _connection?.setEditingState(next);+ _syncTerminalText(next.text);+ return;+ }++ // The native buffer can be empty at a shell prompt, but Backspace still+ // has meaning to the remote terminal.+ widget.onDelete(1);+ }++ void _cancelPendingDeletes() {+ _pendingDeleteSelectors = 0;+ _deleteSelectorTimer?.cancel();+ _deleteSelectorTimer = null;+ }++ int _previousCodePointBoundary(String text, int offset) {+ if (offset <= 0) return 0;+ final previous = text.codeUnitAt(offset - 1);+ if (previous >= 0xdc00 &&+ previous <= 0xdfff &&+ offset >= 2 &&+ text.codeUnitAt(offset - 2) >= 0xd800 &&+ text.codeUnitAt(offset - 2) <= 0xdbff) {+ return offset - 2;+ }+ return offset - 1;+ }++ @override+ void updateFloatingCursor(RawFloatingCursorPoint point) {+ // print('updateFloatingCursor $point');+ }++ @override+ void didChangeInputControl(+ TextInputControl? oldControl,+ TextInputControl? newControl,+ ) {}++ @override+ void insertContent(KeyboardInsertedContent content) {}++ @override+ bool onFocusReceived() => false;++ @override+ void showAutocorrectionPromptRect(int start, int end) {+ // print('showAutocorrectionPromptRect');+ }++ @override+ void connectionClosed() {+ // print('connectionClosed');+ }++ @override+ void performPrivateCommand(String action, Map<String, dynamic> data) {+ // print('performPrivateCommand $action');+ }++ @override+ void insertTextPlaceholder(Size size) {+ // print('insertTextPlaceholder');+ }++ @override+ void removeTextPlaceholder() {+ // print('removeTextPlaceholder');+ }++ @override+ void showToolbar() {+ // print('showToolbar');+ }+}++class _TextEdit {+ const _TextEdit({required this.removed, required this.inserted});++ factory _TextEdit.between(String before, String after) {+ var prefix = 0;+ final sharedLength =+ before.length < after.length ? before.length : after.length;+ while (prefix < sharedLength &&+ before.codeUnitAt(prefix) == after.codeUnitAt(prefix)) {+ prefix++;+ }++ return _TextEdit(+ // A PTY terminal edits at the current cursor; it cannot preserve a+ // common suffix while replacing an earlier character. Rewind the whole+ // suffix from the first difference, then replay the desired suffix.+ removed: before.substring(prefix),+ inserted: after.substring(prefix),+ );+ }++ final String removed;+ final String inserted;+}diff --git a/mobile/third_party/xterm/lib/src/ui/gesture/gesture_detector.dart b/mobile/third_party/xterm/lib/src/ui/gesture/gesture_detector.dartnew file mode 100644index 000000000..c29e50b00--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/gesture/gesture_detector.dart@@ -0,0 +1,162 @@+import 'dart:async';++import 'package:flutter/gestures.dart';+import 'package:flutter/widgets.dart';++class TerminalGestureDetector extends StatefulWidget {+ const TerminalGestureDetector({+ super.key,+ this.child,+ this.onSingleTapUp,+ this.onTapUp,+ this.onTapDown,+ this.onSecondaryTapDown,+ this.onSecondaryTapUp,+ this.onTertiaryTapDown,+ this.onTertiaryTapUp,+ this.onLongPressStart,+ this.onLongPressMoveUpdate,+ this.onLongPressUp,+ this.onDragStart,+ this.onDragUpdate,+ this.onDoubleTapDown,+ });++ final Widget? child;++ final GestureTapUpCallback? onTapUp;++ final GestureTapUpCallback? onSingleTapUp;++ final GestureTapDownCallback? onTapDown;++ final GestureTapDownCallback? onSecondaryTapDown;++ final GestureTapUpCallback? onSecondaryTapUp;++ final GestureTapDownCallback? onDoubleTapDown;++ final GestureTapDownCallback? onTertiaryTapDown;++ final GestureTapUpCallback? onTertiaryTapUp;++ final GestureLongPressStartCallback? onLongPressStart;++ final GestureLongPressMoveUpdateCallback? onLongPressMoveUpdate;++ final GestureLongPressUpCallback? onLongPressUp;++ final GestureDragStartCallback? onDragStart;++ final GestureDragUpdateCallback? onDragUpdate;++ @override+ State<TerminalGestureDetector> createState() =>+ _TerminalGestureDetectorState();+}++class _TerminalGestureDetectorState extends State<TerminalGestureDetector> {+ Timer? _doubleTapTimer;++ Offset? _lastTapOffset;++ // True if a second tap down of a double tap is detected. Used to discard+ // subsequent tap up / tap hold of the same tap.+ bool _isDoubleTap = false;++ // The down handler is force-run on success of a single tap and optimistically+ // run before a long press success.+ void _handleTapDown(TapDownDetails details) {+ widget.onTapDown?.call(details);++ if (_doubleTapTimer != null &&+ _isWithinDoubleTapTolerance(details.globalPosition)) {+ // If there was already a previous tap, the second down hold/tap is a+ // double tap down.+ widget.onDoubleTapDown?.call(details);++ _doubleTapTimer!.cancel();+ _doubleTapTimeout();+ _isDoubleTap = true;+ }+ }++ void _handleTapUp(TapUpDetails details) {+ if (!_isDoubleTap) {+ widget.onSingleTapUp?.call(details);+ _lastTapOffset = details.globalPosition;+ _doubleTapTimer = Timer(kDoubleTapTimeout, _doubleTapTimeout);+ }+ _isDoubleTap = false;+ }++ void _doubleTapTimeout() {+ _doubleTapTimer = null;+ _lastTapOffset = null;+ }++ bool _isWithinDoubleTapTolerance(Offset secondTapOffset) {+ if (_lastTapOffset == null) {+ return false;+ }++ final Offset difference = secondTapOffset - _lastTapOffset!;+ return difference.distance <= kDoubleTapSlop;+ }++ @override+ Widget build(BuildContext context) {+ final gestures = <Type, GestureRecognizerFactory>{};++ gestures[TapGestureRecognizer] =+ GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(+ () => TapGestureRecognizer(debugOwner: this),+ (TapGestureRecognizer instance) {+ instance+ ..onTapDown = _handleTapDown+ ..onTapUp = _handleTapUp+ ..onSecondaryTapDown = widget.onSecondaryTapDown+ ..onSecondaryTapUp = widget.onSecondaryTapUp+ ..onTertiaryTapDown = widget.onTertiaryTapDown+ ..onTertiaryTapUp = widget.onTertiaryTapUp;+ },+ );++ gestures[LongPressGestureRecognizer] =+ GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(+ () => LongPressGestureRecognizer(+ debugOwner: this,+ supportedDevices: {+ PointerDeviceKind.touch,+ // PointerDeviceKind.mouse, // for debugging purposes only+ },+ ),+ (LongPressGestureRecognizer instance) {+ instance+ ..onLongPressStart = widget.onLongPressStart+ ..onLongPressMoveUpdate = widget.onLongPressMoveUpdate+ ..onLongPressUp = widget.onLongPressUp;+ },+ );++ gestures[PanGestureRecognizer] =+ GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(+ () => PanGestureRecognizer(+ debugOwner: this,+ supportedDevices: <PointerDeviceKind>{PointerDeviceKind.mouse},+ ),+ (PanGestureRecognizer instance) {+ instance+ ..dragStartBehavior = DragStartBehavior.down+ ..onStart = widget.onDragStart+ ..onUpdate = widget.onDragUpdate;+ },+ );++ return RawGestureDetector(+ gestures: gestures,+ excludeFromSemantics: true,+ child: widget.child,+ );+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart b/mobile/third_party/xterm/lib/src/ui/gesture/gesture_handler.dartnew file mode 100644index 000000000..237b57ad7--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart@@ -0,0 +1,204 @@+import 'package:flutter/gestures.dart';+import 'package:flutter/widgets.dart';+import 'package:xterm/src/core/mouse/button.dart';+import 'package:xterm/src/core/mouse/button_state.dart';+import 'package:xterm/src/terminal_view.dart';+import 'package:xterm/src/ui/controller.dart';+import 'package:xterm/src/ui/gesture/gesture_detector.dart';+import 'package:xterm/src/ui/pointer_input.dart';+import 'package:xterm/src/ui/render.dart';++class TerminalGestureHandler extends StatefulWidget {+ const TerminalGestureHandler({+ super.key,+ required this.terminalView,+ required this.terminalController,+ this.child,+ this.onTapUp,+ this.onSingleTapUp,+ this.onTapDown,+ this.onSecondaryTapDown,+ this.onSecondaryTapUp,+ this.onTertiaryTapDown,+ this.onTertiaryTapUp,+ this.readOnly = false,+ });++ final TerminalViewState terminalView;++ final TerminalController terminalController;++ final Widget? child;++ final GestureTapUpCallback? onTapUp;++ final GestureTapUpCallback? onSingleTapUp;++ final bool Function(TapDownDetails)? onTapDown;++ final GestureTapDownCallback? onSecondaryTapDown;++ final GestureTapUpCallback? onSecondaryTapUp;++ final GestureTapDownCallback? onTertiaryTapDown;++ final GestureTapUpCallback? onTertiaryTapUp;++ final bool readOnly;++ @override+ State<TerminalGestureHandler> createState() => _TerminalGestureHandlerState();+}++class _TerminalGestureHandlerState extends State<TerminalGestureHandler> {+ TerminalViewState get terminalView => widget.terminalView;++ RenderTerminal get renderTerminal => terminalView.renderTerminal;++ DragStartDetails? _lastDragStartDetails;++ LongPressStartDetails? _lastLongPressStartDetails;++ bool _hostHandlesTap = false;++ @override+ Widget build(BuildContext context) {+ return TerminalGestureDetector(+ child: widget.child,+ onTapUp: widget.onTapUp,+ onSingleTapUp: onSingleTapUp,+ onTapDown: onTapDown,+ onSecondaryTapDown: onSecondaryTapDown,+ onSecondaryTapUp: onSecondaryTapUp,+ onTertiaryTapDown: onSecondaryTapDown,+ onTertiaryTapUp: onSecondaryTapUp,+ onLongPressStart: onLongPressStart,+ onLongPressMoveUpdate: onLongPressMoveUpdate,+ // onLongPressUp: onLongPressUp,+ onDragStart: onDragStart,+ onDragUpdate: onDragUpdate,+ onDoubleTapDown: onDoubleTapDown,+ );+ }++ bool get _shouldSendTapEvent =>+ !widget.readOnly &&+ widget.terminalController.shouldSendPointerInput(PointerInput.tap);++ void _tapDown(+ GestureTapDownCallback? callback,+ TapDownDetails details,+ TerminalMouseButton button, {+ bool forceCallback = false,+ }) {+ // Check if the terminal should and can handle the tap down event.+ var handled = false;+ if (_shouldSendTapEvent) {+ handled = renderTerminal.mouseEvent(+ button,+ TerminalMouseButtonState.down,+ details.localPosition,+ );+ }+ // If the event was not handled by the terminal, use the supplied callback.+ if (!handled || forceCallback) {+ callback?.call(details);+ }+ }++ void _tapUp(+ GestureTapUpCallback? callback,+ TapUpDetails details,+ TerminalMouseButton button, {+ bool forceCallback = false,+ }) {+ // Check if the terminal should and can handle the tap up event.+ var handled = false;+ if (_shouldSendTapEvent) {+ handled = renderTerminal.mouseEvent(+ button,+ TerminalMouseButtonState.up,+ details.localPosition,+ );+ }+ // If the event was not handled by the terminal, use the supplied callback.+ if (!handled || forceCallback) {+ callback?.call(details);+ }+ }++ void onTapDown(TapDownDetails details) {+ // Give host actions (e.g. Cmd-click a link) first refusal. Neither half+ // of a consumed click may also reach a mouse-tracking TUI.+ _hostHandlesTap = widget.onTapDown?.call(details) ?? false;+ if (_hostHandlesTap) return;+ _tapDown(+ null,+ details,+ TerminalMouseButton.left,+ );+ }++ void onSingleTapUp(TapUpDetails details) {+ void notify(TapUpDetails details) {+ widget.onTapUp?.call(details);+ widget.onSingleTapUp?.call(details);+ }++ if (_hostHandlesTap) {+ notify(details);+ return;+ }+ _tapUp(notify, details, TerminalMouseButton.left);+ }++ void onSecondaryTapDown(TapDownDetails details) {+ _tapDown(widget.onSecondaryTapDown, details, TerminalMouseButton.right);+ }++ void onSecondaryTapUp(TapUpDetails details) {+ _tapUp(widget.onSecondaryTapUp, details, TerminalMouseButton.right);+ }++ void onTertiaryTapDown(TapDownDetails details) {+ _tapDown(widget.onTertiaryTapDown, details, TerminalMouseButton.middle);+ }++ void onTertiaryTapUp(TapUpDetails details) {+ _tapUp(widget.onTertiaryTapUp, details, TerminalMouseButton.right);+ }++ void onDoubleTapDown(TapDownDetails details) {+ if (_hostHandlesTap) return;+ renderTerminal.selectWord(details.localPosition);+ }++ void onLongPressStart(LongPressStartDetails details) {+ _lastLongPressStartDetails = details;+ renderTerminal.selectWord(details.localPosition);+ }++ void onLongPressMoveUpdate(LongPressMoveUpdateDetails details) {+ renderTerminal.selectWord(+ _lastLongPressStartDetails!.localPosition,+ details.localPosition,+ );+ }++ // void onLongPressUp() {}++ void onDragStart(DragStartDetails details) {+ _lastDragStartDetails = details;++ details.kind == PointerDeviceKind.mouse+ ? renderTerminal.selectCharacters(details.localPosition)+ : renderTerminal.selectWord(details.localPosition);+ }++ void onDragUpdate(DragUpdateDetails details) {+ renderTerminal.selectCharacters(+ _lastDragStartDetails!.localPosition,+ details.localPosition,+ );+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/infinite_scroll_view.dart b/mobile/third_party/xterm/lib/src/ui/infinite_scroll_view.dartnew file mode 100644index 000000000..9640a3cac--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/infinite_scroll_view.dart@@ -0,0 +1,115 @@+import 'package:flutter/rendering.dart';+import 'package:flutter/widgets.dart';++/// The function called when the user scrolls the [InfiniteScrollView]. [offset]+/// is the current offset of the scroll view, ranging from [double.negativeInfinity]+/// to [double.infinity].+typedef ScrollCallback = void Function(double offset);++/// A [Scrollable] that can be scrolled infinitely in both directions. When+/// scroll happens, the [onScroll] callback is called with the new offset.+class InfiniteScrollView extends StatelessWidget {+ const InfiniteScrollView({+ super.key,+ required this.onScroll,+ required this.child,+ });++ final ScrollCallback onScroll;++ final Widget child;++ @override+ Widget build(BuildContext context) {+ return Scrollable(+ viewportBuilder: (context, position) {+ return _InfiniteScrollView(+ position: position,+ onScroll: onScroll,+ child: child,+ );+ },+ );+ }+}++class _InfiniteScrollView extends SingleChildRenderObjectWidget {+ const _InfiniteScrollView({+ // super.key,+ super.child,+ required this.position,+ required this.onScroll,+ });++ final ViewportOffset position;++ final ScrollCallback onScroll;++ @override+ RenderObject createRenderObject(BuildContext context) {+ return _RenderInfiniteScrollView(+ position: position,+ onScroll: onScroll,+ );+ }++ @override+ void updateRenderObject(+ BuildContext context,+ _RenderInfiniteScrollView renderObject,+ ) {+ renderObject+ ..position = position+ ..onScroll = onScroll;+ }+}++class _RenderInfiniteScrollView extends RenderShiftedBox {+ _RenderInfiniteScrollView({+ RenderBox? child,+ required ViewportOffset position,+ required ScrollCallback onScroll,+ }) : _position = position,+ _scrollCallback = onScroll,+ super(child);++ ViewportOffset _position;+ set position(ViewportOffset value) {+ if (_position == value) return;+ if (attached) _position.removeListener(markNeedsLayout);+ _position = value;+ if (attached) _position.addListener(markNeedsLayout);+ markNeedsLayout();+ }++ ScrollCallback _scrollCallback;+ set onScroll(ScrollCallback value) {+ if (_scrollCallback == value) return;+ _scrollCallback = value;+ markNeedsLayout();+ }++ void _onScroll() {+ _scrollCallback(_position.pixels);+ }++ @override+ void attach(covariant PipelineOwner owner) {+ super.attach(owner);+ _position.addListener(_onScroll);+ }++ @override+ void detach() {+ super.detach();+ _position.removeListener(_onScroll);+ }++ @override+ void performLayout() {+ child?.layout(constraints, parentUsesSize: true);+ size = child?.size ?? Size.zero;+ _position.applyViewportDimension(size.height);+ _position.applyContentDimensions(double.negativeInfinity, double.infinity);+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/input_map.dart b/mobile/third_party/xterm/lib/src/ui/input_map.dartnew file mode 100644index 000000000..3f65d1d1e--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/input_map.dart@@ -0,0 +1,288 @@+import 'package:flutter/services.dart';+import 'package:xterm/src/core/input/keys.dart';++final _keyToTerminalKey = {+ LogicalKeyboardKey.hyper: TerminalKey.hyper,+ LogicalKeyboardKey.superKey: TerminalKey.superKey,+ LogicalKeyboardKey.fnLock: TerminalKey.fnLock,+ LogicalKeyboardKey.suspend: TerminalKey.suspend,+ LogicalKeyboardKey.resume: TerminalKey.resume,+ LogicalKeyboardKey.sleep: TerminalKey.sleep,+ LogicalKeyboardKey.wakeUp: TerminalKey.wakeUp,+ LogicalKeyboardKey.keyA: TerminalKey.keyA,+ LogicalKeyboardKey.keyB: TerminalKey.keyB,+ LogicalKeyboardKey.keyC: TerminalKey.keyC,+ LogicalKeyboardKey.keyD: TerminalKey.keyD,+ LogicalKeyboardKey.keyE: TerminalKey.keyE,+ LogicalKeyboardKey.keyF: TerminalKey.keyF,+ LogicalKeyboardKey.keyG: TerminalKey.keyG,+ LogicalKeyboardKey.keyH: TerminalKey.keyH,+ LogicalKeyboardKey.keyI: TerminalKey.keyI,+ LogicalKeyboardKey.keyJ: TerminalKey.keyJ,+ LogicalKeyboardKey.keyK: TerminalKey.keyK,+ LogicalKeyboardKey.keyL: TerminalKey.keyL,+ LogicalKeyboardKey.keyM: TerminalKey.keyM,+ LogicalKeyboardKey.keyN: TerminalKey.keyN,+ LogicalKeyboardKey.keyO: TerminalKey.keyO,+ LogicalKeyboardKey.keyP: TerminalKey.keyP,+ LogicalKeyboardKey.keyQ: TerminalKey.keyQ,+ LogicalKeyboardKey.keyR: TerminalKey.keyR,+ LogicalKeyboardKey.keyS: TerminalKey.keyS,+ LogicalKeyboardKey.keyT: TerminalKey.keyT,+ LogicalKeyboardKey.keyU: TerminalKey.keyU,+ LogicalKeyboardKey.keyV: TerminalKey.keyV,+ LogicalKeyboardKey.keyW: TerminalKey.keyW,+ LogicalKeyboardKey.keyX: TerminalKey.keyX,+ LogicalKeyboardKey.keyY: TerminalKey.keyY,+ LogicalKeyboardKey.keyZ: TerminalKey.keyZ,+ LogicalKeyboardKey.digit1: TerminalKey.digit1,+ LogicalKeyboardKey.digit2: TerminalKey.digit2,+ LogicalKeyboardKey.digit3: TerminalKey.digit3,+ LogicalKeyboardKey.digit4: TerminalKey.digit4,+ LogicalKeyboardKey.digit5: TerminalKey.digit5,+ LogicalKeyboardKey.digit6: TerminalKey.digit6,+ LogicalKeyboardKey.digit7: TerminalKey.digit7,+ LogicalKeyboardKey.digit8: TerminalKey.digit8,+ LogicalKeyboardKey.digit9: TerminalKey.digit9,+ LogicalKeyboardKey.digit0: TerminalKey.digit0,+ LogicalKeyboardKey.enter: TerminalKey.enter,+ LogicalKeyboardKey.escape: TerminalKey.escape,+ LogicalKeyboardKey.backspace: TerminalKey.backspace,+ LogicalKeyboardKey.tab: TerminalKey.tab,+ LogicalKeyboardKey.space: TerminalKey.space,+ LogicalKeyboardKey.minus: TerminalKey.minus,+ LogicalKeyboardKey.equal: TerminalKey.equal,+ LogicalKeyboardKey.bracketLeft: TerminalKey.bracketLeft,+ LogicalKeyboardKey.bracketRight: TerminalKey.bracketRight,+ LogicalKeyboardKey.backslash: TerminalKey.backslash,+ LogicalKeyboardKey.semicolon: TerminalKey.semicolon,+ LogicalKeyboardKey.quote: TerminalKey.quote,+ LogicalKeyboardKey.backquote: TerminalKey.backquote,+ LogicalKeyboardKey.comma: TerminalKey.comma,+ LogicalKeyboardKey.period: TerminalKey.period,+ LogicalKeyboardKey.slash: TerminalKey.slash,+ LogicalKeyboardKey.capsLock: TerminalKey.capsLock,+ LogicalKeyboardKey.f1: TerminalKey.f1,+ LogicalKeyboardKey.f2: TerminalKey.f2,+ LogicalKeyboardKey.f3: TerminalKey.f3,+ LogicalKeyboardKey.f4: TerminalKey.f4,+ LogicalKeyboardKey.f5: TerminalKey.f5,+ LogicalKeyboardKey.f6: TerminalKey.f6,+ LogicalKeyboardKey.f7: TerminalKey.f7,+ LogicalKeyboardKey.f8: TerminalKey.f8,+ LogicalKeyboardKey.f9: TerminalKey.f9,+ LogicalKeyboardKey.f10: TerminalKey.f10,+ LogicalKeyboardKey.f11: TerminalKey.f11,+ LogicalKeyboardKey.f12: TerminalKey.f12,+ LogicalKeyboardKey.printScreen: TerminalKey.printScreen,+ LogicalKeyboardKey.scrollLock: TerminalKey.scrollLock,+ LogicalKeyboardKey.pause: TerminalKey.pause,+ LogicalKeyboardKey.insert: TerminalKey.insert,+ LogicalKeyboardKey.home: TerminalKey.home,+ LogicalKeyboardKey.pageUp: TerminalKey.pageUp,+ LogicalKeyboardKey.delete: TerminalKey.delete,+ LogicalKeyboardKey.end: TerminalKey.end,+ LogicalKeyboardKey.pageDown: TerminalKey.pageDown,+ LogicalKeyboardKey.arrowRight: TerminalKey.arrowRight,+ LogicalKeyboardKey.arrowLeft: TerminalKey.arrowLeft,+ LogicalKeyboardKey.arrowDown: TerminalKey.arrowDown,+ LogicalKeyboardKey.arrowUp: TerminalKey.arrowUp,+ LogicalKeyboardKey.numLock: TerminalKey.numLock,+ LogicalKeyboardKey.numpadDivide: TerminalKey.numpadDivide,+ LogicalKeyboardKey.numpadMultiply: TerminalKey.numpadMultiply,+ LogicalKeyboardKey.numpadSubtract: TerminalKey.numpadSubtract,+ LogicalKeyboardKey.numpadAdd: TerminalKey.numpadAdd,+ LogicalKeyboardKey.numpadEnter: TerminalKey.numpadEnter,+ LogicalKeyboardKey.numpad1: TerminalKey.numpad1,+ LogicalKeyboardKey.numpad2: TerminalKey.numpad2,+ LogicalKeyboardKey.numpad3: TerminalKey.numpad3,+ LogicalKeyboardKey.numpad4: TerminalKey.numpad4,+ LogicalKeyboardKey.numpad5: TerminalKey.numpad5,+ LogicalKeyboardKey.numpad6: TerminalKey.numpad6,+ LogicalKeyboardKey.numpad7: TerminalKey.numpad7,+ LogicalKeyboardKey.numpad8: TerminalKey.numpad8,+ LogicalKeyboardKey.numpad9: TerminalKey.numpad9,+ LogicalKeyboardKey.numpad0: TerminalKey.numpad0,+ LogicalKeyboardKey.numpadDecimal: TerminalKey.numpadDecimal,+ LogicalKeyboardKey.intlBackslash: TerminalKey.intlBackslash,+ LogicalKeyboardKey.contextMenu: TerminalKey.contextMenu,+ LogicalKeyboardKey.power: TerminalKey.power,+ LogicalKeyboardKey.numpadEqual: TerminalKey.numpadEqual,+ LogicalKeyboardKey.f13: TerminalKey.f13,+ LogicalKeyboardKey.f14: TerminalKey.f14,+ LogicalKeyboardKey.f15: TerminalKey.f15,+ LogicalKeyboardKey.f16: TerminalKey.f16,+ LogicalKeyboardKey.f17: TerminalKey.f17,+ LogicalKeyboardKey.f18: TerminalKey.f18,+ LogicalKeyboardKey.f19: TerminalKey.f19,+ LogicalKeyboardKey.f20: TerminalKey.f20,+ LogicalKeyboardKey.f21: TerminalKey.f21,+ LogicalKeyboardKey.f22: TerminalKey.f22,+ LogicalKeyboardKey.f23: TerminalKey.f23,+ LogicalKeyboardKey.f24: TerminalKey.f24,+ LogicalKeyboardKey.open: TerminalKey.open,+ LogicalKeyboardKey.help: TerminalKey.help,+ LogicalKeyboardKey.select: TerminalKey.select,+ LogicalKeyboardKey.again: TerminalKey.again,+ LogicalKeyboardKey.undo: TerminalKey.undo,+ LogicalKeyboardKey.cut: TerminalKey.cut,+ LogicalKeyboardKey.copy: TerminalKey.copy,+ LogicalKeyboardKey.paste: TerminalKey.paste,+ LogicalKeyboardKey.find: TerminalKey.find,+ LogicalKeyboardKey.audioVolumeMute: TerminalKey.audioVolumeMute,+ LogicalKeyboardKey.audioVolumeUp: TerminalKey.audioVolumeUp,+ LogicalKeyboardKey.audioVolumeDown: TerminalKey.audioVolumeDown,+ LogicalKeyboardKey.numpadComma: TerminalKey.numpadComma,+ LogicalKeyboardKey.intlRo: TerminalKey.intlRo,+ LogicalKeyboardKey.kanaMode: TerminalKey.kanaMode,+ LogicalKeyboardKey.intlYen: TerminalKey.intlYen,+ LogicalKeyboardKey.convert: TerminalKey.convert,+ LogicalKeyboardKey.nonConvert: TerminalKey.nonConvert,+ LogicalKeyboardKey.lang1: TerminalKey.lang1,+ LogicalKeyboardKey.lang2: TerminalKey.lang2,+ LogicalKeyboardKey.lang3: TerminalKey.lang3,+ LogicalKeyboardKey.lang4: TerminalKey.lang4,+ LogicalKeyboardKey.lang5: TerminalKey.lang5,+ LogicalKeyboardKey.abort: TerminalKey.abort,+ LogicalKeyboardKey.props: TerminalKey.props,+ LogicalKeyboardKey.numpadParenLeft: TerminalKey.numpadParenLeft,+ LogicalKeyboardKey.numpadParenRight: TerminalKey.numpadParenRight,+ LogicalKeyboardKey.controlLeft: TerminalKey.controlLeft,+ LogicalKeyboardKey.shiftLeft: TerminalKey.shiftLeft,+ LogicalKeyboardKey.altLeft: TerminalKey.altLeft,+ LogicalKeyboardKey.metaLeft: TerminalKey.metaLeft,+ LogicalKeyboardKey.controlRight: TerminalKey.controlRight,+ LogicalKeyboardKey.shiftRight: TerminalKey.shiftRight,+ LogicalKeyboardKey.altRight: TerminalKey.altRight,+ LogicalKeyboardKey.metaRight: TerminalKey.metaRight,+ LogicalKeyboardKey.info: TerminalKey.info,+ LogicalKeyboardKey.closedCaptionToggle: TerminalKey.closedCaptionToggle,+ LogicalKeyboardKey.brightnessUp: TerminalKey.brightnessUp,+ LogicalKeyboardKey.brightnessDown: TerminalKey.brightnessDown,+ LogicalKeyboardKey.mediaLast: TerminalKey.mediaLast,+ LogicalKeyboardKey.launchPhone: TerminalKey.launchPhone,+ LogicalKeyboardKey.exit: TerminalKey.exit,+ LogicalKeyboardKey.channelUp: TerminalKey.channelUp,+ LogicalKeyboardKey.channelDown: TerminalKey.channelDown,+ LogicalKeyboardKey.mediaPlay: TerminalKey.mediaPlay,+ LogicalKeyboardKey.mediaPause: TerminalKey.mediaPause,+ LogicalKeyboardKey.mediaRecord: TerminalKey.mediaRecord,+ LogicalKeyboardKey.mediaFastForward: TerminalKey.mediaFastForward,+ LogicalKeyboardKey.mediaRewind: TerminalKey.mediaRewind,+ LogicalKeyboardKey.mediaTrackNext: TerminalKey.mediaTrackNext,+ LogicalKeyboardKey.mediaTrackPrevious: TerminalKey.mediaTrackPrevious,+ LogicalKeyboardKey.mediaStop: TerminalKey.mediaStop,+ LogicalKeyboardKey.eject: TerminalKey.eject,+ LogicalKeyboardKey.mediaPlayPause: TerminalKey.mediaPlayPause,+ LogicalKeyboardKey.speechInputToggle: TerminalKey.speechInputToggle,+ LogicalKeyboardKey.launchWordProcessor: TerminalKey.launchWordProcessor,+ LogicalKeyboardKey.launchSpreadsheet: TerminalKey.launchSpreadsheet,+ LogicalKeyboardKey.launchMail: TerminalKey.launchMail,+ LogicalKeyboardKey.launchContacts: TerminalKey.launchContacts,+ LogicalKeyboardKey.launchCalendar: TerminalKey.launchCalendar,+ LogicalKeyboardKey.logOff: TerminalKey.logOff,+ LogicalKeyboardKey.launchControlPanel: TerminalKey.launchControlPanel,+ LogicalKeyboardKey.spellCheck: TerminalKey.spellCheck,+ LogicalKeyboardKey.launchScreenSaver: TerminalKey.launchScreenSaver,+ LogicalKeyboardKey.launchAssistant: TerminalKey.launchAssistant,+ LogicalKeyboardKey.newKey: TerminalKey.newKey,+ LogicalKeyboardKey.close: TerminalKey.close,+ LogicalKeyboardKey.save: TerminalKey.save,+ LogicalKeyboardKey.print: TerminalKey.print,+ LogicalKeyboardKey.browserSearch: TerminalKey.browserSearch,+ LogicalKeyboardKey.browserHome: TerminalKey.browserHome,+ LogicalKeyboardKey.browserBack: TerminalKey.browserBack,+ LogicalKeyboardKey.browserForward: TerminalKey.browserForward,+ LogicalKeyboardKey.browserStop: TerminalKey.browserStop,+ LogicalKeyboardKey.browserRefresh: TerminalKey.browserRefresh,+ LogicalKeyboardKey.browserFavorites: TerminalKey.browserFavorites,+ LogicalKeyboardKey.zoomIn: TerminalKey.zoomIn,+ LogicalKeyboardKey.zoomOut: TerminalKey.zoomOut,+ LogicalKeyboardKey.zoomToggle: TerminalKey.zoomToggle,+ LogicalKeyboardKey.redo: TerminalKey.redo,+ LogicalKeyboardKey.mailReply: TerminalKey.mailReply,+ LogicalKeyboardKey.mailForward: TerminalKey.mailForward,+ LogicalKeyboardKey.mailSend: TerminalKey.mailSend,+ LogicalKeyboardKey.gameButton1: TerminalKey.gameButton1,+ LogicalKeyboardKey.gameButton2: TerminalKey.gameButton2,+ LogicalKeyboardKey.gameButton3: TerminalKey.gameButton3,+ LogicalKeyboardKey.gameButton4: TerminalKey.gameButton4,+ LogicalKeyboardKey.gameButton5: TerminalKey.gameButton5,+ LogicalKeyboardKey.gameButton6: TerminalKey.gameButton6,+ LogicalKeyboardKey.gameButton7: TerminalKey.gameButton7,+ LogicalKeyboardKey.gameButton8: TerminalKey.gameButton8,+ LogicalKeyboardKey.gameButton9: TerminalKey.gameButton9,+ LogicalKeyboardKey.gameButton10: TerminalKey.gameButton10,+ LogicalKeyboardKey.gameButton11: TerminalKey.gameButton11,+ LogicalKeyboardKey.gameButton12: TerminalKey.gameButton12,+ LogicalKeyboardKey.gameButton13: TerminalKey.gameButton13,+ LogicalKeyboardKey.gameButton14: TerminalKey.gameButton14,+ LogicalKeyboardKey.gameButton15: TerminalKey.gameButton15,+ LogicalKeyboardKey.gameButton16: TerminalKey.gameButton16,+ LogicalKeyboardKey.gameButtonA: TerminalKey.gameButtonA,+ LogicalKeyboardKey.gameButtonB: TerminalKey.gameButtonB,+ LogicalKeyboardKey.gameButtonC: TerminalKey.gameButtonC,+ LogicalKeyboardKey.gameButtonLeft1: TerminalKey.gameButtonLeft1,+ LogicalKeyboardKey.gameButtonLeft2: TerminalKey.gameButtonLeft2,+ LogicalKeyboardKey.gameButtonMode: TerminalKey.gameButtonMode,+ LogicalKeyboardKey.gameButtonRight1: TerminalKey.gameButtonRight1,+ LogicalKeyboardKey.gameButtonRight2: TerminalKey.gameButtonRight2,+ LogicalKeyboardKey.gameButtonSelect: TerminalKey.gameButtonSelect,+ LogicalKeyboardKey.gameButtonStart: TerminalKey.gameButtonStart,+ LogicalKeyboardKey.gameButtonThumbLeft: TerminalKey.gameButtonThumbLeft,+ LogicalKeyboardKey.gameButtonThumbRight: TerminalKey.gameButtonThumbRight,+ LogicalKeyboardKey.gameButtonX: TerminalKey.gameButtonX,+ LogicalKeyboardKey.gameButtonY: TerminalKey.gameButtonY,+ LogicalKeyboardKey.gameButtonZ: TerminalKey.gameButtonZ,+ LogicalKeyboardKey.fn: TerminalKey.fn,+ LogicalKeyboardKey.shift: TerminalKey.shift,+ LogicalKeyboardKey.meta: TerminalKey.meta,+ LogicalKeyboardKey.alt: TerminalKey.alt,+ LogicalKeyboardKey.control: TerminalKey.control,+};++final _keyById = () {+ final map = <int, TerminalKey>{};+ for (final entry in _keyToTerminalKey.entries) {+ map[entry.key.keyId] = entry.value;+ }+ return map;+}();++final _keyByChar = () {+ final map = <String, TerminalKey>{};+ for (final entry in _keyToTerminalKey.entries) {+ final label = entry.key.keyLabel;++ if (label.isEmpty || label.length > 1) {+ continue;+ }++ map[label] = entry.value;+ map[label.toUpperCase()] = entry.value;+ map[label.toLowerCase()] = entry.value;+ }+ return map;+}();++/// Converts a [LogicalKeyboardKey] to a [TerminalKey]. Returns `null` if the+/// key does not have a corresponding [TerminalKey].+///+/// For example, `LogicalKeyboardKey.keyA` will be converted to+/// `TerminalKey.keyA`.+TerminalKey? keyToTerminalKey(LogicalKeyboardKey key) {+ return _keyById[key.keyId];+}++/// Converts a character to a [TerminalKey]. Returns `null` if the character+/// does not have a corresponding [TerminalKey].+///+/// For example, `charToTerminalKey('a')` or `charToTerminalKey('A')` will both+/// return [TerminalKey.a].+TerminalKey? charToTerminalKey(String char) {+ if (char.length != 1) {+ return null;+ }++ return _keyByChar[char];+}diff --git a/mobile/third_party/xterm/lib/src/ui/keyboard_listener.dart b/mobile/third_party/xterm/lib/src/ui/keyboard_listener.dartnew file mode 100644index 000000000..bb2f9920e--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/keyboard_listener.dart@@ -0,0 +1,49 @@+import 'package:flutter/widgets.dart';++class CustomKeyboardListener extends StatelessWidget {+ final Widget child;++ final FocusNode focusNode;++ final bool autofocus;++ final void Function(String) onInsert;++ final void Function(String?) onComposing;++ final KeyEventResult Function(FocusNode, KeyEvent) onKeyEvent;++ const CustomKeyboardListener({+ super.key,+ required this.child,+ required this.focusNode,+ this.autofocus = false,+ required this.onInsert,+ required this.onComposing,+ required this.onKeyEvent,+ });++ KeyEventResult _onKeyEvent(FocusNode focusNode, KeyEvent keyEvent) {+ // First try to handle the key event directly.+ final handled = onKeyEvent(focusNode, keyEvent);+ if (handled == KeyEventResult.ignored) {+ // If it was not handled, but the key corresponds to a character,+ // insert the character.+ if (keyEvent.character != null && keyEvent.character != "") {+ onInsert(keyEvent.character!);+ return KeyEventResult.handled;+ }+ }+ return handled;+ }++ @override+ Widget build(BuildContext context) {+ return Focus(+ focusNode: focusNode,+ autofocus: autofocus,+ onKeyEvent: _onKeyEvent,+ child: child,+ );+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/keyboard_visibility.dart b/mobile/third_party/xterm/lib/src/ui/keyboard_visibility.dartnew file mode 100644index 000000000..158c5d114--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/keyboard_visibility.dart@@ -0,0 +1,58 @@+import 'package:flutter/widgets.dart';++class KeyboardVisibilty extends StatefulWidget {+ const KeyboardVisibilty({+ super.key,+ required this.child,+ this.onKeyboardShow,+ this.onKeyboardHide,+ });++ final Widget child;++ final VoidCallback? onKeyboardShow;++ final VoidCallback? onKeyboardHide;++ @override+ KeyboardVisibiltyState createState() => KeyboardVisibiltyState();+}++class KeyboardVisibiltyState extends State<KeyboardVisibilty>+ with WidgetsBindingObserver {+ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }++ @override+ void didChangeMetrics() {+ final bottomInset = View.of(context).viewInsets.bottom;++ if (bottomInset != _lastBottomInset) {+ if (bottomInset > 0) {+ widget.onKeyboardShow?.call();+ } else {+ widget.onKeyboardHide?.call();+ }+ }++ _lastBottomInset = bottomInset;++ super.didChangeMetrics();+ }++ var _lastBottomInset = 0.0;++ @override+ Widget build(BuildContext context) {+ return widget.child;+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/painter.dart b/mobile/third_party/xterm/lib/src/ui/painter.dartnew file mode 100644index 000000000..bc45fa21c--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/painter.dart@@ -0,0 +1,290 @@+import 'dart:ui';+import 'package:flutter/painting.dart';++import 'package:xterm/src/ui/palette_builder.dart';+import 'package:xterm/src/ui/paragraph_cache.dart';+import 'package:xterm/xterm.dart';++/// Returns the glyph text used to paint one terminal code point.+///+/// U+23FA defaults to Apple's coloured "record button" emoji when the active+/// monospace face has no glyph for it. Flutter's Skia fallback still chooses+/// that emoji even with a text-presentation selector, while SF Mono contains+/// U+25CF as the equivalent filled status dot. Substitute only while painting+/// so ANSI supplies the colour and the terminal buffer/copy text stays U+23FA.+String terminalGlyphText(int charCode) => charCode == 0x23FA+ ? String.fromCharCode(0x25CF)+ : String.fromCharCode(charCode);++/// Encapsulates the logic for painting various terminal elements.+class TerminalPainter {+ TerminalPainter({+ required TerminalTheme theme,+ required TerminalStyle textStyle,+ required TextScaler textScaler,+ }) : _textStyle = textStyle,+ _theme = theme,+ _textScaler = textScaler;++ /// A lookup table from terminal colors to Flutter colors.+ late var _colorPalette = PaletteBuilder(_theme).build();++ /// Size of each character in the terminal.+ late var _cellSize = _measureCharSize();++ /// The cached for cells in the terminal. Should be cleared when the same+ /// cell no longer produces the same visual output. For example, when+ /// [_textStyle] is changed, or when the system font changes.+ final _paragraphCache = ParagraphCache(10240);++ TerminalStyle get textStyle => _textStyle;+ TerminalStyle _textStyle;+ set textStyle(TerminalStyle value) {+ if (value == _textStyle) return;+ _textStyle = value;+ _cellSize = _measureCharSize();+ _paragraphCache.clear();+ }++ TextScaler get textScaler => _textScaler;+ TextScaler _textScaler = TextScaler.linear(1.0);+ set textScaler(TextScaler value) {+ if (value == _textScaler) return;+ _textScaler = value;+ _cellSize = _measureCharSize();+ _paragraphCache.clear();+ }++ TerminalTheme get theme => _theme;+ TerminalTheme _theme;+ set theme(TerminalTheme value) {+ if (value == _theme) return;+ _theme = value;+ _colorPalette = PaletteBuilder(value).build();+ _paragraphCache.clear();+ }++ Size _measureCharSize() {+ const test = 'mmmmmmmmmm';++ final textStyle = _textStyle.toTextStyle();+ final builder = ParagraphBuilder(textStyle.getParagraphStyle());+ builder.pushStyle(+ textStyle.getTextStyle(textScaler: _textScaler),+ );+ builder.addText(test);++ final paragraph = builder.build();+ paragraph.layout(ParagraphConstraints(width: double.infinity));++ final result = Size(+ paragraph.maxIntrinsicWidth / test.length,+ paragraph.height,+ );++ paragraph.dispose();+ return result;+ }++ /// The size of each character in the terminal.+ Size get cellSize => _cellSize;++ /// When the set of font available to the system changes, call this method to+ /// clear cached state related to font rendering.+ void clearFontCache() {+ _cellSize = _measureCharSize();+ _paragraphCache.clear();+ }++ /// Paints the cursor based on the current cursor type.+ void paintCursor(+ Canvas canvas,+ Offset offset, {+ required TerminalCursorType cursorType,+ bool hasFocus = true,+ }) {+ final paint = Paint()+ ..color = _theme.cursor+ ..strokeWidth = 1;++ if (!hasFocus) {+ paint.style = PaintingStyle.stroke;+ canvas.drawRect(offset & _cellSize, paint);+ return;+ }++ switch (cursorType) {+ case TerminalCursorType.block:+ paint.style = PaintingStyle.fill;+ canvas.drawRect(offset & _cellSize, paint);+ return;+ case TerminalCursorType.underline:+ return canvas.drawLine(+ Offset(offset.dx, _cellSize.height - 1),+ Offset(offset.dx + _cellSize.width, _cellSize.height - 1),+ paint,+ );+ case TerminalCursorType.verticalBar:+ return canvas.drawLine(+ Offset(offset.dx, 0),+ Offset(offset.dx, _cellSize.height),+ paint,+ );+ }+ }++ @pragma('vm:prefer-inline')+ void paintHighlight(Canvas canvas, Offset offset, int length, Color color) {+ final endOffset =+ offset.translate(length * _cellSize.width, _cellSize.height);++ final paint = Paint()+ ..color = color+ ..strokeWidth = 1;++ canvas.drawRect(+ Rect.fromPoints(offset, endOffset),+ paint,+ );+ }++ /// Paints [line] to [canvas] at [offset]. The x offset of [offset] is usually+ /// 0, and the y offset is the top of the line.+ void paintLine(+ Canvas canvas,+ Offset offset,+ BufferLine line,+ ) {+ final cellData = CellData.empty();+ final cellWidth = _cellSize.width;++ for (var i = 0; i < line.length; i++) {+ line.getCellData(i, cellData);++ final charWidth = cellData.content >> CellContent.widthShift;+ final cellOffset = offset.translate(i * cellWidth, 0);++ paintCell(canvas, cellOffset, cellData);++ if (charWidth == 2) {+ i++;+ }+ }+ }++ @pragma('vm:prefer-inline')+ void paintCell(Canvas canvas, Offset offset, CellData cellData) {+ paintCellBackground(canvas, offset, cellData);+ paintCellForeground(canvas, offset, cellData);+ }++ /// Paints the character in the cell represented by [cellData] to [canvas] at+ /// [offset].+ @pragma('vm:prefer-inline')+ void paintCellForeground(Canvas canvas, Offset offset, CellData cellData) {+ final charCode = cellData.content & CellContent.codepointMask;+ if (charCode == 0) return;++ final cacheKey = cellData.getHash() ^ _textScaler.hashCode;+ var paragraph = _paragraphCache.getLayoutFromCache(cacheKey);++ if (paragraph == null) {+ final cellFlags = cellData.flags;++ var color = cellFlags & CellFlags.inverse == 0+ ? resolveForegroundColor(cellData.foreground)+ : resolveBackgroundColor(cellData.background);++ if (cellData.flags & CellFlags.faint != 0) {+ color = color.withOpacity(0.5);+ }++ final style = _textStyle.toTextStyle(+ color: color,+ bold: cellFlags & CellFlags.bold != 0,+ italic: cellFlags & CellFlags.italic != 0,+ underline: cellFlags & CellFlags.underline != 0,+ );++ // Flutter does not draw an underline below a space which is not between+ // other regular characters. As only single characters are drawn, this+ // will never produce an underline below a space in the terminal. As a+ // workaround the regular space CodePoint 0x20 is replaced with+ // the CodePoint 0xA0. This is a non breaking space and a underline can be+ // drawn below it.+ var char = terminalGlyphText(charCode);+ if (cellFlags & CellFlags.underline != 0 && charCode == 0x20) {+ char = String.fromCharCode(0xA0);+ }++ paragraph = _paragraphCache.performAndCacheLayout(+ char,+ style,+ _textScaler,+ cacheKey,+ );+ }++ canvas.drawParagraph(paragraph, offset);+ }++ /// Paints the background of a cell represented by [cellData] to [canvas] at+ /// [offset].+ @pragma('vm:prefer-inline')+ void paintCellBackground(Canvas canvas, Offset offset, CellData cellData) {+ late Color color;+ final colorType = cellData.background & CellColor.typeMask;++ if (cellData.flags & CellFlags.inverse != 0) {+ color = resolveForegroundColor(cellData.foreground);+ } else if (colorType == CellColor.normal) {+ return;+ } else {+ color = resolveBackgroundColor(cellData.background);+ }++ final paint = Paint()..color = color;+ final doubleWidth = cellData.content >> CellContent.widthShift == 2;+ final widthScale = doubleWidth ? 2 : 1;+ final size = Size(_cellSize.width * widthScale + 1, _cellSize.height);+ canvas.drawRect(offset & size, paint);+ }++ /// Get the effective foreground color for a cell from information encoded in+ /// [cellColor].+ @pragma('vm:prefer-inline')+ Color resolveForegroundColor(int cellColor) {+ final colorType = cellColor & CellColor.typeMask;+ final colorValue = cellColor & CellColor.valueMask;++ switch (colorType) {+ case CellColor.normal:+ return _theme.foreground;+ case CellColor.named:+ case CellColor.palette:+ return _colorPalette[colorValue];+ case CellColor.rgb:+ default:+ return Color(colorValue | 0xFF000000);+ }+ }++ /// Get the effective background color for a cell from information encoded in+ /// [cellColor].+ @pragma('vm:prefer-inline')+ Color resolveBackgroundColor(int cellColor) {+ final colorType = cellColor & CellColor.typeMask;+ final colorValue = cellColor & CellColor.valueMask;++ switch (colorType) {+ case CellColor.normal:+ return _theme.background;+ case CellColor.named:+ case CellColor.palette:+ return _colorPalette[colorValue];+ case CellColor.rgb:+ default:+ return Color(colorValue | 0xFF000000);+ }+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/palette_builder.dart b/mobile/third_party/xterm/lib/src/ui/palette_builder.dartnew file mode 100644index 000000000..0dedff03b--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/palette_builder.dart@@ -0,0 +1,118 @@+import 'package:flutter/widgets.dart';+import 'package:xterm/src/ui/terminal_theme.dart';+import 'package:xterm/src/utils/lookup_table.dart';++class PaletteBuilder {+ final TerminalTheme theme;++ PaletteBuilder(this.theme);++ List<Color> build() {+ return List<Color>.generate(+ 256,+ paletteColor,+ growable: false,+ );+ }++ /// https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit+ Color paletteColor(int colNum) {+ switch (colNum) {+ case 0:+ return theme.black;+ case 1:+ return theme.red;+ case 2:+ return theme.green;+ case 3:+ return theme.yellow;+ case 4:+ return theme.blue;+ case 5:+ return theme.magenta;+ case 6:+ return theme.cyan;+ case 7:+ return theme.white;+ case 8:+ return theme.brightBlack;+ case 9:+ return theme.brightRed;+ case 10:+ return theme.brightGreen;+ case 11:+ return theme.brightYellow;+ case 12:+ return theme.brightBlue;+ case 13:+ return theme.brightMagenta;+ case 14:+ return theme.brightCyan;+ case 15:+ return theme.white;+ }++ if (colNum < 232) {+ var r = 0;+ var g = 0;+ var b = 0;++ final index = colNum - 16;++ for (var i = 0; i < index; i++) {+ if (b == 0) {+ b = 95;+ } else if (b < 255) {+ b += 40;+ } else {+ b = 0;+ if (g == 0) {+ g = 95;+ } else if (g < 255) {+ g += 40;+ } else {+ g = 0;+ if (r == 0) {+ r = 95;+ } else if (r < 255) {+ r += 40;+ } else {+ break;+ }+ }+ }+ }++ return Color.fromARGB(0xFF, r, g, b);+ }++ return Color(_grayscaleColors[colNum.clamp(232, 255)]!);+ }+}++final _grayscaleColors = FastLookupTable({+ 232: 0xff080808,+ 233: 0xff121212,+ 234: 0xff1c1c1c,+ 235: 0xff262626,+ 236: 0xff303030,+ 237: 0xff3a3a3a,+ 238: 0xff444444,+ 239: 0xff4e4e4e,+ 240: 0xff585858,+ 241: 0xff626262,+ 242: 0xff6c6c6c,+ 243: 0xff767676,+ 244: 0xff808080,+ 245: 0xff8a8a8a,+ 246: 0xff949494,+ 247: 0xff9e9e9e,+ 248: 0xffa8a8a8,+ 249: 0xffb2b2b2,+ 250: 0xffbcbcbc,+ 251: 0xffc6c6c6,+ 252: 0xffd0d0d0,+ 253: 0xffdadada,+ 254: 0xffe4e4e4,+ 255: 0xffeeeeee,+});diff --git a/mobile/third_party/xterm/lib/src/ui/paragraph_cache.dart b/mobile/third_party/xterm/lib/src/ui/paragraph_cache.dartnew file mode 100644index 000000000..80896a042--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/paragraph_cache.dart@@ -0,0 +1,51 @@+import 'dart:ui';++import 'package:flutter/widgets.dart';+import 'package:quiver/collection.dart';++/// A cache of laid out [Paragraph]s. This is used to avoid laying out the same+/// text multiple times, which is expensive.+class ParagraphCache {+ ParagraphCache(int maximumSize)+ : _cache = LruMap<int, Paragraph>(maximumSize: maximumSize);++ final LruMap<int, Paragraph> _cache;++ /// Returns a [Paragraph] for the given [key]. [key] is the same as the+ /// key argument to [performAndCacheLayout].+ Paragraph? getLayoutFromCache(int key) {+ return _cache[key];+ }++ /// Applies [style] and [textScaler] to [text] and lays it out to create+ /// a [Paragraph]. The [Paragraph] is cached and can be retrieved with the+ /// same [key] by calling [getLayoutFromCache].+ Paragraph performAndCacheLayout(+ String text,+ TextStyle style,+ TextScaler textScaler,+ int key,+ ) {+ final builder = ParagraphBuilder(style.getParagraphStyle());+ builder.pushStyle(style.getTextStyle(textScaler: textScaler));+ builder.addText(text);++ final paragraph = builder.build();+ paragraph.layout(ParagraphConstraints(width: double.infinity));++ _cache[key] = paragraph;+ return paragraph;+ }++ /// Clears the cache. This should be called when the same text and style+ /// pair no longer produces the same layout. For example, when a font is+ /// loaded.+ void clear() {+ _cache.clear();+ }++ /// Returns the number of [Paragraph]s in the cache.+ int get length {+ return _cache.length;+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/pointer_input.dart b/mobile/third_party/xterm/lib/src/ui/pointer_input.dartnew file mode 100644index 000000000..1f2bd5379--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/pointer_input.dart@@ -0,0 +1,29 @@+enum PointerInput {+ /// Taps / buttons presses & releases.+ tap,++ /// Scroll / mouse wheels events.+ scroll,++ /// Drag events, a pointer is in a down state and dragged across the terminal.+ drag,++ /// Move events, a pointer is in an up state and moved across the terminal.+ move,+}++class PointerInputs {+ final Set<PointerInput> inputs;++ const PointerInputs(this.inputs);++ const PointerInputs.none() : inputs = const <PointerInput>{};++ const PointerInputs.all()+ : inputs = const <PointerInput>{+ PointerInput.tap,+ PointerInput.scroll,+ PointerInput.drag,+ PointerInput.move,+ };+}diff --git a/mobile/third_party/xterm/lib/src/ui/render.dart b/mobile/third_party/xterm/lib/src/ui/render.dartnew file mode 100644index 000000000..b8da24cd9--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/render.dart@@ -0,0 +1,715 @@+import 'dart:math' show max;+import 'package:flutter/rendering.dart';+import 'package:flutter/scheduler.dart';+import 'package:flutter/widgets.dart';+import 'package:xterm/src/core/buffer/cell_offset.dart';+import 'package:xterm/src/core/buffer/range.dart';+import 'package:xterm/src/core/buffer/segment.dart';+import 'package:xterm/src/core/mouse/button.dart';+import 'package:xterm/src/core/mouse/button_state.dart';+import 'package:xterm/src/terminal.dart';+import 'package:xterm/src/ui/controller.dart';+import 'package:xterm/src/ui/cursor_type.dart';+import 'package:xterm/src/ui/painter.dart';+import 'package:xterm/src/ui/selection_mode.dart';+import 'package:xterm/src/ui/terminal_size.dart';+import 'package:xterm/src/ui/terminal_text_style.dart';+import 'package:xterm/src/ui/terminal_theme.dart';++typedef EditableRectCallback = void Function(Rect rect, Rect caretRect);++class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {+ RenderTerminal({+ required Terminal terminal,+ required TerminalController controller,+ required ViewportOffset offset,+ required EdgeInsets padding,+ required bool autoResize,+ bool resizeBuffer = true,+ bool renderingEnabled = true,+ required TerminalStyle textStyle,+ required TextScaler textScaler,+ required TerminalTheme theme,+ required FocusNode focusNode,+ required TerminalCursorType cursorType,+ required bool alwaysShowCursor,+ EditableRectCallback? onEditableRect,+ String? composingText,+ int composingBacktrackCells = 0,+ }) : _terminal = terminal,+ _controller = controller,+ _offset = offset,+ _padding = padding,+ _autoResize = autoResize,+ _resizeBuffer = resizeBuffer,+ _renderingEnabled = renderingEnabled,+ _focusNode = focusNode,+ _cursorType = cursorType,+ _alwaysShowCursor = alwaysShowCursor,+ _onEditableRect = onEditableRect,+ _composingText = composingText,+ _composingBacktrackCells = composingBacktrackCells,+ _painter = TerminalPainter(+ theme: theme,+ textStyle: textStyle,+ textScaler: textScaler,+ );++ Terminal _terminal;+ set terminal(Terminal terminal) {+ if (_terminal == terminal) return;+ if (attached && _renderingEnabled) {+ _terminal.removeListener(_onTerminalChange);+ }+ _terminal = terminal;+ _reportedViewportSize = null;+ if (attached && _renderingEnabled) _terminal.addListener(_onTerminalChange);+ _resizeTerminalIfNeeded();+ markNeedsLayout();+ }++ TerminalController _controller;+ set controller(TerminalController controller) {+ if (_controller == controller) return;+ if (attached) _controller.removeListener(_onControllerUpdate);+ _controller = controller;+ if (attached) _controller.addListener(_onControllerUpdate);+ markNeedsLayout();+ }++ ViewportOffset _offset;+ set offset(ViewportOffset value) {+ if (value == _offset) return;+ if (attached) _offset.removeListener(_onScroll);+ _offset = value;+ if (attached) _offset.addListener(_onScroll);+ markNeedsLayout();+ }++ EdgeInsets _padding;+ set padding(EdgeInsets value) {+ if (value == _padding) return;+ _padding = value;+ markNeedsLayout();+ }++ bool _autoResize;+ set autoResize(bool value) {+ if (value == _autoResize) return;+ _autoResize = value;+ markNeedsLayout();+ }++ bool _resizeBuffer;+ set resizeBuffer(bool value) {+ if (value == _resizeBuffer) return;+ _resizeBuffer = value;+ _reportedViewportSize = null;+ markNeedsLayout();+ }++ bool _renderingEnabled;+ set renderingEnabled(bool value) {+ if (value == _renderingEnabled) return;+ _renderingEnabled = value;+ if (attached) {+ if (value) {+ _terminal.addListener(_onTerminalChange);+ } else {+ _terminal.removeListener(_onTerminalChange);+ }+ }+ // Catch up from the live buffer once, preserving follow-tail or the user's+ // scroll offset. Hidden output never queues a renderer layout or paint.+ if (value) markNeedsLayout();+ }++ set textStyle(TerminalStyle value) {+ if (value == _painter.textStyle) return;+ _painter.textStyle = value;+ markNeedsLayout();+ }++ set textScaler(TextScaler value) {+ if (value == _painter.textScaler) return;+ _painter.textScaler = value;+ markNeedsLayout();+ }++ set theme(TerminalTheme value) {+ if (value == _painter.theme) return;+ _painter.theme = value;+ markNeedsPaint();+ }++ FocusNode _focusNode;+ set focusNode(FocusNode value) {+ if (value == _focusNode) return;+ if (attached) _focusNode.removeListener(_onFocusChange);+ _focusNode = value;+ if (attached) _focusNode.addListener(_onFocusChange);+ markNeedsPaint();+ }++ TerminalCursorType _cursorType;+ set cursorType(TerminalCursorType value) {+ if (value == _cursorType) return;+ _cursorType = value;+ markNeedsPaint();+ }++ bool _alwaysShowCursor;+ set alwaysShowCursor(bool value) {+ if (value == _alwaysShowCursor) return;+ _alwaysShowCursor = value;+ markNeedsPaint();+ }++ EditableRectCallback? _onEditableRect;+ set onEditableRect(EditableRectCallback? value) {+ if (value == _onEditableRect) return;+ _onEditableRect = value;+ markNeedsLayout();+ }++ String? _composingText;+ set composingText(String? value) {+ if (value == _composingText) return;+ _composingText = value;+ markNeedsPaint();+ }++ int _composingBacktrackCells;+ set composingBacktrackCells(int value) {+ if (value == _composingBacktrackCells) return;+ _composingBacktrackCells = value;+ markNeedsPaint();+ }++ TerminalSize? _viewportSize;+ TerminalSize? _reportedViewportSize;++ final TerminalPainter _painter;++ var _stickToBottom = true;+ double _laidOutMaxScrollExtent = 0;+ bool _editableRectPending = false;++ void _onScroll() {+ // Output may already have extended the buffer since the last layout. The+ // scroll position still describes that layout, so comparing it to the live+ // buffer would mistake a jump to the tail for scrolling up into history.+ _stickToBottom = _scrollOffset >= _laidOutMaxScrollExtent - 0.5;+ if (!_renderingEnabled) return;+ markNeedsLayout();+ _scheduleEditableRect();+ }++ /// Resolve the tail against the buffer and viewport of the next layout,+ /// rather than jumping to a ScrollPosition extent from the previous frame.+ void scrollToBottom() {+ final needsLayout = !_stickToBottom ||+ !hasSize ||+ (_maxScrollExtent - _scrollOffset).abs() > 0.5;+ _stickToBottom = true;+ if (_renderingEnabled && needsLayout) markNeedsLayout();+ }++ void _onFocusChange() {+ markNeedsPaint();+ _scheduleEditableRect();+ }++ void _onTerminalChange() {+ markNeedsLayout();+ _scheduleEditableRect();+ }++ void _onControllerUpdate() {+ if (_renderingEnabled) markNeedsLayout();+ }++ @override+ final isRepaintBoundary = true;++ @override+ void attach(PipelineOwner owner) {+ super.attach(owner);+ _offset.addListener(_onScroll);+ if (_renderingEnabled) _terminal.addListener(_onTerminalChange);+ _controller.addListener(_onControllerUpdate);+ _focusNode.addListener(_onFocusChange);+ }++ @override+ void detach() {+ super.detach();+ _offset.removeListener(_onScroll);+ _terminal.removeListener(_onTerminalChange);+ _controller.removeListener(_onControllerUpdate);+ _focusNode.removeListener(_onFocusChange);+ }++ @override+ bool hitTestSelf(Offset position) {+ return true;+ }++ @override+ void systemFontsDidChange() {+ _painter.clearFontCache();+ super.systemFontsDidChange();+ }++ @override+ void performLayout() {+ size = constraints.biggest;+ if (!_renderingEnabled) return;++ final followTail = _stickToBottom;+ _updateViewportSize();++ if (followTail) {+ // Correct before publishing the dimensions. A terminal redraw may empty+ // its history for one frame; publishing that short extent while pixels+ // still points into the old history starts a macOS bounce to the top.+ // That animation would keep scrolling even as the next output refills it.+ _offset.correctBy(_maxScrollExtent - _scrollOffset);+ }+ _updateScrollOffset();+ if (followTail) _stickToBottom = true;+ _laidOutMaxScrollExtent = _maxScrollExtent;+ _scheduleEditableRect();+ }++ /// Total height of the terminal in pixels. Includes scrollback buffer.+ double get _terminalHeight =>+ _terminal.buffer.lines.length * _painter.cellSize.height;++ /// The distance from the top of the terminal to the top of the viewport.+ // double get _scrollOffset => _offset.pixels;+ double get _scrollOffset {+ // return _offset.pixels ~/ _painter.cellSize.height * _painter.cellSize.height;+ return _offset.pixels;+ }++ /// The height of a terminal line in pixels. This includes the line spacing.+ /// Height of the entire terminal is expected to be a multiple of this value.+ double get lineHeight => _painter.cellSize.height;++ /// Get the top-left corner of the cell at [cellOffset] in pixels.+ Offset getOffset(CellOffset cellOffset) {+ final row = cellOffset.y;+ final col = cellOffset.x;+ final x = col * _painter.cellSize.width;+ final y = row * _painter.cellSize.height;+ return Offset(x + _padding.left, y + _padding.top - _scrollOffset);+ }++ /// Get the [CellOffset] of the cell that [offset] is in.+ CellOffset getCellOffset(Offset offset) {+ final x = offset.dx - _padding.left;+ final y = offset.dy - _padding.top + _scrollOffset;+ final row = y ~/ _painter.cellSize.height;+ final col = x ~/ _painter.cellSize.width;+ return CellOffset(+ col.clamp(0, _terminal.viewWidth - 1),+ row.clamp(0, _terminal.buffer.lines.length - 1),+ );+ }++ /// Selects entire words in the terminal that contains [from] and [to].+ void selectWord(Offset from, [Offset? to]) {+ final fromOffset = getCellOffset(from);+ final fromBoundary = _terminal.buffer.getWordBoundary(fromOffset);+ if (fromBoundary == null) return;+ if (to == null) {+ _controller.setSelection(+ _terminal.buffer.createAnchorFromOffset(fromBoundary.begin),+ _terminal.buffer.createAnchorFromOffset(fromBoundary.end),+ mode: SelectionMode.line,+ );+ } else {+ final toOffset = getCellOffset(to);+ final toBoundary = _terminal.buffer.getWordBoundary(toOffset);+ if (toBoundary == null) return;+ final range = fromBoundary.merge(toBoundary);+ _controller.setSelection(+ _terminal.buffer.createAnchorFromOffset(range.begin),+ _terminal.buffer.createAnchorFromOffset(range.end),+ mode: SelectionMode.line,+ );+ }+ }++ /// Selects characters in the terminal that starts from [from] to [to]. At+ /// least one cell is selected even if [from] and [to] are same.+ void selectCharacters(Offset from, [Offset? to]) {+ final fromPosition = getCellOffset(from);+ if (to == null) {+ _controller.setSelection(+ _terminal.buffer.createAnchorFromOffset(fromPosition),+ _terminal.buffer.createAnchorFromOffset(fromPosition),+ );+ } else {+ var toPosition = getCellOffset(to);+ if (toPosition.x >= fromPosition.x) {+ toPosition = CellOffset(toPosition.x + 1, toPosition.y);+ }+ _controller.setSelection(+ _terminal.buffer.createAnchorFromOffset(fromPosition),+ _terminal.buffer.createAnchorFromOffset(toPosition),+ );+ }+ }++ /// Send a mouse event at [offset] with [button] being currently in [buttonState].+ bool mouseEvent(+ TerminalMouseButton button,+ TerminalMouseButtonState buttonState,+ Offset offset,+ ) {+ final position = getCellOffset(offset);+ return _terminal.mouseInput(button, buttonState, position);+ }++ /// Layout can change the scroll offset and ancestors can move this view.+ /// Report the final caret once per frame, including when a retained view+ /// returns without fresh output. Unfocused terminals have no native caret.+ void _scheduleEditableRect() {+ if (_editableRectPending ||+ !attached ||+ !_renderingEnabled ||+ !_focusNode.hasFocus ||+ _onEditableRect == null) {+ return;+ }+ _editableRectPending = true;+ SchedulerBinding.instance.addPostFrameCallback((_) {+ _editableRectPending = false;+ if (!attached || !_renderingEnabled || !_focusNode.hasFocus || !hasSize) {+ return;+ }+ _notifyEditableRect();+ });+ }++ void _notifyEditableRect() {+ final cursor = localToGlobal(cursorOffset);++ final rect = Rect.fromLTRB(+ cursor.dx,+ cursor.dy,+ size.width,+ cursor.dy + _painter.cellSize.height,+ );++ final caretRect = cursor & _painter.cellSize;++ _onEditableRect?.call(rect, caretRect);+ }++ /// Update the viewport size in cells based on the current widget size in+ /// pixels.+ void _updateViewportSize() {+ if (size <= _painter.cellSize) {+ return;+ }++ final viewportSize = TerminalSize(+ size.width ~/ _painter.cellSize.width,+ _viewportHeight ~/ _painter.cellSize.height,+ );++ if (_viewportSize != viewportSize) {+ _viewportSize = viewportSize;+ }+ // A retained view may have received a replacement screen while hidden,+ // even when its own pixel dimensions did not change.+ _resizeTerminalIfNeeded();+ }++ /// Notify the underlying terminal that the viewport size has changed.+ void _resizeTerminalIfNeeded() {+ if (_renderingEnabled &&+ _autoResize &&+ !_resizeBuffer &&+ _viewportSize != null &&+ _reportedViewportSize != _viewportSize) {+ _reportedViewportSize = _viewportSize;+ // Shrinking a captured TUI locally can discard its latest rows when+ // its cursor is parked near the top. Keep the authoritative remote+ // cells while requesting a new grid; the next keyframe replaces them.+ _terminal.onResize?.call(+ _viewportSize!.width,+ _viewportSize!.height,+ _painter.cellSize.width.round(),+ _painter.cellSize.height.round(),+ );+ return;+ }+ if (_renderingEnabled &&+ _autoResize &&+ _resizeBuffer &&+ _viewportSize != null &&+ (_terminal.viewWidth != _viewportSize!.width ||+ _terminal.viewHeight != _viewportSize!.height)) {+ _terminal.resize(+ _viewportSize!.width,+ _viewportSize!.height,+ _painter.cellSize.width.round(),+ _painter.cellSize.height.round(),+ );+ }+ }++ /// Update the scroll offset based on the current terminal state. This should+ /// be called in [performLayout] after the viewport size has been updated.+ void _updateScrollOffset() {+ _offset.applyViewportDimension(_viewportHeight);+ _offset.applyContentDimensions(0, _maxScrollExtent);+ }++ bool get _isComposingText {+ return _composingText != null && _composingText!.isNotEmpty;+ }++ bool get _shouldShowCursor {+ return _terminal.cursorVisibleMode || _alwaysShowCursor || _isComposingText;+ }++ double get _viewportHeight {+ return size.height - _padding.vertical;+ }++ double get _maxScrollExtent {+ return max(_terminalHeight - _viewportHeight, 0.0);+ }++ double get _lineOffset {+ return -_scrollOffset + _padding.top;+ }++ /// The offset of the cursor from the top left corner of this render object.+ Offset get cursorOffset {+ return Offset(+ _terminal.buffer.cursorX * _painter.cellSize.width,+ _terminal.buffer.absoluteCursorY * _painter.cellSize.height + _lineOffset,+ );+ }++ Size get cellSize {+ return _painter.cellSize;+ }++ @override+ void paint(PaintingContext context, Offset offset) {+ _paint(context, offset);+ context.setWillChangeHint();+ }++ void _paint(PaintingContext context, Offset offset) {+ final canvas = context.canvas;++ // A terminal cell with the default background deliberately does not paint+ // its own fill (see TerminalPainter.paintCellBackground). That is fine+ // only when another paint pass has already cleared this layer. During an+ // incremental terminal/IME repaint it has not: old composition underlines,+ // cursors and glyphs survive until a full widget rebuild. Own the entire+ // render region here so every frame starts from the current app/terminal+ // background, then clip all terminal drawing to that region.+ final paintBounds = offset & size;+ canvas.save();+ canvas.clipRect(paintBounds);+ canvas.drawRect(+ paintBounds,+ Paint()..color = _painter.theme.background,+ );++ final lines = _terminal.buffer.lines;+ final charHeight = _painter.cellSize.height;++ final firstLineOffset = _scrollOffset - _padding.top;+ final lastLineOffset = _scrollOffset + size.height + _padding.bottom;++ final firstLine = firstLineOffset ~/ charHeight;+ final lastLine = lastLineOffset ~/ charHeight;++ final effectFirstLine = firstLine.clamp(0, lines.length - 1);+ final effectLastLine = lastLine.clamp(0, lines.length - 1);++ for (var i = effectFirstLine; i <= effectLastLine; i++) {+ _painter.paintLine(+ canvas,+ offset.translate(0, (i * charHeight + _lineOffset).truncateToDouble()),+ lines[i],+ );+ }++ if (_terminal.buffer.absoluteCursorY >= effectFirstLine &&+ _terminal.buffer.absoluteCursorY <= effectLastLine) {+ if (_isComposingText) {+ _paintComposingText(canvas, offset + cursorOffset);+ }++ if (_shouldShowCursor) {+ _painter.paintCursor(+ canvas,+ offset + cursorOffset,+ cursorType: _cursorType,+ hasFocus: _focusNode.hasFocus,+ );+ }+ }++ _paintHighlights(+ canvas,+ offset,+ _controller.highlights,+ effectFirstLine,+ effectLastLine,+ );++ if (_controller.selection != null) {+ _paintSelection(+ canvas,+ offset,+ _controller.selection!,+ effectFirstLine,+ effectLastLine,+ );+ }++ canvas.restore();+ }++ /// Paints the text that is currently being composed in IME to [canvas] at+ /// [offset]. [offset] is usually the cursor position.+ void _paintComposingText(Canvas canvas, Offset offset) {+ final composingText = _composingText;+ if (composingText == null) {+ return;+ }++ var startColumn = _terminal.buffer.cursorX - _composingBacktrackCells;+ var startLine = _terminal.buffer.absoluteCursorY;+ while (startColumn < 0 && startLine > 0) {+ startColumn += _terminal.viewWidth;+ startLine--;+ }+ final renderOrigin = offset - cursorOffset;+ final composingOffset = renderOrigin ++ Offset(+ startColumn.clamp(0, _terminal.viewWidth - 1).toDouble() *+ _painter.cellSize.width,+ startLine * _painter.cellSize.height + _lineOffset,+ );++ final style = _painter.textStyle.toTextStyle(+ color: _painter.resolveForegroundColor(_terminal.cursor.foreground),+ backgroundColor: _painter.theme.background,+ // Native macOS input can mark an entire uncommitted terminal buffer,+ // even with Telex disabled. Underlining that buffer makes ordinary input+ // look like a rendering artifact and does not match Terminal.app.+ underline: false,+ );++ // Do not use ParagraphBuilder with an empty placeholder for the leading+ // terminal cells. On macOS that run can retain the platform marked-text+ // decoration (a grey underline), despite the TextStyle above explicitly+ // selecting TextDecoration.none. Paint only the pre-edit run at its cell+ // position so an IME remains visible without styling ordinary terminal+ // input as marked/underlined text.+ final textPainter = TextPainter(+ text: TextSpan(+ text: composingText,+ style: style.copyWith(+ decoration: TextDecoration.none,+ decorationColor: const Color(0x00000000),+ ),+ ),+ textDirection: TextDirection.ltr,+ textScaler: _painter.textScaler,+ )..layout(+ maxWidth: (size.width - composingOffset.dx).clamp(0.0, size.width));++ textPainter.paint(canvas, composingOffset);+ textPainter.dispose();+ }++ void _paintSelection(+ Canvas canvas,+ Offset offset,+ BufferRange selection,+ int firstLine,+ int lastLine,+ ) {+ for (final segment in selection.toSegments()) {+ if (segment.line >= _terminal.buffer.lines.length) {+ break;+ }++ if (segment.line < firstLine) {+ continue;+ }++ if (segment.line > lastLine) {+ break;+ }++ _paintSegment(canvas, offset, segment, _painter.theme.selection);+ }+ }++ void _paintHighlights(+ Canvas canvas,+ Offset offset,+ List<TerminalHighlight> highlights,+ int firstLine,+ int lastLine,+ ) {+ for (var highlight in _controller.highlights) {+ final range = highlight.range?.normalized;++ if (range == null ||+ range.begin.y > lastLine ||+ range.end.y < firstLine) {+ continue;+ }++ for (var segment in range.toSegments()) {+ if (segment.line < firstLine) {+ continue;+ }++ if (segment.line > lastLine) {+ break;+ }++ _paintSegment(canvas, offset, segment, highlight.color);+ }+ }+ }++ // The render box's own paint offset (e.g. from an ancestor Padding) must be added here just like+ // paintLine/paintCursor already do — this was missing, so a selection/highlight rect was drawn in+ // the wrong place whenever this box's offset was non-zero, leaving trailing selected characters+ // rendered outside the highlighted box instead of inside it.+ @pragma('vm:prefer-inline')+ void _paintSegment(+ Canvas canvas,+ Offset offset,+ BufferSegment segment,+ Color color,+ ) {+ final start = segment.start ?? 0;+ final end = segment.end ?? _terminal.viewWidth;++ final startOffset = offset.translate(+ start * _painter.cellSize.width,+ segment.line * _painter.cellSize.height + _lineOffset,+ );++ _painter.paintHighlight(canvas, startOffset, end - start, color);+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart b/mobile/third_party/xterm/lib/src/ui/scroll_handler.dartnew file mode 100644index 000000000..ad6f0a565--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart@@ -0,0 +1,148 @@+import 'package:flutter/widgets.dart';+import 'package:xterm/core.dart';+import 'package:xterm/src/ui/infinite_scroll_view.dart';++/// Handles scrolling gestures in the alternate screen buffer. In alternate+/// screen buffer, the terminal don't have a scrollback buffer, instead, the+/// scroll gestures are converted to escape sequences based on the current+/// report mode declared by the application.+class TerminalScrollGestureHandler extends StatefulWidget {+ const TerminalScrollGestureHandler({+ super.key,+ required this.terminal,+ required this.getCellOffset,+ required this.getLineHeight,+ this.simulateScroll = true,+ this.onAltBufferScroll,+ required this.child,+ });++ final Terminal terminal;++ /// Returns the cell offset for the pixel offset.+ final CellOffset Function(Offset) getCellOffset;++ /// Returns the pixel height of lines in the terminal.+ final double Function() getLineHeight;++ /// Whether to simulate scroll events in the terminal when the application+ /// doesn't declare it supports mouse wheel events. true by default as it+ /// is the default behavior of most terminals.+ final bool simulateScroll;++ /// When set, takes over alt-buffer scroll entirely — [terminal].mouseInput/keyInput are never+ /// called, this is asked instead. For a program that owns terminal mouse-tracking but doesn't+ /// correctly handle wheel reports itself (confirmed live: Grok's CLI echoes the raw SGR escape+ /// bytes into its own prompt as literal characters instead of scrolling), the caller supplying+ /// this hook is expected to know a backend-native way to scroll instead (tmux copy-mode) and not+ /// need the emulator's own mouse/key simulation at all.+ final void Function(bool up)? onAltBufferScroll;++ final Widget child;++ @override+ State<TerminalScrollGestureHandler> createState() =>+ _TerminalScrollGestureHandlerState();+}++class _TerminalScrollGestureHandlerState+ extends State<TerminalScrollGestureHandler> {+ /// Whether the application is in alternate screen buffer. If false, then this+ /// widget does nothing.+ var isAltBuffer = false;++ /// The variable that tracks the line offset in last scroll event. Used to+ /// determine how many the scroll events should be sent to the terminal.+ var lastLineOffset = 0;++ /// This variable tracks the last offset where the scroll gesture started.+ /// Used to calculate the cell offset of the terminal mouse event.+ var lastPointerPosition = Offset.zero;++ @override+ void initState() {+ widget.terminal.addListener(_onTerminalUpdated);+ isAltBuffer = widget.terminal.isUsingAltBuffer;+ super.initState();+ }++ @override+ void dispose() {+ widget.terminal.removeListener(_onTerminalUpdated);+ super.dispose();+ }++ @override+ void didUpdateWidget(covariant TerminalScrollGestureHandler oldWidget) {+ if (oldWidget.terminal != widget.terminal) {+ oldWidget.terminal.removeListener(_onTerminalUpdated);+ widget.terminal.addListener(_onTerminalUpdated);+ isAltBuffer = widget.terminal.isUsingAltBuffer;+ }+ super.didUpdateWidget(oldWidget);+ }++ void _onTerminalUpdated() {+ if (isAltBuffer != widget.terminal.isUsingAltBuffer) {+ isAltBuffer = widget.terminal.isUsingAltBuffer;+ setState(() {});+ }+ }++ /// Send a single scroll event to the terminal. If [simulateScroll] is true,+ /// then if the application doesn't recognize mouse wheel events, this method+ /// will simulate scroll events by sending up/down arrow keys.+ void _sendScrollEvent(bool up) {+ final onAltBufferScroll = widget.onAltBufferScroll;+ if (onAltBufferScroll != null) {+ onAltBufferScroll(up);+ return;+ }++ final position = widget.getCellOffset(lastPointerPosition);++ final handled = widget.terminal.mouseInput(+ up ? TerminalMouseButton.wheelUp : TerminalMouseButton.wheelDown,+ TerminalMouseButtonState.down,+ position,+ );++ if (!handled && widget.simulateScroll) {+ widget.terminal.keyInput(+ up ? TerminalKey.arrowUp : TerminalKey.arrowDown,+ );+ }+ }++ void _onScroll(double offset) {+ final currentLineOffset = offset ~/ widget.getLineHeight();++ final delta = currentLineOffset - lastLineOffset;++ for (var i = 0; i < delta.abs(); i++) {+ _sendScrollEvent(delta < 0);+ }++ lastLineOffset = currentLineOffset;+ }++ @override+ Widget build(BuildContext context) {+ if (!isAltBuffer) {+ return widget.child;+ }++ return Listener(+ onPointerSignal: (event) {+ lastPointerPosition = event.position;+ },+ onPointerDown: (event) {+ lastPointerPosition = event.position;+ },+ child: InfiniteScrollView(+ onScroll: _onScroll,+ child: widget.child,+ ),+ );+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/selection_mode.dart b/mobile/third_party/xterm/lib/src/ui/selection_mode.dartnew file mode 100644index 000000000..aa3a5044b--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/selection_mode.dart@@ -0,0 +1,5 @@+enum SelectionMode {+ line,++ block,+}diff --git a/mobile/third_party/xterm/lib/src/ui/shortcut/actions.dart b/mobile/third_party/xterm/lib/src/ui/shortcut/actions.dartnew file mode 100644index 000000000..a06670b7d--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/shortcut/actions.dart@@ -0,0 +1,71 @@+import 'package:flutter/services.dart';+import 'package:flutter/widgets.dart';+import 'package:xterm/src/terminal.dart';+import 'package:xterm/src/ui/controller.dart';+import 'package:xterm/src/ui/selection_mode.dart';++class TerminalActions extends StatelessWidget {+ const TerminalActions({+ super.key,+ required this.terminal,+ required this.controller,+ required this.child,+ });++ final Terminal terminal;++ final TerminalController controller;++ final Widget child;++ @override+ Widget build(BuildContext context) {+ return Actions(+ actions: {+ PasteTextIntent: CallbackAction<PasteTextIntent>(+ onInvoke: (intent) async {+ final data = await Clipboard.getData(Clipboard.kTextPlain);+ final text = data?.text;+ if (text != null) {+ terminal.paste(text);+ controller.clearSelection();+ }+ return null;+ },+ ),+ CopySelectionTextIntent: CallbackAction<CopySelectionTextIntent>(+ onInvoke: (intent) async {+ final selection = controller.selection;++ if (selection == null) {+ return;+ }++ final text = terminal.buffer.getText(selection);++ await Clipboard.setData(ClipboardData(text: text));++ return null;+ },+ ),+ SelectAllTextIntent: CallbackAction<SelectAllTextIntent>(+ onInvoke: (intent) {+ controller.setSelection(+ terminal.buffer.createAnchor(+ 0,+ terminal.buffer.height - terminal.viewHeight,+ ),+ terminal.buffer.createAnchor(+ terminal.viewWidth,+ terminal.buffer.height - 1,+ ),+ mode: SelectionMode.line,+ );+ return null;+ },+ ),+ },+ child: child,+ );+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/shortcut/shortcuts.dart b/mobile/third_party/xterm/lib/src/ui/shortcut/shortcuts.dartnew file mode 100644index 000000000..042ee156b--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/shortcut/shortcuts.dart@@ -0,0 +1,34 @@+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:flutter/widgets.dart';++Map<ShortcutActivator, Intent> get defaultTerminalShortcuts {+ switch (defaultTargetPlatform) {+ case TargetPlatform.android:+ case TargetPlatform.fuchsia:+ case TargetPlatform.linux:+ case TargetPlatform.windows:+ return _defaultShortcuts;+ case TargetPlatform.iOS:+ case TargetPlatform.macOS:+ return _defaultAppleShortcuts;+ }+}++final _defaultShortcuts = {+ SingleActivator(LogicalKeyboardKey.keyC, control: true, shift: true):+ CopySelectionTextIntent.copy,+ SingleActivator(LogicalKeyboardKey.keyV, control: true):+ const PasteTextIntent(SelectionChangedCause.keyboard),+ SingleActivator(LogicalKeyboardKey.keyA, control: true):+ const SelectAllTextIntent(SelectionChangedCause.keyboard),+};++final _defaultAppleShortcuts = {+ SingleActivator(LogicalKeyboardKey.keyC, meta: true):+ CopySelectionTextIntent.copy,+ SingleActivator(LogicalKeyboardKey.keyV, meta: true):+ const PasteTextIntent(SelectionChangedCause.keyboard),+ SingleActivator(LogicalKeyboardKey.keyA, meta: true):+ const SelectAllTextIntent(SelectionChangedCause.keyboard),+};diff --git a/mobile/third_party/xterm/lib/src/ui/terminal_size.dart b/mobile/third_party/xterm/lib/src/ui/terminal_size.dartnew file mode 100644index 000000000..07258c9ac--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/terminal_size.dart@@ -0,0 +1,24 @@+class TerminalSize {+ final int width;++ final int height;++ const TerminalSize(this.width, this.height);++ @override+ String toString() => 'TerminalSize($width, $height)';++ @override+ bool operator ==(Object other) {+ if (identical(this, other)) {+ return true;+ }+ if (other is! TerminalSize) {+ return false;+ }+ return other.width == width && other.height == height;+ }++ @override+ int get hashCode => width.hashCode ^ height.hashCode;+}diff --git a/mobile/third_party/xterm/lib/src/ui/terminal_text_style.dart b/mobile/third_party/xterm/lib/src/ui/terminal_text_style.dartnew file mode 100644index 000000000..51026a3a0--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/terminal_text_style.dart@@ -0,0 +1,90 @@+import 'package:flutter/widgets.dart';++const _kDefaultFontSize = 13.0;++const _kDefaultHeight = 1.2;++const _kDefaultFontFamily = 'monospace';++const _kDefaultFontFamilyFallback = [+ 'Menlo',+ 'Monaco',+ 'Consolas',+ 'Liberation Mono',+ 'Courier New',+ 'Noto Sans Mono CJK SC',+ 'Noto Sans Mono CJK TC',+ 'Noto Sans Mono CJK KR',+ 'Noto Sans Mono CJK JP',+ 'Noto Sans Mono CJK HK',+ 'Noto Color Emoji',+ 'Noto Sans Symbols',+ 'monospace',+ 'sans-serif',+];++class TerminalStyle {+ const TerminalStyle({+ this.fontSize = _kDefaultFontSize,+ this.height = _kDefaultHeight,+ this.fontFamily = _kDefaultFontFamily,+ this.fontFamilyFallback = _kDefaultFontFamilyFallback,+ });++ factory TerminalStyle.fromTextStyle(TextStyle textStyle) {+ return TerminalStyle(+ fontSize: textStyle.fontSize ?? _kDefaultFontSize,+ height: textStyle.height ?? _kDefaultHeight,+ fontFamily: textStyle.fontFamily ??+ textStyle.fontFamilyFallback?.first ??+ _kDefaultFontFamily,+ fontFamilyFallback:+ textStyle.fontFamilyFallback ?? _kDefaultFontFamilyFallback,+ );+ }++ final double fontSize;++ final double height;++ final String fontFamily;++ final List<String> fontFamilyFallback;++ TextStyle toTextStyle({+ Color? color,+ Color? backgroundColor,+ bool bold = false,+ bool italic = false,+ bool underline = false,+ }) {+ return TextStyle(+ fontSize: fontSize,+ height: height,+ fontFamily: fontFamily,+ fontFamilyFallback: fontFamilyFallback,+ color: color,+ backgroundColor: backgroundColor,+ // Terminal.app's ANSI emphasis is optically closer to SF Mono Semibold+ // than Bold. Using w700 makes highlighted runs noticeably heavier than+ // the same pane rendered by the native terminal.+ fontWeight: bold ? FontWeight.w600 : FontWeight.normal,+ fontStyle: italic ? FontStyle.italic : FontStyle.normal,+ decoration: underline ? TextDecoration.underline : TextDecoration.none,+ );+ }++ TerminalStyle copyWith({+ double? fontSize,+ double? height,+ String? fontFamily,+ List<String>? fontFamilyFallback,+ }) {+ return TerminalStyle(+ fontSize: fontSize ?? this.fontSize,+ height: height ?? this.height,+ fontFamily: fontFamily ?? this.fontFamily,+ fontFamilyFallback: fontFamilyFallback ?? this.fontFamilyFallback,+ );+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/terminal_theme.dart b/mobile/third_party/xterm/lib/src/ui/terminal_theme.dartnew file mode 100644index 000000000..0b70e422e--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/terminal_theme.dart@@ -0,0 +1,57 @@+import 'package:flutter/widgets.dart';++class TerminalTheme {+ const TerminalTheme({+ required this.cursor,+ required this.selection,+ required this.foreground,+ required this.background,+ required this.black,+ required this.white,+ required this.red,+ required this.green,+ required this.yellow,+ required this.blue,+ required this.magenta,+ required this.cyan,+ required this.brightBlack,+ required this.brightRed,+ required this.brightGreen,+ required this.brightYellow,+ required this.brightBlue,+ required this.brightMagenta,+ required this.brightCyan,+ required this.brightWhite,+ required this.searchHitBackground,+ required this.searchHitBackgroundCurrent,+ required this.searchHitForeground,+ });++ final Color cursor;+ final Color selection;++ final Color foreground;+ final Color background;++ final Color black;+ final Color red;+ final Color green;+ final Color yellow;+ final Color blue;+ final Color magenta;+ final Color cyan;+ final Color white;++ final Color brightBlack;+ final Color brightRed;+ final Color brightGreen;+ final Color brightYellow;+ final Color brightBlue;+ final Color brightMagenta;+ final Color brightCyan;+ final Color brightWhite;++ final Color searchHitBackground;+ final Color searchHitBackgroundCurrent;+ final Color searchHitForeground;+}diff --git a/mobile/third_party/xterm/lib/src/ui/themes.dart b/mobile/third_party/xterm/lib/src/ui/themes.dartnew file mode 100644index 000000000..6c5e3e856--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/themes.dart@@ -0,0 +1,56 @@+import 'package:flutter/widgets.dart';+import 'package:xterm/src/ui/terminal_theme.dart';++class TerminalThemes {+ static const defaultTheme = TerminalTheme(+ cursor: Color(0XAAAEAFAD),+ selection: Color(0XAAAEAFAD),+ foreground: Color(0XFFCCCCCC),+ background: Color(0XFF1E1E1E),+ black: Color(0XFF000000),+ red: Color(0XFFCD3131),+ green: Color(0XFF0DBC79),+ yellow: Color(0XFFE5E510),+ blue: Color(0XFF2472C8),+ magenta: Color(0XFFBC3FBC),+ cyan: Color(0XFF11A8CD),+ white: Color(0XFFE5E5E5),+ brightBlack: Color(0XFF666666),+ brightRed: Color(0XFFF14C4C),+ brightGreen: Color(0XFF23D18B),+ brightYellow: Color(0XFFF5F543),+ brightBlue: Color(0XFF3B8EEA),+ brightMagenta: Color(0XFFD670D6),+ brightCyan: Color(0XFF29B8DB),+ brightWhite: Color(0XFFFFFFFF),+ searchHitBackground: Color(0XFFFFFF2B),+ searchHitBackgroundCurrent: Color(0XFF31FF26),+ searchHitForeground: Color(0XFF000000),+ );++ static const whiteOnBlack = TerminalTheme(+ cursor: Color(0XFFAEAFAD),+ selection: Color(0XFFAEAFAD),+ foreground: Color(0XFFFFFFFF),+ background: Color(0XFF000000),+ black: Color(0XFF000000),+ red: Color(0XFFCD3131),+ green: Color(0XFF0DBC79),+ yellow: Color(0XFFE5E510),+ blue: Color(0XFF2472C8),+ magenta: Color(0XFFBC3FBC),+ cyan: Color(0XFF11A8CD),+ white: Color(0XFFE5E5E5),+ brightBlack: Color(0XFF666666),+ brightRed: Color(0XFFF14C4C),+ brightGreen: Color(0XFF23D18B),+ brightYellow: Color(0XFFF5F543),+ brightBlue: Color(0XFF3B8EEA),+ brightMagenta: Color(0XFFD670D6),+ brightCyan: Color(0XFF29B8DB),+ brightWhite: Color(0XFFFFFFFF),+ searchHitBackground: Color(0XFFFFFF2B),+ searchHitBackgroundCurrent: Color(0XFF31FF26),+ searchHitForeground: Color(0XFF000000),+ );+}diff --git a/mobile/third_party/xterm/lib/src/utils/ascii.dart b/mobile/third_party/xterm/lib/src/utils/ascii.dartnew file mode 100644index 000000000..b5a67ab60--- /dev/null+++ b/mobile/third_party/xterm/lib/src/utils/ascii.dart@@ -0,0 +1,403 @@+// ignore_for_file: constant_identifier_names++abstract class Ascii {+ /*+ * Helper functions+ */++ static bool isNonPrintable(int c) {+ return c < 32 || c == 127;+ }++ /*+ * Non-printable ASCII characters+ */++ /// Null character+ static const NULL = 00;++ /// Start of Header+ static const SOH = 01;++ /// Start of Text+ static const STX = 02;++ /// End of Text, hearts card suit+ static const ETX = 03;++ /// End of Transmission, diamonds card suit+ static const EOT = 04;++ /// Enquiry, clubs card suit+ static const ENQ = 05;++ /// Acknowledgement, spade card suit+ static const ACK = 06;++ /// Bell+ static const BEL = 07;++ /// Backspace+ static const BS = 08;++ /// Horizontal Tab+ static const HT = 09;++ /// Line feed+ static const LF = 10;++ /// Vertical Tab, male symbol, symbol for Mars+ static const VT = 11;++ /// Form feed, female symbol, symbol for Venus+ static const FF = 12;++ /// Carriage return+ static const CR = 13;++ /// Shift Out+ static const SO = 14;++ /// Shift In+ static const SI = 15;++ /// Data link escape+ static const DLE = 16;++ /// Device control 1+ static const DC1 = 17;++ /// Device control 2+ static const DC2 = 18;++ /// Device control 3+ static const DC3 = 19;++ /// Device control 4+ static const DC4 = 20;++ /// NAK Negative-acknowledge+ static const NAK = 21;++ /// Synchronous idle+ static const SYN = 22;++ /// End of trans. block+ static const ETB = 23;++ /// Cancel+ static const CAN = 24;++ /// End of medium+ static const EM = 25;++ /// Substitute+ static const SUB = 26;++ /// Escape+ static const ESC = 27;++ /// File separator+ static const FS = 28;++ /// Group separator+ static const GS = 29;++ /// Record separator+ static const RS = 30;++ /// Unit separator+ static const US = 31;++ /// Delete+ static const DEL = 127;++ /*+ * Printable ASCII characters+ */++ /// Space " "+ static const space = 32;++ /// Exclamation mark "!"+ static const exclamationMark = 33;++ /// Double quotes '"'+ static const doubleQuotes = 34;++ /// Number sign '#'+ static const numberSign = 35;++ /// Dollar sign '$'+ static const dollarSign = 36;++ /// Percent sign '%'+ static const percentSign = 37;++ /// Ampersand '&'+ static const ampersand = 38;++ /// Single quote "'"+ static const singleQuote = 39;++ /// round brackets or parentheses, opening round bracket '('+ static const openParentheses = 40;++ /// parentheses or round brackets, closing parentheses ')'+ static const closeParentheses = 41;++ /// Asterisk '*'+ static const asterisk = 42;++ /// Plus sign '+'+ static const plus = 43;++ /// Comma ","+ static const comma = 44;++ /// Hyphen , minus sign '-'+ static const minus = 45;++ /// Dot, full stop '.'+ static const dot = 46;++ /// Slash , forward slash , fraction bar , division slash '/'+ static const slash = 47;++ /// number zero+ static const num0 = 48;++ /// number one+ static const num1 = 49;++ /// number two+ static const num2 = 50;++ /// number three+ static const num3 = 51;++ /// number four+ static const num4 = 52;++ /// number five+ static const num5 = 53;++ /// number six+ static const num6 = 54;++ /// number seven+ static const num7 = 55;++ /// number eight+ static const num8 = 56;++ /// number nine+ static const num9 = 57;++ /// Colon ':'+ static const colon = 58;++ /// Semicolon ';'+ static const semicolon = 59;++ /// Less-than sign '<'+ static const lessThan = 60;++ /// Equals sign '='+ static const equal = 61;++ /// Greater-than sign ; Inequality sign '>'+ static const greaterThan = 62;++ /// Question mark '?'+ static const questionMark = 63;++ /// At sign '@'+ static const atSign = 64;++ /// Capital letter A+ static const A = 65;++ /// Capital letter B+ static const B = 66;++ /// Capital letter C+ static const C = 67;++ /// Capital letter D+ static const D = 68;++ /// Capital letter E+ static const E = 69;++ /// Capital letter F+ static const F = 70;++ /// Capital letter G+ static const G = 71;++ /// Capital letter H+ static const H = 72;++ /// Capital letter I+ static const I = 73;++ /// Capital letter J+ static const J = 74;++ /// Capital letter K+ static const K = 75;++ /// Capital letter L+ static const L = 76;++ /// Capital letter M+ static const M = 77;++ /// Capital letter N+ static const N = 78;++ /// Capital letter O+ static const O = 79;++ /// Capital letter P+ static const P = 80;++ /// Capital letter Q+ static const Q = 81;++ /// Capital letter R+ static const R = 82;++ /// Capital letter S+ static const S = 83;++ /// Capital letter T+ static const T = 84;++ /// Capital letter U+ static const U = 85;++ /// Capital letter V+ static const V = 86;++ /// Capital letter W+ static const W = 87;++ /// Capital letter X+ static const X = 88;++ /// Capital letter Y+ static const Y = 89;++ /// Capital letter Z+ static const Z = 90;++ /// square brackets or box brackets, opening bracket '['+ static const openBracket = 91;++ /// Backslash , reverse slash '\\'+ static const backslash = 92;++ /// box brackets or square brackets, closing bracket ']'+ static const closeBracket = 93;++ /// Circumflex accent or Caret '^'+ static const caret = 94;++ /// underscore , understrike , underbar or low line '_'+ static const underscore = 95;++ /// Grave accent '`'+ static const graveAccent = 96;++ /// Lowercase letter a , minuscule a+ static const a = 97;++ /// Lowercase letter b , minuscule b+ static const b = 98;++ /// Lowercase letter c , minuscule c+ static const c = 99;++ /// Lowercase letter d , minuscule d+ static const d = 100;++ /// Lowercase letter e , minuscule e+ static const e = 101;++ /// Lowercase letter f , minuscule f+ static const f = 102;++ /// Lowercase letter g , minuscule g+ static const g = 103;++ /// Lowercase letter h , minuscule h+ static const h = 104;++ /// Lowercase letter i , minuscule i+ static const i = 105;++ /// Lowercase letter j , minuscule j+ static const j = 106;++ /// Lowercase letter k , minuscule k+ static const k = 107;++ /// Lowercase letter l , minuscule l+ static const l = 108;++ /// Lowercase letter m , minuscule m+ static const m = 109;++ /// Lowercase letter n , minuscule n+ static const n = 110;++ /// Lowercase letter o , minuscule o+ static const o = 111;++ /// Lowercase letter p , minuscule p+ static const p = 112;++ /// Lowercase letter q , minuscule q+ static const q = 113;++ /// Lowercase letter r , minuscule r+ static const r = 114;++ /// Lowercase letter s , minuscule s+ static const s = 115;++ /// Lowercase letter t , minuscule t+ static const t = 116;++ /// Lowercase letter u , minuscule u+ static const u = 117;++ /// Lowercase letter v , minuscule v+ static const v = 118;++ /// Lowercase letter w , minuscule w+ static const w = 119;++ /// Lowercase letter x , minuscule x+ static const x = 120;++ /// Lowercase letter y , minuscule y+ static const y = 121;++ /// Lowercase letter z , minuscule z+ static const z = 122;++ /// braces or curly brackets, opening braces '{'+ static const openBrace = 123;++ /// vertical-bar, vbar, vertical line or vertical slash '|'+ static const verticalBar = 124;++ /// curly brackets or braces, closing curly brackets '}'+ static const closeBrace = 125;++ /// Tilde ; swung dash '~'+ static const tilde = 126;+}diff --git a/mobile/third_party/xterm/lib/src/utils/byte_consumer.dart b/mobile/third_party/xterm/lib/src/utils/byte_consumer.dartnew file mode 100644index 000000000..4a2ad382c--- /dev/null+++ b/mobile/third_party/xterm/lib/src/utils/byte_consumer.dart@@ -0,0 +1,107 @@+import 'dart:collection';++class ByteConsumer {+ final _queue = ListQueue<List<int>>();++ final _consumed = ListQueue<List<int>>();++ var _currentOffset = 0;++ var _length = 0;++ var _totalConsumed = 0;++ void add(String data) {+ if (data.isEmpty) return;+ final runes = data.runes.toList(growable: false);+ _queue.addLast(runes);+ _length += runes.length;+ }++ int peek() {+ final data = _queue.first;+ if (_currentOffset < data.length) {+ return data[_currentOffset];+ } else {+ final result = consume();+ rollback();+ return result;+ }+ }++ int consume() {+ final data = _queue.first;++ if (_currentOffset >= data.length) {+ _consumed.add(_queue.removeFirst());+ _currentOffset -= data.length;+ return consume();+ }++ _length--;+ _totalConsumed++;+ return data[_currentOffset++];+ }++ /// Rolls back the last [n] call.+ void rollback([int n = 1]) {+ _currentOffset -= n;+ _totalConsumed -= n;+ _length += n;+ while (_currentOffset < 0) {+ final rollback = _consumed.removeLast();+ _queue.addFirst(rollback);+ _currentOffset += rollback.length;+ }+ }++ /// Rolls back to the state when this consumer had [length] bytes.+ void rollbackTo(int length) {+ rollback(length - _length);+ }++ int get length => _length;++ int get totalConsumed => _totalConsumed;++ bool get isEmpty => _length == 0;++ bool get isNotEmpty => _length != 0;++ /// Unreferences data blocks that have been consumed. After calling this+ /// method, the consumer will not be able to roll back to consumed blocks.+ void unrefConsumedBlocks() {+ _consumed.clear();+ }++ /// Resets the consumer to its initial state.+ void reset() {+ _queue.clear();+ _consumed.clear();+ _currentOffset = 0;+ _totalConsumed = 0;+ _length = 0;+ }+}++// void main() {+// final consumer = ByteConsumer();+// consumer.add(Uint8List.fromList([1, 2, 3]));+// consumer.add(Uint8List.fromList([4, 5, 6]));++// while (consumer.isNotEmpty) {+// print(consumer.consume());+// }++// consumer.rollback(5);++// while (consumer.isNotEmpty) {+// print(consumer.consume());+// }++// consumer.rollbackTo(3);++// while (consumer.isNotEmpty) {+// print(consumer.consume());+// }+// }diff --git a/mobile/third_party/xterm/lib/src/utils/char_code.dart b/mobile/third_party/xterm/lib/src/utils/char_code.dartnew file mode 100644index 000000000..9eb79e0ac--- /dev/null+++ b/mobile/third_party/xterm/lib/src/utils/char_code.dart@@ -0,0 +1,5 @@+extension StringCharCode on String {+ int get charCode {+ return codeUnitAt(0);+ }+}diff --git a/mobile/third_party/xterm/lib/src/utils/circular_buffer.dart b/mobile/third_party/xterm/lib/src/utils/circular_buffer.dartnew file mode 100644index 000000000..2edcc0468--- /dev/null+++ b/mobile/third_party/xterm/lib/src/utils/circular_buffer.dart@@ -0,0 +1,339 @@+/// A circular buffer in which elements know their index in the buffer.+class IndexAwareCircularBuffer<T extends IndexedItem> {+ /// Creates a new circular list with the specified [maxLength].+ IndexAwareCircularBuffer(int maxLength)+ : _array = List<T?>.filled(maxLength, null);++ /// The backing array for this list. Length is always equal to [maxLength].+ late List<T?> _array;++ /// The number of elements in the list. This is always less than or equal to+ /// [maxLength].+ var _length = 0;++ /// The index of the first element in [_array].+ var _startIndex = 0;++ /// The start index of this list, including items that has been dropped in+ /// overflow+ var _absoluteStartIndex = 0;++ /// Gets the cyclic index for the specified regular index. The cyclic index+ /// can then be used on the backing array to get the element associated with+ /// the regular index.+ @pragma('vm:prefer-inline')+ int _getCyclicIndex(int index) {+ return (_startIndex + index) % _array.length;+ }++ /// Removes the element at [index] from the list.+ @pragma('vm:prefer-inline')+ void _dropChild(int index) {+ final cyclicIndex = _getCyclicIndex(index);+ _array[cyclicIndex]?._detach();+ _array[cyclicIndex] = null;+ }++ /// Adds the specified [child] to the list at the specified [index].+ @pragma('vm:prefer-inline')+ void _adoptChild(int index, T child) {+ final cyclicIndex = _getCyclicIndex(index);+ _array[cyclicIndex]?._detach();+ _array[cyclicIndex] = child.._attach(this, index);+ }++ /// Moves the element at [fromIndex] to [toIndex]. Both indexes should be+ /// less than [maxLength].+ @pragma('vm:prefer-inline')+ void _moveChild(int fromIndex, int toIndex) {+ final fromCyclicIndex = _getCyclicIndex(fromIndex);+ final toCyclicIndex = _getCyclicIndex(toIndex);+ _array[toCyclicIndex]?._detach();+ _array[toCyclicIndex] = _array[fromCyclicIndex]?.._move(toIndex);+ _array[fromCyclicIndex] = null;+ }++ /// Gets the element at the specified [index] in the list.+ @pragma('vm:prefer-inline')+ T? _getChild(int index) {+ return _array[_getCyclicIndex(index)];+ }++ /// The number of elements that can be stored in the list.+ int get maxLength {+ return _array.length;+ }++ /// Sets the number of elements that can be stored in the list. This operation+ /// is relatively expensive, as it requires the backing array to be+ /// reallocated.+ set maxLength(int value) {+ if (value <= 0) {+ throw ArgumentError.value(value, 'value', "maxLength can't be negative!");+ }++ if (value == _array.length) return;++ // Reconstruct array, starting at index 0. Only transfer values from the+ // indexes 0 to length.+ final newArray = List<T?>.generate(+ value,+ (index) => index < _length ? _getChild(index) : null,+ );++ _startIndex = 0;+ _array = newArray;+ }++ /// Number of elements in the list.+ int get length {+ return _length;+ }++ /// Iterates over the list and calls [callback] for each element.+ void forEach(void Function(T item) callback) {+ final length = _length;+ for (int i = 0; i < length; i++) {+ callback(_getChild(i)!);+ }+ }++ /// Gets the element at the specified [index] in the list. Throws if the+ /// index is out of bounds.+ T operator [](int index) {+ RangeError.checkValueInInterval(index, 0, length - 1, 'index');+ return _getChild(index)!;+ }++ /// Sets the element at the specified [index] in the list. Throws if the+ /// index is out of bounds.+ operator []=(int index, T value) {+ RangeError.checkValueInInterval(index, 0, length - 1, 'index');+ _adoptChild(index, value);+ }++ /// Atomically replaces a same-length range.+ ///+ /// This is required when [replacement] contains items that already belong to+ /// this buffer. Repeated `operator []=` assignments temporarily leave the+ /// same item in two slots; overwriting the source slot then detaches the item+ /// that was just adopted into the destination slot.+ void replaceRange(int index, List<T> replacement) {+ if (replacement.isEmpty) return;+ RangeError.checkValueInInterval(index, 0, length - 1, 'index');+ RangeError.checkValueInInterval(+ index + replacement.length - 1,+ 0,+ length - 1,+ 'replacement',+ );++ for (var offset = 0; offset < replacement.length; offset++) {+ _dropChild(index + offset);+ }+ for (var offset = 0; offset < replacement.length; offset++) {+ _adoptChild(index + offset, replacement[offset]);+ }+ }++ /// Removes all elements from the list.+ void clear() {+ for (var i = 0; i < _length; i++) {+ _dropChild(i);+ }+ _startIndex = 0;+ _length = 0;+ }++ /// Adds all elements in [items] to the list.+ void pushAll(Iterable<T> items) {+ for (var element in items) {+ push(element);+ }+ }++ /// Adds [value] to the end of the list. May cause the first element to be+ /// trimmed if the list is full.+ void push(T value) {+ _adoptChild(_length, value);++ if (_length == _array.length) {+ // When the list is full, we trim the first element+ _startIndex++;+ _absoluteStartIndex++;+ if (_startIndex == _array.length) {+ _startIndex = 0;+ }+ } else {+ // When the list is not full, we just increase the length+ _length++;+ }+ }++ /// Removes and returns the last value on the list, throws if the list is+ /// empty.+ T pop() {+ assert(_length > 0, 'Cannot pop from an empty list');+ final result = _getChild(_length - 1);+ _dropChild(_length - 1);+ _length--;+ return result!;+ }++ /// Deletes [count] elements starting at [index], shifting all elements after+ /// [index] to the left.+ void remove(int index, [int count = 1]) {+ if (count > 0) {+ if (index + count >= _length) {+ count = _length - index;+ }+ for (var i = index; i < _length - count; i++) {+ _moveChild(i + count, i);+ }+ for (var i = _length - count; i < _length; i++) {+ _dropChild(i);+ }+ _length -= count;+ }+ }++ /// Inserts [item] at [index], shifting all elements after [index] to the+ /// right. May cause the first element to be trimmed if the list is full.+ void insert(int index, T item) {+ RangeError.checkValueInInterval(index, 0, _length, 'index');++ if (index == _length) {+ return push(item);+ }++ if (index == 0 && _length >= _array.length) {+ // when something is inserted at index 0 and the list is full then+ // the new value immediately gets removed => nothing changes+ return;+ }++ for (var i = _length - 1; i >= index; i--) {+ _moveChild(i, i + 1);+ }++ _adoptChild(index, item);++ if (_length >= _array.length) {+ _startIndex += 1;+ _absoluteStartIndex += 1;+ } else {+ _length++;+ }+ }++ /// Inserts [items] at [index] in order.+ void insertAll(int index, List<T> items) {+ for (var i = items.length - 1; i >= 0; i--) {+ insert(index, items[i]);+ // when the list is full then we have to move the index down+ // as newly inserted values remove values with a lower index+ if (_length >= _array.length) {+ index--;+ if (index < 0) {+ return;+ }+ }+ }+ }++ /// Removes [count] elements starting at [index], shifting all elements after+ /// [index] to the left.+ ///+ /// This method is cheap since it does not actually modify the list, but+ /// instead just adjusts the start index and length.+ void trimStart(int count) {+ if (count > _length) count = _length;+ _startIndex += count;+ _startIndex %= _array.length;+ _length -= count;+ }++ /// Replaces all elements in the list with [replacement].+ void replaceWith(List<T> replacement) {+ for (var i = 0; i < _length; i++) {+ _dropChild(i);+ }++ var copyStart = 0;+ if (replacement.length > maxLength) {+ copyStart = replacement.length - maxLength;+ }++ for (var i = 0; i < copyStart; i++) {+ _dropChild(i);+ }++ final copyLength = replacement.length - copyStart;+ for (var i = 0; i < copyLength; i++) {+ _adoptChild(i, replacement[copyStart + i]);+ }++ _startIndex = 0;+ _length = copyLength;+ }++ /// Replaces the element at [index] with [value] and returns the replaced+ /// item.+ T swap(int index, T value) {+ final result = _getChild(index);+ _adoptChild(index, value);+ return result!;+ }++ /// Whether adding another element would cause the first element to be+ /// trimmed.+ bool get isFull => length == maxLength;++ /// Returns a list containing all elements in the list.+ List<T> toList() {+ return List<T>.generate(length, (index) => this[index]);+ }++ String debugDump() {+ final buffer = StringBuffer();+ buffer.writeln('CircularList:');+ for (var i = 0; i < _length; i++) {+ final child = _getChild(i);+ buffer.writeln(' $i: $child');+ }+ return buffer.toString();+ }+}++mixin IndexedItem {+ IndexAwareCircularBuffer? _owner;++ int? _absoluteIndex;++ /// The index of this item in the buffer. Must only be accessed when+ /// [attached] is true.+ int get index => _absoluteIndex! - _owner!._absoluteStartIndex;++ /// Whether this item is currently stored in a buffer.+ bool get attached => _owner != null;++ /// Sets the owner and index of this item. This is called by the buffer when+ /// the item is adopted.+ void _attach(IndexAwareCircularBuffer owner, int index) {+ _owner = owner;+ _absoluteIndex = owner._absoluteStartIndex + index;+ }++ /// Marks this item as detached from a buffer. This is called after the item+ /// has been removed from the buffer.+ void _detach() {+ _owner = null;+ _absoluteIndex = null;+ }++ /// Moves this item to [newIndex] in the buffer.+ void _move(int newIndex) {+ assert(attached);+ _absoluteIndex = _owner!._absoluteStartIndex + newIndex;+ }+}diff --git a/mobile/third_party/xterm/lib/src/utils/debugger.dart b/mobile/third_party/xterm/lib/src/utils/debugger.dartnew file mode 100644index 000000000..303bbbbe8--- /dev/null+++ b/mobile/third_party/xterm/lib/src/utils/debugger.dart@@ -0,0 +1,595 @@+import 'package:xterm/src/core/escape/handler.dart';+import 'package:xterm/src/core/escape/parser.dart';+import 'package:xterm/src/core/mouse/mode.dart';+import 'package:xterm/src/base/observable.dart';++class TerminalCommand {+ TerminalCommand(+ this.start,+ this.end,+ this.chars,+ this.escapedChars,+ this.explanation,+ this.error,+ );++ final int start;++ final int end;++ final String chars;++ final String escapedChars;++ final List<String> explanation;++ final bool error;+}++class TerminalDebugger with Observable {+ late final _parser = EscapeParser(_handler);++ late final _handler = _TerminalDebuggerHandler(recordCommand);++ final recorded = <int>[];++ final commands = <TerminalCommand>[];++ void write(String chunk) {+ recorded.addAll(chunk.runes);+ _parser.write(chunk);+ notifyListeners();+ }++ void recordCommand(String explanation, {bool error = false}) {+ final start = _parser.tokenBegin;+ final end = _parser.tokenEnd;++ if (commands.isNotEmpty && commands.last.end == end) {+ commands.last.explanation.add(explanation);+ } else {+ final charCodes = recorded.sublist(start, end);+ final chars = String.fromCharCodes(charCodes);+ final escapedChars = _escape(chars);+ commands.add(+ TerminalCommand(start, end, chars, escapedChars, [explanation], error),+ );+ }+ }++ String getRecord(TerminalCommand command) {+ final charCodes = recorded.sublist(0, command.end);+ return String.fromCharCodes(charCodes);+ }++ static String _escape(String chars) {+ final escaped = StringBuffer();+ for (final char in chars.runes) {+ if (char == 0x1b) {+ escaped.write('ESC');+ } else if (char < 32) {+ escaped.write('^0x${char.toRadixString(16)}');+ } else if (char == 127) {+ escaped.write('^?');+ } else {+ escaped.writeCharCode(char);+ }+ }+ return escaped.toString();+ }+}++class _TerminalDebuggerHandler implements EscapeHandler {+ _TerminalDebuggerHandler(this.onCommand);++ final void Function(String explanation, {bool error}) onCommand;++ @override+ void writeChar(int char) {+ onCommand('writeChar(${String.fromCharCode(char)})');+ }++ /* SBC */++ @override+ void bell() {+ onCommand('bell');+ }++ @override+ void backspaceReturn() {+ onCommand('backspaceReturn');+ }++ @override+ void tab() {+ onCommand('tab');+ }++ @override+ void lineFeed() {+ onCommand('lineFeed');+ }++ @override+ void carriageReturn() {+ onCommand('carriageReturn');+ }++ @override+ void shiftOut() {+ onCommand('shiftOut');+ }++ @override+ void shiftIn() {+ onCommand('shiftIn');+ }++ @override+ void unknownSBC(int char) {+ onCommand('unkownSBC(${String.fromCharCode(char)})', error: true);+ }++ /* ANSI sequence */++ @override+ void saveCursor() {+ onCommand('saveCursor');+ }++ @override+ void restoreCursor() {+ onCommand('restoreCursor');+ }++ @override+ void index() {+ onCommand('index');+ }++ @override+ void nextLine() {+ onCommand('nextLine');+ }++ @override+ void setTapStop() {+ onCommand('setTapStop');+ }++ @override+ void reverseIndex() {+ onCommand('reverseIndex');+ }++ @override+ void designateCharset(int charset, int name) {+ onCommand('designateCharset($charset, $name)');+ }++ @override+ void unkownEscape(int char) {+ onCommand('unkownEscape(${String.fromCharCode(char)})', error: true);+ }++ /* CSI */++ @override+ void repeatPreviousCharacter(int count) {+ onCommand('repeatPreviousCharacter($count)');+ }++ @override+ void unknownCSI(int finalByte) {+ onCommand('unkownCSI(${String.fromCharCode(finalByte)})', error: true);+ }++ @override+ void setCursor(int x, int y) {+ onCommand('setCursor($x, $y)');+ }++ @override+ void setCursorX(int x) {+ onCommand('setCursorX($x)');+ }++ @override+ void setCursorY(int y) {+ onCommand('setCursorY($y)');+ }++ @override+ void sendPrimaryDeviceAttributes() {+ onCommand('sendPrimaryDeviceAttributes');+ }++ @override+ void clearTabStopUnderCursor() {+ onCommand('clearTabStopUnderCursor');+ }++ @override+ void clearAllTabStops() {+ onCommand('clearAllTabStops');+ }++ @override+ void moveCursorX(int offset) {+ onCommand('moveCursorX($offset)');+ }++ @override+ void moveCursorY(int n) {+ onCommand('moveCursorY($n)');+ }++ @override+ void sendSecondaryDeviceAttributes() {+ onCommand('sendSecondaryDeviceAttributes');+ }++ @override+ void sendTertiaryDeviceAttributes() {+ onCommand('sendTertiaryDeviceAttributes');+ }++ @override+ void sendOperatingStatus() {+ onCommand('sendOperatingStatus');+ }++ @override+ void sendCursorPosition() {+ onCommand('sendCursorPosition');+ }++ @override+ void setMargins(int i, [int? bottom]) {+ onCommand('setMargins($i, $bottom)');+ }++ @override+ void cursorNextLine(int amount) {+ onCommand('cursorNextLine($amount)');+ }++ @override+ void cursorPrecedingLine(int amount) {+ onCommand('cursorPrecedingLine($amount)');+ }++ @override+ void eraseDisplayBelow() {+ onCommand('eraseDisplayBelow');+ }++ @override+ void eraseDisplayAbove() {+ onCommand('eraseDisplayAbove');+ }++ @override+ void eraseDisplay() {+ onCommand('eraseDisplay');+ }++ @override+ void eraseScrollbackOnly() {+ onCommand('eraseScrollbackOnly');+ }++ @override+ void eraseLineRight() {+ onCommand('eraseLineRight');+ }++ @override+ void eraseLineLeft() {+ onCommand('eraseLineLeft');+ }++ @override+ void eraseLine() {+ onCommand('eraseLine');+ }++ @override+ void insertLines(int amount) {+ onCommand('insertLines($amount)');+ }++ @override+ void deleteLines(int amount) {+ onCommand('deleteLines($amount)');+ }++ @override+ void deleteChars(int amount) {+ onCommand('deleteChars($amount)');+ }++ @override+ void scrollUp(int amount) {+ onCommand('scrollUp($amount)');+ }++ @override+ void scrollDown(int amount) {+ onCommand('scrollDown($amount)');+ }++ @override+ void eraseChars(int amount) {+ onCommand('eraseChars($amount)');+ }++ @override+ void insertBlankChars(int amount) {+ onCommand('insertBlankChars($amount)');+ }++ @override+ void resize(int cols, int rows) {+ onCommand('resize($cols, $rows)');+ }++ @override+ void sendSize() {+ onCommand('sendSize');+ }++ /* Modes */++ @override+ void setInsertMode(bool enabled) {+ onCommand('setInsertMode($enabled)');+ }++ @override+ void setLineFeedMode(bool enabled) {+ onCommand('setLineFeedMode($enabled)');+ }++ @override+ void setUnknownMode(int mode, bool enabled) {+ onCommand('setUnknownMode($mode, $enabled)', error: true);+ }++ /* DEC Private modes */++ @override+ void setCursorKeysMode(bool enabled) {+ onCommand('setCursorKeysMode($enabled)');+ }++ @override+ void setReverseDisplayMode(bool enabled) {+ onCommand('setReverseDisplayMode($enabled)');+ }++ @override+ void setOriginMode(bool enabled) {+ onCommand('setOriginMode($enabled)');+ }++ @override+ void setColumnMode(bool enabled) {+ onCommand('setColumnMode($enabled)');+ }++ @override+ void setAutoWrapMode(bool enabled) {+ onCommand('setAutoWrapMode($enabled)');+ }++ @override+ void setMouseMode(MouseMode mode) {+ onCommand('setMouseMode($mode)');+ }++ @override+ void setCursorBlinkMode(bool enabled) {+ onCommand('setCursorBlinkMode($enabled)');+ }++ @override+ void setCursorVisibleMode(bool enabled) {+ onCommand('setCursorVisibleMode($enabled)');+ }++ @override+ void useAltBuffer() {+ onCommand('useAltBuffer');+ }++ @override+ void useMainBuffer() {+ onCommand('useMainBuffer');+ }++ @override+ void clearAltBuffer() {+ onCommand('clearAltBuffer');+ }++ @override+ void setAppKeypadMode(bool enabled) {+ onCommand('setAppKeypadMode($enabled)');+ }++ @override+ void setReportFocusMode(bool enabled) {+ onCommand('setReportFocusMode($enabled)');+ }++ @override+ void setMouseReportMode(MouseReportMode mode) {+ onCommand('setMouseReportMode($mode)');+ }++ @override+ void setAltBufferMouseScrollMode(bool enabled) {+ onCommand('setAltBufferMouseScrollMode($enabled)');+ }++ @override+ void setBracketedPasteMode(bool enabled) {+ onCommand('setBracketedPasteMode($enabled)');+ }++ @override+ void setUnknownDecMode(int mode, bool enabled) {+ onCommand('setUnknownDecMode($mode, $enabled)', error: true);+ }++ /* Select Graphic Rendition (SGR) */++ @override+ void resetCursorStyle() {+ onCommand('resetCursorStyle');+ }++ @override+ void setCursorBold() {+ onCommand('setCursorBold');+ }++ @override+ void setCursorFaint() {+ onCommand('setCursorFaint');+ }++ @override+ void setCursorItalic() {+ onCommand('setCursorItalic');+ }++ @override+ void setCursorUnderline() {+ onCommand('setCursorUnderline');+ }++ @override+ void setCursorBlink() {+ onCommand('setCursorBlink');+ }++ @override+ void setCursorInverse() {+ onCommand('setCursorInverse');+ }++ @override+ void setCursorInvisible() {+ onCommand('setCursorInvisible');+ }++ @override+ void setCursorStrikethrough() {+ onCommand('setCursorStrikethrough');+ }++ @override+ void unsetCursorBold() {+ onCommand('unsetCursorBold');+ }++ @override+ void unsetCursorFaint() {+ onCommand('unsetCursorFaint');+ }++ @override+ void unsetCursorItalic() {+ onCommand('unsetCursorItalic');+ }++ @override+ void unsetCursorUnderline() {+ onCommand('unsetCursorUnderline');+ }++ @override+ void unsetCursorBlink() {+ onCommand('unsetCursorBlink');+ }++ @override+ void unsetCursorInverse() {+ onCommand('unsetCursorInverse');+ }++ @override+ void unsetCursorInvisible() {+ onCommand('unsetCursorInvisible');+ }++ @override+ void unsetCursorStrikethrough() {+ onCommand('unsetCursorStrikethrough');+ }++ @override+ void setForegroundColor16(int color) {+ onCommand('setForegroundColor16($color)');+ }++ @override+ void setForegroundColor256(int index) {+ onCommand('setForegroundColor256($index)');+ }++ @override+ void setForegroundColorRgb(int r, int g, int b) {+ onCommand('setForegroundColorRgb($r, $g, $b)');+ }++ @override+ void resetForeground() {+ onCommand('resetForeground');+ }++ @override+ void setBackgroundColor16(int color) {+ onCommand('setBackgroundColor16($color)');+ }++ @override+ void setBackgroundColor256(int index) {+ onCommand('setBackgroundColor256($index)');+ }++ @override+ void setBackgroundColorRgb(int r, int g, int b) {+ onCommand('setBackgroundColorRgb($r, $g, $b)');+ }++ @override+ void resetBackground() {+ onCommand('resetBackground');+ }++ @override+ void unsupportedStyle(int param) {+ onCommand('unsupportedStyle($param)', error: true);+ }++ /* OSC */++ @override+ void setTitle(String name) {+ onCommand('setTitle($name)');+ }++ @override+ void setIconName(String name) {+ onCommand('setIconName($name)');+ }++ @override+ void unknownOSC(String code, List<String> args) {+ onCommand('unknownOSC($code, $args)', error: true);+ }+}diff --git a/mobile/third_party/xterm/lib/src/utils/debugger_view.dart b/mobile/third_party/xterm/lib/src/utils/debugger_view.dartnew file mode 100644index 000000000..f5ff556a2--- /dev/null+++ b/mobile/third_party/xterm/lib/src/utils/debugger_view.dart@@ -0,0 +1,170 @@+import 'package:flutter/material.dart';+import 'package:xterm/src/utils/debugger.dart';++class TerminalDebuggerView extends StatefulWidget {+ const TerminalDebuggerView(+ this.debugger, {+ super.key,+ this.scrollController,+ this.onSeek,+ });++ final TerminalDebugger debugger;++ final ScrollController? scrollController;++ final void Function(int?)? onSeek;++ @override+ State<TerminalDebuggerView> createState() => _TerminalDebuggerViewState();+}++class _TerminalDebuggerViewState extends State<TerminalDebuggerView> {+ int? selectedCommand;++ @override+ void initState() {+ widget.debugger.addListener(_onDebuggerChanged);+ super.initState();+ }++ @override+ void didUpdateWidget(covariant TerminalDebuggerView oldWidget) {+ if (oldWidget.debugger != widget.debugger) {+ oldWidget.debugger.removeListener(_onDebuggerChanged);+ widget.debugger.addListener(_onDebuggerChanged);+ }+ super.didUpdateWidget(oldWidget);+ }++ @override+ void dispose() {+ widget.debugger.removeListener(_onDebuggerChanged);+ super.dispose();+ }++ void _onDebuggerChanged() {+ setState(() {});+ }++ @override+ Widget build(BuildContext context) {+ final commands = widget.debugger.commands;+ return ListView.builder(+ itemExtent: 20,+ controller: widget.scrollController,+ itemCount: commands.length,+ itemBuilder: (context, index) {+ final command = commands[index];+ return _CommandItem(+ index,+ command,+ selected: selectedCommand == index,+ onTap: () {+ if (selectedCommand == index) {+ selectedCommand = null;+ } else {+ setState(() => selectedCommand = index);+ }+ widget.onSeek?.call(selectedCommand);+ },+ );+ },+ );+ }+}++class _CommandItem extends StatelessWidget {+ const _CommandItem(+ this.index,+ this.command, {+ this.onTap,+ this.selected = false,+ });++ final int index;++ final TerminalCommand command;++ final bool selected;++ final void Function()? onTap;++ @override+ Widget build(BuildContext context) {+ return GestureDetector(+ onTap: onTap,+ child: MouseRegion(+ cursor: SystemMouseCursors.click,+ onEnter: (event) {+ if (event.down) {+ onTap?.call();+ }+ },+ child: Container(+ decoration: BoxDecoration(+ border: Border.all(+ color: selected ? Colors.blue : Colors.transparent,+ width: 2,+ ),+ borderRadius: BorderRadius.circular(5),+ ),+ child: Row(+ children: [+ Container(+ width: 50,+ child: Text(+ '${index + 1}',+ style: TextStyle(+ color: selected ? Colors.blue : Colors.black,+ fontSize: 14,+ fontFamily: 'monospace',+ fontFamilyFallback: [+ 'Menlo',+ 'Monaco',+ 'Consolas',+ 'Liberation Mono',+ 'Courier New',+ 'Noto Sans Mono CJK SC',+ 'Noto Sans Mono CJK TC',+ 'Noto Sans Mono CJK KR',+ 'Noto Sans Mono CJK JP',+ 'Noto Sans Mono CJK HK',+ 'Noto Color Emoji',+ 'Noto Sans Symbols',+ 'monospace',+ 'sans-serif',+ ],+ ),+ textAlign: TextAlign.right,+ ),+ ),+ SizedBox(width: 20),+ Container(+ width: 400,+ child: Text(+ command.escapedChars,+ style: TextStyle(+ color: command.error ? Colors.red : null,+ fontSize: 14,+ ),+ ),+ ),+ Expanded(+ child: Container(+ child: Text(+ command.explanation.join(','),+ style: TextStyle(+ color: command.error ? Colors.red : null,+ fontSize: 14,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/third_party/xterm/lib/src/utils/hash_values.dart b/mobile/third_party/xterm/lib/src/utils/hash_values.dartnew file mode 100644index 000000000..cdc43ed07--- /dev/null+++ b/mobile/third_party/xterm/lib/src/utils/hash_values.dart@@ -0,0 +1,111 @@+class _HashEnd {+ const _HashEnd();+}++const _HashEnd _hashEnd = _HashEnd();++class _Jenkins {+ static int combine(int hash, Object? o) {+ assert(o is! Iterable);+ hash = 0x1fffffff & (hash + o.hashCode);+ hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));+ return hash ^ (hash >> 6);+ }++ static int finish(int hash) {+ hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));+ hash = hash ^ (hash >> 11);+ return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));+ }+}++int hashValues(+ Object? arg01,+ Object? arg02, [+ Object? arg03 = _hashEnd,+ Object? arg04 = _hashEnd,+ Object? arg05 = _hashEnd,+ Object? arg06 = _hashEnd,+ Object? arg07 = _hashEnd,+ Object? arg08 = _hashEnd,+ Object? arg09 = _hashEnd,+ Object? arg10 = _hashEnd,+ Object? arg11 = _hashEnd,+ Object? arg12 = _hashEnd,+ Object? arg13 = _hashEnd,+ Object? arg14 = _hashEnd,+ Object? arg15 = _hashEnd,+ Object? arg16 = _hashEnd,+ Object? arg17 = _hashEnd,+ Object? arg18 = _hashEnd,+ Object? arg19 = _hashEnd,+ Object? arg20 = _hashEnd,+]) {+ int result = 0;+ result = _Jenkins.combine(result, arg01);+ result = _Jenkins.combine(result, arg02);+ if (!identical(arg03, _hashEnd)) {+ result = _Jenkins.combine(result, arg03);+ if (!identical(arg04, _hashEnd)) {+ result = _Jenkins.combine(result, arg04);+ if (!identical(arg05, _hashEnd)) {+ result = _Jenkins.combine(result, arg05);+ if (!identical(arg06, _hashEnd)) {+ result = _Jenkins.combine(result, arg06);+ if (!identical(arg07, _hashEnd)) {+ result = _Jenkins.combine(result, arg07);+ if (!identical(arg08, _hashEnd)) {+ result = _Jenkins.combine(result, arg08);+ if (!identical(arg09, _hashEnd)) {+ result = _Jenkins.combine(result, arg09);+ if (!identical(arg10, _hashEnd)) {+ result = _Jenkins.combine(result, arg10);+ if (!identical(arg11, _hashEnd)) {+ result = _Jenkins.combine(result, arg11);+ if (!identical(arg12, _hashEnd)) {+ result = _Jenkins.combine(result, arg12);+ if (!identical(arg13, _hashEnd)) {+ result = _Jenkins.combine(result, arg13);+ if (!identical(arg14, _hashEnd)) {+ result = _Jenkins.combine(result, arg14);+ if (!identical(arg15, _hashEnd)) {+ result = _Jenkins.combine(result, arg15);+ if (!identical(arg16, _hashEnd)) {+ result = _Jenkins.combine(result, arg16);+ if (!identical(arg17, _hashEnd)) {+ result = _Jenkins.combine(result, arg17);+ if (!identical(arg18, _hashEnd)) {+ result = _Jenkins.combine(result, arg18);+ if (!identical(arg19, _hashEnd)) {+ result = _Jenkins.combine(result, arg19);+ if (!identical(arg20, _hashEnd)) {+ result = _Jenkins.combine(result, arg20);+ // I can see my house from here!+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ return _Jenkins.finish(result);+}++int hashList(Iterable<Object> arguments) {+ int result = 0;+ for (Object argument in arguments) {+ result = _Jenkins.combine(result, argument);+ }+ return _Jenkins.finish(result);+}diff --git a/mobile/third_party/xterm/lib/src/utils/lookup_table.dart b/mobile/third_party/xterm/lib/src/utils/lookup_table.dartnew file mode 100644index 000000000..377294bb2--- /dev/null+++ b/mobile/third_party/xterm/lib/src/utils/lookup_table.dart@@ -0,0 +1,34 @@+/// Fixed-size list based lookup table, optimized for small positive integer+/// keys.+class FastLookupTable<T> {+ FastLookupTable(Map<int, T> data) {+ var maxIndex = data.keys.first;++ for (var key in data.keys) {+ if (key > maxIndex) {+ maxIndex = key;+ }+ }++ _maxIndex = maxIndex;++ _table = List<T?>.filled(maxIndex + 1, null);++ for (var entry in data.entries) {+ _table[entry.key] = entry.value;+ }+ }++ late final List<T?> _table;+ late final int _maxIndex;++ T? operator [](int index) {+ if (index > _maxIndex) {+ return null;+ }++ return _table[index];+ }++ int get maxIndex => _maxIndex;+}diff --git a/mobile/third_party/xterm/lib/src/utils/unicode_v11.dart b/mobile/third_party/xterm/lib/src/utils/unicode_v11.dartnew file mode 100644index 000000000..fd95ba0b8--- /dev/null+++ b/mobile/third_party/xterm/lib/src/utils/unicode_v11.dart@@ -0,0 +1,512 @@+// ignore_for_file: constant_identifier_names++import 'dart:typed_data';++const BMP_COMBINING = [+ [0x0300, 0x036F],+ [0x0483, 0x0489],+ [0x0591, 0x05BD],+ [0x05BF, 0x05BF],+ [0x05C1, 0x05C2],+ [0x05C4, 0x05C5],+ [0x05C7, 0x05C7],+ [0x0600, 0x0605],+ [0x0610, 0x061A],+ [0x061C, 0x061C],+ [0x064B, 0x065F],+ [0x0670, 0x0670],+ [0x06D6, 0x06DD],+ [0x06DF, 0x06E4],+ [0x06E7, 0x06E8],+ [0x06EA, 0x06ED],+ [0x070F, 0x070F],+ [0x0711, 0x0711],+ [0x0730, 0x074A],+ [0x07A6, 0x07B0],+ [0x07EB, 0x07F3],+ [0x07FD, 0x07FD],+ [0x0816, 0x0819],+ [0x081B, 0x0823],+ [0x0825, 0x0827],+ [0x0829, 0x082D],+ [0x0859, 0x085B],+ [0x08D3, 0x0902],+ [0x093A, 0x093A],+ [0x093C, 0x093C],+ [0x0941, 0x0948],+ [0x094D, 0x094D],+ [0x0951, 0x0957],+ [0x0962, 0x0963],+ [0x0981, 0x0981],+ [0x09BC, 0x09BC],+ [0x09C1, 0x09C4],+ [0x09CD, 0x09CD],+ [0x09E2, 0x09E3],+ [0x09FE, 0x09FE],+ [0x0A01, 0x0A02],+ [0x0A3C, 0x0A3C],+ [0x0A41, 0x0A42],+ [0x0A47, 0x0A48],+ [0x0A4B, 0x0A4D],+ [0x0A51, 0x0A51],+ [0x0A70, 0x0A71],+ [0x0A75, 0x0A75],+ [0x0A81, 0x0A82],+ [0x0ABC, 0x0ABC],+ [0x0AC1, 0x0AC5],+ [0x0AC7, 0x0AC8],+ [0x0ACD, 0x0ACD],+ [0x0AE2, 0x0AE3],+ [0x0AFA, 0x0AFF],+ [0x0B01, 0x0B01],+ [0x0B3C, 0x0B3C],+ [0x0B3F, 0x0B3F],+ [0x0B41, 0x0B44],+ [0x0B4D, 0x0B4D],+ [0x0B56, 0x0B56],+ [0x0B62, 0x0B63],+ [0x0B82, 0x0B82],+ [0x0BC0, 0x0BC0],+ [0x0BCD, 0x0BCD],+ [0x0C00, 0x0C00],+ [0x0C04, 0x0C04],+ [0x0C3E, 0x0C40],+ [0x0C46, 0x0C48],+ [0x0C4A, 0x0C4D],+ [0x0C55, 0x0C56],+ [0x0C62, 0x0C63],+ [0x0C81, 0x0C81],+ [0x0CBC, 0x0CBC],+ [0x0CBF, 0x0CBF],+ [0x0CC6, 0x0CC6],+ [0x0CCC, 0x0CCD],+ [0x0CE2, 0x0CE3],+ [0x0D00, 0x0D01],+ [0x0D3B, 0x0D3C],+ [0x0D41, 0x0D44],+ [0x0D4D, 0x0D4D],+ [0x0D62, 0x0D63],+ [0x0DCA, 0x0DCA],+ [0x0DD2, 0x0DD4],+ [0x0DD6, 0x0DD6],+ [0x0E31, 0x0E31],+ [0x0E34, 0x0E3A],+ [0x0E47, 0x0E4E],+ [0x0EB1, 0x0EB1],+ [0x0EB4, 0x0EBC],+ [0x0EC8, 0x0ECD],+ [0x0F18, 0x0F19],+ [0x0F35, 0x0F35],+ [0x0F37, 0x0F37],+ [0x0F39, 0x0F39],+ [0x0F71, 0x0F7E],+ [0x0F80, 0x0F84],+ [0x0F86, 0x0F87],+ [0x0F8D, 0x0F97],+ [0x0F99, 0x0FBC],+ [0x0FC6, 0x0FC6],+ [0x102D, 0x1030],+ [0x1032, 0x1037],+ [0x1039, 0x103A],+ [0x103D, 0x103E],+ [0x1058, 0x1059],+ [0x105E, 0x1060],+ [0x1071, 0x1074],+ [0x1082, 0x1082],+ [0x1085, 0x1086],+ [0x108D, 0x108D],+ [0x109D, 0x109D],+ [0x1160, 0x11FF],+ [0x135D, 0x135F],+ [0x1712, 0x1714],+ [0x1732, 0x1734],+ [0x1752, 0x1753],+ [0x1772, 0x1773],+ [0x17B4, 0x17B5],+ [0x17B7, 0x17BD],+ [0x17C6, 0x17C6],+ [0x17C9, 0x17D3],+ [0x17DD, 0x17DD],+ [0x180B, 0x180E],+ [0x1885, 0x1886],+ [0x18A9, 0x18A9],+ [0x1920, 0x1922],+ [0x1927, 0x1928],+ [0x1932, 0x1932],+ [0x1939, 0x193B],+ [0x1A17, 0x1A18],+ [0x1A1B, 0x1A1B],+ [0x1A56, 0x1A56],+ [0x1A58, 0x1A5E],+ [0x1A60, 0x1A60],+ [0x1A62, 0x1A62],+ [0x1A65, 0x1A6C],+ [0x1A73, 0x1A7C],+ [0x1A7F, 0x1A7F],+ [0x1AB0, 0x1ABE],+ [0x1B00, 0x1B03],+ [0x1B34, 0x1B34],+ [0x1B36, 0x1B3A],+ [0x1B3C, 0x1B3C],+ [0x1B42, 0x1B42],+ [0x1B6B, 0x1B73],+ [0x1B80, 0x1B81],+ [0x1BA2, 0x1BA5],+ [0x1BA8, 0x1BA9],+ [0x1BAB, 0x1BAD],+ [0x1BE6, 0x1BE6],+ [0x1BE8, 0x1BE9],+ [0x1BED, 0x1BED],+ [0x1BEF, 0x1BF1],+ [0x1C2C, 0x1C33],+ [0x1C36, 0x1C37],+ [0x1CD0, 0x1CD2],+ [0x1CD4, 0x1CE0],+ [0x1CE2, 0x1CE8],+ [0x1CED, 0x1CED],+ [0x1CF4, 0x1CF4],+ [0x1CF8, 0x1CF9],+ [0x1DC0, 0x1DF9],+ [0x1DFB, 0x1DFF],+ [0x200B, 0x200F],+ [0x202A, 0x202E],+ [0x2060, 0x2064],+ [0x2066, 0x206F],+ [0x20D0, 0x20F0],+ [0x2CEF, 0x2CF1],+ [0x2D7F, 0x2D7F],+ [0x2DE0, 0x2DFF],+ [0x302A, 0x302D],+ [0x3099, 0x309A],+ [0xA66F, 0xA672],+ [0xA674, 0xA67D],+ [0xA69E, 0xA69F],+ [0xA6F0, 0xA6F1],+ [0xA802, 0xA802],+ [0xA806, 0xA806],+ [0xA80B, 0xA80B],+ [0xA825, 0xA826],+ [0xA8C4, 0xA8C5],+ [0xA8E0, 0xA8F1],+ [0xA8FF, 0xA8FF],+ [0xA926, 0xA92D],+ [0xA947, 0xA951],+ [0xA980, 0xA982],+ [0xA9B3, 0xA9B3],+ [0xA9B6, 0xA9B9],+ [0xA9BC, 0xA9BD],+ [0xA9E5, 0xA9E5],+ [0xAA29, 0xAA2E],+ [0xAA31, 0xAA32],+ [0xAA35, 0xAA36],+ [0xAA43, 0xAA43],+ [0xAA4C, 0xAA4C],+ [0xAA7C, 0xAA7C],+ [0xAAB0, 0xAAB0],+ [0xAAB2, 0xAAB4],+ [0xAAB7, 0xAAB8],+ [0xAABE, 0xAABF],+ [0xAAC1, 0xAAC1],+ [0xAAEC, 0xAAED],+ [0xAAF6, 0xAAF6],+ [0xABE5, 0xABE5],+ [0xABE8, 0xABE8],+ [0xABED, 0xABED],+ [0xFB1E, 0xFB1E],+ [0xFE00, 0xFE0F],+ [0xFE20, 0xFE2F],+ [0xFEFF, 0xFEFF],+ [0xFFF9, 0xFFFB],+];++const HIGH_COMBINING = [+ [0x101FD, 0x101FD],+ [0x102E0, 0x102E0],+ [0x10376, 0x1037A],+ [0x10A01, 0x10A03],+ [0x10A05, 0x10A06],+ [0x10A0C, 0x10A0F],+ [0x10A38, 0x10A3A],+ [0x10A3F, 0x10A3F],+ [0x10AE5, 0x10AE6],+ [0x10D24, 0x10D27],+ [0x10F46, 0x10F50],+ [0x11001, 0x11001],+ [0x11038, 0x11046],+ [0x1107F, 0x11081],+ [0x110B3, 0x110B6],+ [0x110B9, 0x110BA],+ [0x110BD, 0x110BD],+ [0x110CD, 0x110CD],+ [0x11100, 0x11102],+ [0x11127, 0x1112B],+ [0x1112D, 0x11134],+ [0x11173, 0x11173],+ [0x11180, 0x11181],+ [0x111B6, 0x111BE],+ [0x111C9, 0x111CC],+ [0x1122F, 0x11231],+ [0x11234, 0x11234],+ [0x11236, 0x11237],+ [0x1123E, 0x1123E],+ [0x112DF, 0x112DF],+ [0x112E3, 0x112EA],+ [0x11300, 0x11301],+ [0x1133B, 0x1133C],+ [0x11340, 0x11340],+ [0x11366, 0x1136C],+ [0x11370, 0x11374],+ [0x11438, 0x1143F],+ [0x11442, 0x11444],+ [0x11446, 0x11446],+ [0x1145E, 0x1145E],+ [0x114B3, 0x114B8],+ [0x114BA, 0x114BA],+ [0x114BF, 0x114C0],+ [0x114C2, 0x114C3],+ [0x115B2, 0x115B5],+ [0x115BC, 0x115BD],+ [0x115BF, 0x115C0],+ [0x115DC, 0x115DD],+ [0x11633, 0x1163A],+ [0x1163D, 0x1163D],+ [0x1163F, 0x11640],+ [0x116AB, 0x116AB],+ [0x116AD, 0x116AD],+ [0x116B0, 0x116B5],+ [0x116B7, 0x116B7],+ [0x1171D, 0x1171F],+ [0x11722, 0x11725],+ [0x11727, 0x1172B],+ [0x1182F, 0x11837],+ [0x11839, 0x1183A],+ [0x119D4, 0x119D7],+ [0x119DA, 0x119DB],+ [0x119E0, 0x119E0],+ [0x11A01, 0x11A0A],+ [0x11A33, 0x11A38],+ [0x11A3B, 0x11A3E],+ [0x11A47, 0x11A47],+ [0x11A51, 0x11A56],+ [0x11A59, 0x11A5B],+ [0x11A8A, 0x11A96],+ [0x11A98, 0x11A99],+ [0x11C30, 0x11C36],+ [0x11C38, 0x11C3D],+ [0x11C3F, 0x11C3F],+ [0x11C92, 0x11CA7],+ [0x11CAA, 0x11CB0],+ [0x11CB2, 0x11CB3],+ [0x11CB5, 0x11CB6],+ [0x11D31, 0x11D36],+ [0x11D3A, 0x11D3A],+ [0x11D3C, 0x11D3D],+ [0x11D3F, 0x11D45],+ [0x11D47, 0x11D47],+ [0x11D90, 0x11D91],+ [0x11D95, 0x11D95],+ [0x11D97, 0x11D97],+ [0x11EF3, 0x11EF4],+ [0x13430, 0x13438],+ [0x16AF0, 0x16AF4],+ [0x16B30, 0x16B36],+ [0x16F4F, 0x16F4F],+ [0x16F8F, 0x16F92],+ [0x1BC9D, 0x1BC9E],+ [0x1BCA0, 0x1BCA3],+ [0x1D167, 0x1D169],+ [0x1D173, 0x1D182],+ [0x1D185, 0x1D18B],+ [0x1D1AA, 0x1D1AD],+ [0x1D242, 0x1D244],+ [0x1DA00, 0x1DA36],+ [0x1DA3B, 0x1DA6C],+ [0x1DA75, 0x1DA75],+ [0x1DA84, 0x1DA84],+ [0x1DA9B, 0x1DA9F],+ [0x1DAA1, 0x1DAAF],+ [0x1E000, 0x1E006],+ [0x1E008, 0x1E018],+ [0x1E01B, 0x1E021],+ [0x1E023, 0x1E024],+ [0x1E026, 0x1E02A],+ [0x1E130, 0x1E136],+ [0x1E2EC, 0x1E2EF],+ [0x1E8D0, 0x1E8D6],+ [0x1E944, 0x1E94A],+ [0xE0001, 0xE0001],+ [0xE0020, 0xE007F],+ [0xE0100, 0xE01EF],+];++const BMP_WIDE = [+ [0x1100, 0x115F],+ [0x231A, 0x231B],+ [0x2329, 0x232A],+ [0x23E9, 0x23EC],+ [0x23F0, 0x23F0],+ [0x23F3, 0x23F3],+ [0x25FD, 0x25FE],+ [0x2614, 0x2615],+ [0x2648, 0x2653],+ [0x267F, 0x267F],+ [0x2693, 0x2693],+ [0x26A1, 0x26A1],+ [0x26AA, 0x26AB],+ [0x26BD, 0x26BE],+ [0x26C4, 0x26C5],+ [0x26CE, 0x26CE],+ [0x26D4, 0x26D4],+ [0x26EA, 0x26EA],+ [0x26F2, 0x26F3],+ [0x26F5, 0x26F5],+ [0x26FA, 0x26FA],+ [0x26FD, 0x26FD],+ [0x2705, 0x2705],+ [0x270A, 0x270B],+ [0x2728, 0x2728],+ [0x274C, 0x274C],+ [0x274E, 0x274E],+ [0x2753, 0x2755],+ [0x2757, 0x2757],+ [0x2795, 0x2797],+ [0x27B0, 0x27B0],+ [0x27BF, 0x27BF],+ [0x2B1B, 0x2B1C],+ [0x2B50, 0x2B50],+ [0x2B55, 0x2B55],+ [0x2E80, 0x2E99],+ [0x2E9B, 0x2EF3],+ [0x2F00, 0x2FD5],+ [0x2FF0, 0x2FFB],+ [0x3000, 0x3029],+ [0x302E, 0x303E],+ [0x3041, 0x3096],+ [0x309B, 0x30FF],+ [0x3105, 0x312F],+ [0x3131, 0x318E],+ [0x3190, 0x31BA],+ [0x31C0, 0x31E3],+ [0x31F0, 0x321E],+ [0x3220, 0x3247],+ [0x3250, 0x4DBF],+ [0x4E00, 0xA48C],+ [0xA490, 0xA4C6],+ [0xA960, 0xA97C],+ [0xAC00, 0xD7A3],+ [0xF900, 0xFAFF],+ [0xFE10, 0xFE19],+ [0xFE30, 0xFE52],+ [0xFE54, 0xFE66],+ [0xFE68, 0xFE6B],+ [0xFF01, 0xFF60],+ [0xFFE0, 0xFFE6],+];++const HIGH_WIDE = [+ [0x16FE0, 0x16FE3],+ [0x17000, 0x187F7],+ [0x18800, 0x18AF2],+ [0x1B000, 0x1B11E],+ [0x1B150, 0x1B152],+ [0x1B164, 0x1B167],+ [0x1B170, 0x1B2FB],+ [0x1F004, 0x1F004],+ [0x1F0CF, 0x1F0CF],+ [0x1F18E, 0x1F18E],+ [0x1F191, 0x1F19A],+ [0x1F200, 0x1F202],+ [0x1F210, 0x1F23B],+ [0x1F240, 0x1F248],+ [0x1F250, 0x1F251],+ [0x1F260, 0x1F265],+ [0x1F300, 0x1F320],+ [0x1F32D, 0x1F335],+ [0x1F337, 0x1F37C],+ [0x1F37E, 0x1F393],+ [0x1F3A0, 0x1F3CA],+ [0x1F3CF, 0x1F3D3],+ [0x1F3E0, 0x1F3F0],+ [0x1F3F4, 0x1F3F4],+ [0x1F3F8, 0x1F43E],+ [0x1F440, 0x1F440],+ [0x1F442, 0x1F4FC],+ [0x1F4FF, 0x1F53D],+ [0x1F54B, 0x1F54E],+ [0x1F550, 0x1F567],+ [0x1F57A, 0x1F57A],+ [0x1F595, 0x1F596],+ [0x1F5A4, 0x1F5A4],+ [0x1F5FB, 0x1F64F],+ [0x1F680, 0x1F6C5],+ [0x1F6CC, 0x1F6CC],+ [0x1F6D0, 0x1F6D2],+ [0x1F6D5, 0x1F6D5],+ [0x1F6EB, 0x1F6EC],+ [0x1F6F4, 0x1F6FA],+ [0x1F7E0, 0x1F7EB],+ [0x1F90D, 0x1F971],+ [0x1F973, 0x1F976],+ [0x1F97A, 0x1F9A2],+ [0x1F9A5, 0x1F9AA],+ [0x1F9AE, 0x1F9CA],+ [0x1F9CD, 0x1F9FF],+ [0x1FA70, 0x1FA73],+ [0x1FA78, 0x1FA7A],+ [0x1FA80, 0x1FA82],+ [0x1FA90, 0x1FA95],+ [0x20000, 0x2FFFD],+ [0x30000, 0x3FFFD],+];++final table = buildTable();++Uint8List buildTable() {+ final table = Uint8List(65536);+ table.fillRange(0, table.length, 1);+ table[0] = 0;+ table.fillRange(1, 32, 0);+ table.fillRange(0x7f, 0xa0, 0);+ for (var r = 0; r < BMP_COMBINING.length; ++r) {+ table.fillRange(BMP_COMBINING[r][0], BMP_COMBINING[r][1] + 1, 0);+ }+ for (var r = 0; r < BMP_WIDE.length; ++r) {+ table.fillRange(BMP_WIDE[r][0], BMP_WIDE[r][1] + 1, 2);+ }+ return table;+}++bool bisearch(int ucs, List<List<int>> data) {+ var min = 0;+ var max = data.length - 1;+ int mid;+ if (ucs < data[0][0] || ucs > data[max][1]) {+ return false;+ }+ while (max >= min) {+ mid = (min + max) >> 1;+ if (ucs > data[mid][1]) {+ min = mid + 1;+ } else if (ucs < data[mid][0]) {+ max = mid - 1;+ } else {+ return true;+ }+ }+ return false;+}++class UnicodeV11 {+ final version = '11';++ int wcwidth(int codePoint) {+ if (codePoint < 32) return 0;+ if (codePoint < 127) return 1;+ if (codePoint < 65536) return table[codePoint];+ if (bisearch(codePoint, HIGH_COMBINING)) return 0;+ if (bisearch(codePoint, HIGH_WIDE)) return 2;+ return 1;+ }+}++final unicodeV11 = UnicodeV11();diff --git a/mobile/third_party/xterm/lib/suggestion.dart b/mobile/third_party/xterm/lib/suggestion.dartnew file mode 100644index 000000000..4ca4f8ddc--- /dev/null+++ b/mobile/third_party/xterm/lib/suggestion.dart@@ -0,0 +1,199 @@+import 'dart:math';++import 'package:flutter/foundation.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/widgets.dart';++/// Controls the location of the suggestion popup of [SuggestionPortal].+class SuggestionPortalController extends OverlayPortalController {+ final _cursorRect = ValueNotifier<Rect>(Rect.zero);++ /// Updates the location of the suggestion popup to [rect]. If the popup is+ /// not showing, it will be shown after this call.+ void update(Rect rect) {+ _cursorRect.value = rect;+ if (!isShowing) show();+ }+}++/// A convenience widget to place a suggestion popup around the cursor specified+/// by [SuggestionPortalController].+class SuggestionPortal extends StatefulWidget {+ const SuggestionPortal({+ super.key,+ required this.controller,+ required this.overlayBuilder,+ required this.child,+ this.padding = const EdgeInsets.all(8),+ this.cursorMargin = const EdgeInsets.all(4),+ });++ final SuggestionPortalController controller;++ final WidgetBuilder overlayBuilder;++ /// The minimum space between [child] and the screen edge.+ final EdgeInsets padding;++ /// The minimum space between [child] and the cursor. Currently, only top and+ /// bottom are used.+ final EdgeInsets cursorMargin;++ final Widget child;++ @override+ State<SuggestionPortal> createState() => _SuggestionPortalState();+}++class _SuggestionPortalState extends State<SuggestionPortal> {+ @override+ Widget build(BuildContext context) {+ return OverlayPortal.targetsRootOverlay(+ controller: widget.controller,+ overlayChildBuilder: (context) {+ return SuggestionLayout(+ cursorRect: widget.controller._cursorRect,+ padding: widget.padding,+ cursorMargin: widget.cursorMargin,+ child: widget.overlayBuilder(context),+ );+ },+ child: widget.child,+ );+ }+}++/// A widget that places [child] around [cursorRect].+class SuggestionLayout extends SingleChildRenderObjectWidget {+ SuggestionLayout({+ super.child,+ required this.cursorRect,+ required this.padding,+ required this.cursorMargin,+ });++ /// The location of the cursor relative to the top left corner of this widget.+ final ValueListenable<Rect> cursorRect;++ /// The minimum space between [child] and the edge of this widget.+ final EdgeInsets padding;++ /// The minimum space between [child] and the cursor. Currently, only top and+ /// bottom are used.+ final EdgeInsets cursorMargin;++ @override+ RenderObject createRenderObject(BuildContext context) {+ return RenderCompletionLayout(+ null,+ cursorRect: cursorRect,+ padding: padding,+ cursorMargin: cursorMargin,+ );+ }++ @override+ void updateRenderObject(+ BuildContext context,+ covariant RenderCompletionLayout renderObject,+ ) {+ renderObject.cursorRect = cursorRect;+ renderObject.padding = padding;+ renderObject.cursorMargin = cursorMargin;+ }+}++class RenderCompletionLayout extends RenderShiftedBox {+ RenderCompletionLayout(+ super.child, {+ required ValueListenable<Rect> cursorRect,+ required EdgeInsets padding,+ required EdgeInsets cursorMargin,+ }) : _cursorRect = cursorRect,+ _padding = padding,+ _cursorPadding = cursorMargin;++ ValueListenable<Rect> _cursorRect;+ ValueListenable<Rect> get cursorRect => _cursorRect;+ set cursorRect(ValueListenable<Rect> value) {+ if (_cursorRect == value) return;+ _cursorRect.removeListener(markNeedsLayout);+ _cursorRect = value;+ _cursorRect.addListener(markNeedsLayout);+ markNeedsLayout();+ }++ EdgeInsets _padding;+ EdgeInsets get padding => _padding;+ set padding(EdgeInsets value) {+ if (_padding == value) return;+ _padding = value;+ markNeedsLayout();+ }++ EdgeInsets _cursorPadding;+ EdgeInsets get cursorMargin => _cursorPadding;+ set cursorMargin(EdgeInsets value) {+ if (_cursorPadding == value) return;+ _cursorPadding = value;+ markNeedsLayout();+ }++ @override+ void attach(covariant PipelineOwner owner) {+ cursorRect.addListener(markNeedsLayout);+ super.attach(owner);+ }++ @override+ void detach() {+ cursorRect.removeListener(markNeedsLayout);+ super.detach();+ }++ @override+ void performLayout() {+ final child = this.child;++ if (child == null) {+ size = constraints.smallest;+ return;+ }++ size = constraints.biggest;++ // space available for the completion overlay above the cursor+ final spaceAbove = cursorRect.value.top - padding.top - cursorMargin.top;++ // space available for the completion overlay below the cursor+ final spaceBelow = size.height -+ cursorRect.value.bottom -+ padding.bottom -+ cursorMargin.bottom;++ final childConstraints = BoxConstraints(+ minWidth: 0,+ maxWidth: size.width - padding.horizontal,+ minHeight: 0,+ maxHeight: max(spaceAbove, spaceBelow),+ );++ child.layout(childConstraints, parentUsesSize: true);++ // Whether the completion overlay can be placed above the cursor.+ final fitsBelow = spaceBelow >= child.size.height;++ final childParentData = child.parentData as BoxParentData;+ childParentData.offset = Offset(+ min(+ size.width - padding.right - child.size.width,+ cursorRect.value.left,+ ),+ // Showing the completion overlay below the cursor is preferred, unless+ // there's insufficient space for it.+ fitsBelow+ ? cursorRect.value.bottom + cursorMargin.bottom+ : cursorRect.value.top - cursorMargin.top - child.size.height,+ );+ }+}diff --git a/mobile/third_party/xterm/lib/ui.dart b/mobile/third_party/xterm/lib/ui.dartnew file mode 100644index 000000000..bc2c8a948--- /dev/null+++ b/mobile/third_party/xterm/lib/ui.dart@@ -0,0 +1,10 @@+export 'src/terminal_view.dart';+export 'src/ui/controller.dart';+export 'src/ui/cursor_type.dart';+export 'src/ui/keyboard_visibility.dart';+export 'src/ui/pointer_input.dart';+export 'src/ui/selection_mode.dart';+export 'src/ui/shortcut/shortcuts.dart';+export 'src/ui/terminal_text_style.dart';+export 'src/ui/terminal_theme.dart';+export 'src/ui/themes.dart';diff --git a/mobile/third_party/xterm/lib/utils.dart b/mobile/third_party/xterm/lib/utils.dartnew file mode 100644index 000000000..74c0abac3--- /dev/null+++ b/mobile/third_party/xterm/lib/utils.dart@@ -0,0 +1,2 @@+export 'src/utils/debugger.dart';+export 'src/utils/debugger_view.dart';diff --git a/mobile/third_party/xterm/lib/xterm.dart b/mobile/third_party/xterm/lib/xterm.dartnew file mode 100644index 000000000..60e7299df--- /dev/null+++ b/mobile/third_party/xterm/lib/xterm.dart@@ -0,0 +1,3 @@+export 'core.dart';+export 'ui.dart';+export 'zmodem.dart';diff --git a/mobile/third_party/xterm/lib/zmodem.dart b/mobile/third_party/xterm/lib/zmodem.dartnew file mode 100644index 000000000..6498e6d56--- /dev/null+++ b/mobile/third_party/xterm/lib/zmodem.dart@@ -0,0 +1,312 @@+import 'dart:async';+import 'dart:convert';+import 'dart:typed_data';++import 'package:zmodem/zmodem.dart';++export 'package:zmodem/zmodem.dart' show ZModemFileInfo;++typedef ZModemInputHandler = void Function(String output);++typedef ZModemOfferHandler = void Function(ZModemOffer offer);++typedef ZModemRequestHandler = Future<Iterable<ZModemOffer>> Function();++abstract class ZModemOffer {+ ZModemFileInfo get info;++ Stream<Uint8List> accept(int offset);++ void skip();+}++class ZModemCallbackOffer implements ZModemOffer {+ @override+ final ZModemFileInfo info;++ final Stream<Uint8List> Function(int offset) onAccept;++ final void Function()? onSkip;++ ZModemCallbackOffer(this.info, {required this.onAccept, this.onSkip});++ @override+ Stream<Uint8List> accept(int offset) {+ return onAccept(offset);+ }++ @override+ void skip() {+ onSkip?.call();+ }+}++final _zmodemSenderInit = '**\x18B0000000'.codeUnits;++final _zmodemReceiverInit = '**\x18B0100000'.codeUnits;++class ZModemMux {+ /// Data from the underlying data channel.+ final Stream<Uint8List> stdout;++ /// The sink to write data to the underlying data channel.+ final StreamSink<List<int>> stdin;++ /// The callback to receive data that should be written to the terminal.+ ZModemInputHandler? onTerminalInput;++ /// The callback to handle file receiving. If not set, all offers will be+ /// skipped.+ ZModemOfferHandler? onFileOffer;++ /// The callback to handle file sending. If not set, all requests will be+ /// ignored.+ ZModemRequestHandler? onFileRequest;++ ZModemMux({required this.stdin, required this.stdout}) {+ _stdoutSubscription = stdout.listen(_handleStdout);+ }++ /// Subscriptions to [stdout]. Used to pause/resume the stream when no more+ /// space is available in local buffers.+ late final StreamSubscription<Uint8List> _stdoutSubscription;++ late final _terminalSink = StreamController<List<int>>(+ // onPause: _stdoutSubscription.pause,+ // onResume: _stdoutSubscription.resume,+ )+ ..stream+ .transform(Utf8Decoder(allowMalformed: true))+ .listen(onTerminalInput);++ /// Current ZModem session. If null, no session is active.+ ZModemCore? _session;++ /// The sink to write data when receiving a file. If null, no file is being+ /// received.+ StreamController<Uint8List>? _receiveSink;++ /// Offers to send to the remote peer. If null, no offers are being sent.+ Iterator<ZModemOffer>? _fileOffers;++ /// Writes terminal output to the underlying connection. [input] may be+ /// buffered if a ZModem session is active.+ void terminalWrite(String input) {+ if (_session == null) {+ stdin.add(utf8.encode(input));+ }+ }++ /// This is the entry point of multiplexing, dispatching data to ZModem or+ /// terminal depending on the current state.+ void _handleStdout(Uint8List chunk) {+ if (_session != null) {+ _handleZModem(chunk);+ return;+ }++ if (_detectZModem(chunk)) {+ return;+ }++ _terminalSink.add(chunk);+ }++ /// Detects a ZModem session in [chunk] and starts it if found. Returns true+ /// if a session was started.+ bool _detectZModem(Uint8List chunk) {+ final index = chunk.listIndexOf(_zmodemSenderInit) ??+ chunk.listIndexOf(_zmodemReceiverInit);++ if (index != null) {+ _terminalSink.add(Uint8List.sublistView(chunk, 0, index));++ _session = ZModemCore(+ onPlainText: (text) {+ _terminalSink.add([text]);+ },+ );++ _handleZModem(Uint8List.sublistView(chunk, index));+ return true;+ }++ return false;+ }++ void _handleZModem(Uint8List chunk) async {+ for (final event in _session!.receive(chunk)) {+ /// remote is sz+ if (event is ZFileOfferedEvent) {+ _handleZFileOfferedEvent(event);+ } else if (event is ZFileDataEvent) {+ _handleZFileDataEvent(event);+ } else if (event is ZFileEndEvent) {+ await _handleZFileEndEvent(event);+ } else if (event is ZSessionFinishedEvent) {+ await _handleZSessionFinishedEvent(event);+ }++ /// remote is rz+ else if (event is ZReadyToSendEvent) {+ await _handleFileRequestEvent(event);+ } else if (event is ZFileAcceptedEvent) {+ await _handleFileAcceptedEvent(event);+ } else if (event is ZFileSkippedEvent) {+ _handleFileSkippedEvent(event);+ }++ _flush();+ }++ _flush();+ }++ void _handleZFileOfferedEvent(ZFileOfferedEvent event) {+ final onFileOffer = this.onFileOffer;++ if (onFileOffer == null) {+ _session!.skipFile();+ return;+ }++ onFileOffer(_createRemoteOffer(event.fileInfo));+ }++ void _handleZFileDataEvent(ZFileDataEvent event) {+ _receiveSink!.add(event.data as Uint8List);+ }++ Future<void> _handleZFileEndEvent(ZFileEndEvent event) async {+ await _closeReceiveSink();+ }++ Future<void> _handleZSessionFinishedEvent(ZSessionFinishedEvent event) async {+ _flush();+ await _reset();+ }++ Future<void> _handleFileRequestEvent(ZReadyToSendEvent event) async {+ _fileOffers ??= (await onFileRequest?.call())?.iterator;++ _moveToNextOffer();+ }++ Future<void> _handleFileAcceptedEvent(ZFileAcceptedEvent event) async {+ final data = _fileOffers!.current.accept(event.offset);+ var bytesSent = 0;++ await stdin.addStream(+ data.transform(+ StreamTransformer<Uint8List, Uint8List>.fromHandlers(+ handleData: (chunk, sink) {+ bytesSent += chunk.length;+ _session!.sendFileData(chunk);+ sink.add(_session!.dataToSend());+ },+ ),+ ),+ );++ _session!.finishSending(event.offset + bytesSent);+ }++ void _handleFileSkippedEvent(ZFileSkippedEvent event) {+ _fileOffers!.current.skip();+ _moveToNextOffer();+ }++ /// Sends next file offer if available, or closes the session if not.+ void _moveToNextOffer() {+ if (_fileOffers?.moveNext() != true) {+ _closeSession();+ return;+ }++ _session!.offerFile(_fileOffers!.current.info);+ }++ /// Creates a [ZModemOffer] ƒrom the info from remote peer that can be used+ /// by local client to accept or skip the file.+ ZModemOffer _createRemoteOffer(ZModemFileInfo fileInfo) {+ return ZModemCallbackOffer(+ fileInfo,+ onAccept: (offset) {+ _session!.acceptFile(offset);+ _flush();++ _createReceiveSink();+ return _receiveSink!.stream;+ },+ onSkip: () {+ _session!.skipFile();+ _flush();+ },+ );+ }++ void _createReceiveSink() {+ _receiveSink = StreamController<Uint8List>(+ onPause: () {+ // _stdoutSubscription.pause();+ },+ onResume: () {+ // _stdoutSubscription.resume();+ },+ );+ }++ Future<void> _closeReceiveSink() async {+ _stdoutSubscription.resume();+ await _receiveSink?.close();+ _receiveSink = null;+ }++ /// Requests remote to close the session.+ void _closeSession() {+ _session!.finishSession();+ }++ /// Clears all ZModem state.+ Future<void> _reset() async {+ await _closeReceiveSink();+ _fileOffers = null;+ _session = null;+ }++ /// Sends all pending data packets to the remote. No data is automatically+ /// sent to the remote without calling this method.+ void _flush() {+ final dataToSend = _session?.dataToSend();+ if (dataToSend != null && dataToSend.isNotEmpty) {+ stdin.add(dataToSend);+ }+ }+}++extension ListExtension on List<int> {+ String dump() {+ return map((e) => e.toRadixString(16).padLeft(2, '0')).join(' ');+ }++ int? listIndexOf(List<int> other, [int start = 0]) {+ if (other.length + start > length) {+ return null;+ }+ for (var i = start; i < length - other.length; i++) {+ if (this[i] == other[0]) {+ var found = true;+ for (var j = 1; j < other.length; j++) {+ if (this[i + j] != other[j]) {+ found = false;+ break;+ }+ }+ if (found) {+ return i;+ }+ }+ }+ return null;+ }+}diff --git a/mobile/third_party/xterm/pubspec.yaml b/mobile/third_party/xterm/pubspec.yamlnew file mode 100644index 000000000..945265efd--- /dev/null+++ b/mobile/third_party/xterm/pubspec.yaml@@ -0,0 +1,61 @@+name: xterm+description: xterm.dart is a fast and fully-featured terminal emulator for Flutter applications, with support for mobile and desktop platforms.+version: 4.0.0+homepage: https://github.com/TerminalStudio/xterm.dart++environment:+ sdk: ">=3.0.0 <4.0.0"+ flutter: ">=3.19.0"++dependencies:+ convert: ^3.0.0+ meta: ^1.3.0+ quiver: ^3.0.0+ equatable: ^2.0.3+ flutter:+ sdk: flutter+ zmodem: ^0.0.6++dev_dependencies:+ flutter_test:+ sdk: flutter+ test: ^1.6.5+ lints: ^3.0.0+ dart_code_metrics: ^5.0.0+ mockito: ^5.3.1+ build_runner: ^2.1.1++# For information on the generic Dart part of this file, see the+# following page: https://dart.dev/tools/pub/pubspec++# The following section is specific to Flutter.+flutter:+ # To add assets to your package, add an assets section, like this:+ # assets:+ # - images/a_dot_burr.jpeg+ # - images/a_dot_ham.jpeg+ #+ # For details regarding assets in packages, see+ # https://flutter.dev/assets-and-images/#from-packages+ #+ # An image asset can refer to one or more resolution-specific "variants", see+ # https://flutter.dev/assets-and-images/#resolution-aware.+ # To add custom fonts to your package, add a fonts section here,+ # in this "flutter" section. Each entry in this list should have a+ # "family" key with the font family name, and a "fonts" key with a+ # list giving the asset and other descriptors for the font. For+ # example:+ # fonts:+ # - family: Schyler+ # fonts:+ # - asset: fonts/Schyler-Regular.ttf+ # - asset: fonts/Schyler-Italic.ttf+ # style: italic+ # - family: Trajan Pro+ # fonts:+ # - asset: fonts/TrajanPro.ttf+ # - asset: fonts/TrajanPro_Bold.ttf+ # weight: 700+ #+ # For details regarding fonts in packages, see+ # https://flutter.dev/custom-fonts/#from-packages