Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(web): bring the shared Harness workspace to browsers (#392)

Dee93f148d6e6cd
diff --git a/.github/workflows/release-web.yml b/.github/workflows/release-web.yml
new file mode 100644
index 000000000..c944217f9
--- /dev/null
+++ b/.github/workflows/release-web.yml
@@ -0,0 +1,49 @@
+name: Release web bundle
+
+on:
+ push:
+ tags: ['v*_web']
+
+permissions:
+ contents: write
+
+concurrency:
+ group: web-release-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ bundle:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ env:
+ FLUTTER_VERSION: '3.47.2'
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+ - name: Validate version
+ env:
+ RELEASE_TAG: ${{ github.ref_name }}
+ run: |
+ version="${RELEASE_TAG#v}"
+ version="${version%_web}"
+ [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || exit 1
+ echo "WEB_VERSION=$version" >> "$GITHUB_ENV"
+ - uses: subosito/flutter-action@v2
+ with:
+ flutter-version: ${{ env.FLUTTER_VERSION }}
+ channel: stable
+ cache: true
+ - name: Build shared Flutter workspace
+ working-directory: desktop
+ run: bash scripts/build-web-release.sh "$WEB_VERSION"
+ - name: Publish bundle and checksum
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_TAG: ${{ github.ref_name }}
+ run: |
+ printf '%s\n' \
+ 'Browser build of the shared desktop Flutter app.' \
+ 'The website deployment pins the archive and SHA-256 from harness-web-release.json.' \
+ > "$RUNNER_TEMP/web-release-notes.md"
+ gh release create "$RELEASE_TAG" desktop/build/web-dist/* \
+ --verify-tag --latest=false --title "Harness Web $WEB_VERSION" \
+ --notes-file "$RUNNER_TEMP/web-release-notes.md"
diff --git a/README.md b/README.md
index 0f8f21f54..1e31ec868 100644
--- a/README.md
+++ b/README.md
@@ -280,5 +280,6 @@ It is open hardware, all the way down. This repository has everything it takes t
Make a harness for a tool you love. Improve terminals, engines, the daemon or the relay. Port the
firmware. Start with the [contribution guide](CONTRIBUTING.md).
+[Architecture](docs/architecture.md) · [Product direction (proposal)](docs/product-direction.md) ·
[Development](docs/development.md) · [Extending](docs/extending.md) · [CLI](docs/cli.md) ·
[Security](SECURITY.md) · [MIT license](LICENSE); upstream tools keep their own.
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index e14fb866a..3bc46eaf0 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -93,10 +93,25 @@ its consumer is now the `harness` installer rather than this app.
## Architecture
-### The app talks only to the local `harness` CLI
-
-This is the single most important thing to know. The desktop app **never** dials the cloud backend or
-holds an SSO token:
+### One Flutter UI, native and browser transports
+
+`flutter build web` builds the same `lib/main.dart` and workspace as desktop.
+Do not fork screens or create a second frontend. `kViewerMode` is true on the web:
+the browser owns its OAuth session, peer links, and end-to-end relay encryption.
+`viewer/browser_login.dart` validates the same-tab callback against the backend's
+PKCE transaction; conditional adapters handle storage and native-only services.
+`platform_auth_web.dart` serializes shared login/refresh/logout with Web Locks
+and reloads other tabs when the account changes. Auth and E2EE keys persist in
+origin-local storage; only the OAuth transaction is in session storage.
+Private shared sessions use `ObserverRelayCodec` and `/api/observer-ws`, verifying
+the owner and permitting only observation. Anonymous public pages are not included.
+See [README.md](README.md#web-development) for origin setup, browser storage
+lifetime, capability limits, and Chrome checks. Browser tests must set
+`--dart-define=HARNESS_TEST=true` so no production pollers or analytics run.
+
+### Native desktop talks to the local `harness` CLI
+
+The native desktop target uses the CLI for cloud access and SSO tokens:
- **Auth** lives in the CLI. `lib/auth/cli_login.dart` shells out to `harness auth status --json` and
drives `harness login --json` (NDJSON event stream); `cli_link.dart` wraps `harness link create/import/list`.
@@ -137,7 +152,7 @@ holds an SSO token:
socket file exists, so a daemon restart does not strand the app on TCP. Windows and paths over 96
bytes have no socket. The CLI, engine hooks and the dashboard stay on TCP. Under `flutter test`
`LocalDaemonTransport.detect` finds no socket, so tests never reach a real daemon.
-- The **only** direct-to-backend path is `LocalManualFixture` (`lib/main_local_manual.dart`), a
+- Besides viewer builds, a direct-to-backend test path is `LocalManualFixture` (`lib/main_local_manual.dart`), a
compile-time-gated dev entrypoint fed by `scripts/start-terminal-local-manual.sh`. It fails closed
unless every `--dart-define` is present.
diff --git a/desktop/README.md b/desktop/README.md
index 568a4b309..4043267c0 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -1,10 +1,107 @@
-# Harness Desktop
+# Harness Desktop and Web
Harness Desktop is the native Flutter client for browsing Harness machines and
interacting with their terminal-backed agents. **macOS is the primary supported and tested
experience.** Linux builds exist, with feature parity still in progress; Windows support is
planned and its runner is unexercised. Embedded harness viewers currently require macOS.
+The browser target uses this same Flutter package and `lib/main.dart`: workspace,
+tabs, pickers, settings, state, and the patched xterm renderer are shared. Browser
+support is available as a public preview at
+[harness.autonomous.ai](https://harness.autonomous.ai); there is no separate web UI
+to keep in sync.
+
+## Web development
+
+Use Flutter ≥ 3.47 / Dart ≥ 3.13. From `desktop/`:
+
+```bash
+flutter pub get
+flutter run -d chrome --web-port=3000
+flutter build web --release --no-wasm-dry-run --no-web-resources-cdn
+python3 scripts/serve-web.py --port 3000 # optional local release preview
+flutter test --platform=chrome --dart-define=HARNESS_TEST=true \
+ test/web test/browser_login_test.dart test/observer_codec_test.dart \
+ test/wire_counter_test.dart test/password_stretch_test.dart \
+ test/terminal_binary_test.dart test/e2ee/strict_down_test.dart
+```
+
+Deploy `build/web/` at the root of a dedicated HTTPS origin. The host must serve
+`index.html` for `/auth/callback`; `_redirects` and `_headers` cover hosts that
+support those files. For other hosts, configure the equivalent SPA fallback and
+revalidation of unversioned app files. Do not cache OAuth callbacks. The app uses
+JavaScript/CanvasKit; WebAssembly app compilation is not validated yet.
+
+The entry page inlines Flutter's generated bootstrap to start the app without
+an extra loader request. Keep entry pages and release metadata `no-store`.
+Serve static JavaScript, CanvasKit, fonts, and images with ETags and
+`Cache-Control: public, max-age=0, must-revalidate`: browsers reuse unchanged
+bytes while checking for every deployment. Do not use `no-store` for these
+assets or long-lived immutable caching with their unversioned filenames.
+
+The existing backend handles browser OAuth. Local previews on `127.0.0.1`,
+`localhost`, or `[::1]` use its existing loopback authorization endpoint, returning
+to the registered `/callback` path on the preview's own port without a server
+configuration change.
+For a hosted web app, add the exact origin to the backend's `WEB_URL` or
+comma-separated `WEB_ORIGINS`, and register that origin's `/auth/callback` with SSO.
+Any `SSO_REDIRECT_URI` override must point to that same hosted callback. Tests use a
+synthetic authorization service. An alternate backend can be selected with
+`--dart-define=HARNESS_API_URL=https://your-backend.example` on run/build.
+Use `--dart-define=HARNESS_ANALYTICS_DISABLED=true` for isolated previews.
+
+### Production release
+
+The Flutter source remains in this package. The existing website deployment in
+`autonomous-ai/autonomous-code` serves its compiled files under `/harness-web/`,
+with `/` and `/auth/callback` opening the Flutter app. It also serves the desktop
+downloads and installer redirects.
+
+Push a `vX.Y.Z_web` tag on a tested commit to run **Release web bundle**. CI builds
+with Flutter 3.47.2 and publishes the archive, SHA-256, and
+`harness-web-release.json` as GitHub release assets. Copy that manifest into the
+website's `apps/web/harness-web-release.json`, verify the website build, and use
+its existing `scripts/release-web.sh` release procedure. Its build checks the
+archive's checksum before including it in the image; ArgoCD deploys that image.
+For a local production build, run `bash scripts/build-web-release.sh X.Y.Z`.
+`FLUTTER_BIN` can select an SDK installed outside `PATH`. Output is under
+`build/web-release/` and `build/web-dist/`; the ordinary local preview is separate.
+
+### Browser behavior
+
+- Authenticated access to existing machines uses the shared viewer services and
+ encrypted relay. Link a machine from the browser before controlling it.
+- Existing account-bound sharing invitations open read-only through the observer
+ relay, with the owner's identity verified. Public, anonymous session URLs and
+ published snapshots are the next product layer; they are not implemented here.
+- Login, linked machines, preferences, and cached workspace metadata persist in
+ this origin's local storage across tabs and browser restarts. Only the pending
+ OAuth transaction is tab-local. Browser locks serialize token refresh and
+ machine-key writes; signing out or changing accounts reloads other open tabs.
+ **Sign out** clears authentication while keeping this browser's machine links.
+ Clearing site data removes both; private browsing retains them only for that
+ private session. Existing tab credentials migrate on the next reload.
+- **Download app** sits at the top right of sign-in and workspace screens, opening
+ the existing macOS/Linux download page in a separate tab. Browser sign-in uses
+ a full-page fleet diagram and prominent CTA, sharing the native login actions
+ and their waiting, cancellation, and recovery states.
+- Workspace shortcuts use **Option/Alt** in the browser: Alt-P finds agents,
+ Alt-N starts an agent, Alt-M opens machines, and Alt-T opens a Harness tab.
+ Machine connection commands and link requests use that same `@` picker,
+ with connection and setup forms inside its preview pane.
+ Text editing and terminal
+ Control keys keep their usual behavior. The shared shortcut sheet and welcome
+ hints show the active bindings.
+- Agent processes and files stay on their host machines. Local provisioning,
+ desktop updates, device pairing, local usage ledgers, keyboard config files,
+ native file previews/image clipboard, and embedded native webviews remain
+ desktop capabilities. Remote terminals and streamed image viewers reuse the
+ shared UI. Closing the browser does not stop a running agent.
+
+Keep product changes in the existing shared screens and state. Add platform
+adapters only for browser/native capabilities, following the conditional stores,
+login adapter, and runtime capability checks already in `lib/`.
+
## Development
For workspace dialog work, follow the
diff --git a/desktop/assets/fonts/roboto-mono/OFL.txt b/desktop/assets/fonts/roboto-mono/OFL.txt
new file mode 100644
index 000000000..c2a18415e
--- /dev/null
+++ b/desktop/assets/fonts/roboto-mono/OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2015 The Roboto Mono Project Authors (https://github.com/googlefonts/robotomono)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://openfontlicense.org
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/desktop/assets/fonts/roboto-mono/README.md b/desktop/assets/fonts/roboto-mono/README.md
new file mode 100644
index 000000000..bed13a4a5
--- /dev/null
+++ b/desktop/assets/fonts/roboto-mono/README.md
@@ -0,0 +1,7 @@
+Roboto Mono (variable regular and italic), from
+https://github.com/google/fonts/tree/main/ofl/robotomono, downloaded 2026-09-27.
+Distributed under the SIL Open Font License; see OFL.txt.
+
+The web renderer needs a bundled monospace face; it cannot use the native
+system font families selected by desktop. This asset is shared by terminal
+cells, workspace chrome, and dialogs on web.
diff --git a/desktop/assets/fonts/roboto-mono/RobotoMono-Italic.ttf b/desktop/assets/fonts/roboto-mono/RobotoMono-Italic.ttf
new file mode 100644
index 000000000..414a5121f
Binary files /dev/null and b/desktop/assets/fonts/roboto-mono/RobotoMono-Italic.ttf differ
diff --git a/desktop/assets/fonts/roboto-mono/RobotoMono.ttf b/desktop/assets/fonts/roboto-mono/RobotoMono.ttf
new file mode 100644
index 000000000..f21d1d716
Binary files /dev/null and b/desktop/assets/fonts/roboto-mono/RobotoMono.ttf differ
diff --git a/desktop/lib/analytics/analytics_client.dart b/desktop/lib/analytics/analytics_client.dart
index b5a2037f9..bf549dad3 100644
--- a/desktop/lib/analytics/analytics_client.dart
+++ b/desktop/lib/analytics/analytics_client.dart
@@ -1,6 +1,6 @@
import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
+
+import 'package:dio/dio.dart';
import 'analytics_config.dart';
@@ -33,42 +33,40 @@ abstract interface class AnalyticsClient {
void dispose();
}
-/// Real [AnalyticsClient] over `dart:io` [HttpClient].
+/// Real [AnalyticsClient] using Dio on both native and browser targets.
///
/// 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
+/// to a third-party ingest host. One HTTP client 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;
+ late final Dio _client = Dio(
+ BaseOptions(
+ connectTimeout: AnalyticsLimits.requestTimeout,
+ receiveTimeout: AnalyticsLimits.requestTimeout,
+ sendTimeout: AnalyticsLimits.requestTimeout,
+ validateStatus: (status) => status != null,
+ headers: {'Authorization': _config.writeKey},
+ ),
+ );
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,
+ final response = await _client.post<dynamic>(
+ _config.endpoint.toString(),
+ data: payload,
);
- // 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);
+ return _resultFor(response.statusCode ?? 0);
} on TimeoutException {
return AnalyticsSendResult.retry;
- } on SocketException {
- return AnalyticsSendResult.retry;
- } on HttpException {
+ } on DioException {
return AnalyticsSendResult.retry;
} on Object {
// Anything left (a bad URL, a TLS failure) would fail the same way every
@@ -80,14 +78,9 @@ class HttpAnalyticsClient implements AnalyticsClient {
@override
void dispose() {
_disposed = true;
- _client?.close(force: true);
- _client = null;
+ _client.close(force: true);
}
- 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) {
diff --git a/desktop/lib/analytics/analytics_config.dart b/desktop/lib/analytics/analytics_config.dart
index 84187c6c9..ad88585f7 100644
--- a/desktop/lib/analytics/analytics_config.dart
+++ b/desktop/lib/analytics/analytics_config.dart
@@ -1,7 +1,6 @@
-import 'dart:io';
-
import 'package:flutter/foundation.dart';
+import '../core/runtime_platform.dart';
import '../core/test_run.dart';
/// Where behavioural events go, whether they go at all, and under what limits.
@@ -56,7 +55,7 @@ class AnalyticsConfig {
/// 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';
+ static const String category = kIsWeb ? 'harness-web' : '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
@@ -111,7 +110,8 @@ class AnalyticsConfig {
/// True when `HARNESS_ANALYTICS_DISABLED` is set to anything truthy.
static bool get _muted {
- final value = Platform.environment[disableEnvKey]?.toLowerCase().trim();
+ if (const bool.fromEnvironment('HARNESS_ANALYTICS_DISABLED')) return true;
+ final value = RuntimePlatform.environment[disableEnvKey]?.toLowerCase().trim();
return value == '1' || value == 'true' || value == 'yes';
}
@@ -130,7 +130,7 @@ class AnalyticsConfig {
_ => '',
};
if (define.isNotEmpty) return define;
- final value = Platform.environment[key];
+ final value = RuntimePlatform.environment[key];
return (value != null && value.isNotEmpty) ? value : null;
}
}
diff --git a/desktop/lib/analytics/analytics_identity.dart b/desktop/lib/analytics/analytics_identity.dart
index ec2a9fdbc..9c136c639 100644
--- a/desktop/lib/analytics/analytics_identity.dart
+++ b/desktop/lib/analytics/analytics_identity.dart
@@ -2,6 +2,9 @@ import 'dart:convert';
import 'dart:io';
import 'dart:math';
+import 'package:flutter/foundation.dart' show kIsWeb;
+
+import '../core/browser_storage.dart';
import '../core/harness_file_store.dart';
import 'analytics_config.dart';
@@ -27,14 +30,19 @@ import 'analytics_config.dart';
/// 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()),
+ : _file =
+ file ??
+ (kIsWeb
+ ? null
+ : File('${HarnessFileStore.defaultDirectoryPath()}/$_name')),
+ _computerIdFile =
+ computerIdFile ?? (kIsWeb ? null : File(_defaultComputerIdPath())),
_random = random ?? Random.secure();
static const String _name = 'analytics.json';
- final File _file;
- final File _computerIdFile;
+ final File? _file;
+ final File? _computerIdFile;
final Random _random;
_StoredIdentity? _state;
@@ -90,8 +98,11 @@ class AnalyticsIdentityStore {
if (cached != null) return cached;
var json = const <String, Object?>{};
try {
- if (_file.existsSync()) {
- final decoded = jsonDecode(_file.readAsStringSync());
+ final raw = kIsWeb
+ ? readBrowserPreference('analytics')
+ : (_file!.existsSync() ? _file.readAsStringSync() : null);
+ if (raw != null) {
+ final decoded = jsonDecode(raw);
if (decoded is Map) json = decoded.cast<String, Object?>();
}
} on Object {
@@ -120,7 +131,7 @@ class AnalyticsIdentityStore {
String? _computerId() {
try {
- if (!_computerIdFile.existsSync()) return null;
+ if (_computerIdFile == null || !_computerIdFile.existsSync()) return null;
final id = _computerIdFile.readAsStringSync().trim();
return id.isEmpty ? null : id;
} on Object {
@@ -131,16 +142,18 @@ class AnalyticsIdentityStore {
/// 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,
- );
+ final contents = const JsonEncoder.withIndent(' ').convert({
+ 'user_pseudo_id': state.pseudoId,
+ 'session_id': state.sessionId,
+ 'last_active_ms': state.lastActive,
+ 'enabled': !state.optedOut,
+ });
+ if (kIsWeb) {
+ writeBrowserPreference('analytics', contents);
+ } else {
+ _file!.parent.createSync(recursive: true);
+ _file.writeAsStringSync(contents, flush: true);
+ }
} on Object {
// A read-only home or a full disk costs id stability across restarts,
// not the event in hand.
diff --git a/desktop/lib/analytics/analytics_sink.dart b/desktop/lib/analytics/analytics_sink.dart
index 44e273326..b9442c040 100644
--- a/desktop/lib/analytics/analytics_sink.dart
+++ b/desktop/lib/analytics/analytics_sink.dart
@@ -1,10 +1,10 @@
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 '../core/runtime_architecture.dart';
+import '../core/runtime_platform.dart';
import '../logging/debug_surface.dart';
import 'analytics.dart';
import 'analytics_client.dart';
@@ -196,12 +196,12 @@ Future<AnalyticsContext> resolveAnalyticsContext() async {
// A bundle we can't read is worth an anonymous version, not a lost event.
}
return AnalyticsContext(
- platform: Platform.operatingSystem,
+ platform: RuntimePlatform.operatingSystem,
appVersion: version,
appBuild: build,
- osVersion: Platform.operatingSystemVersion,
- arch: Abi.current().toString(),
- locale: Platform.localeName,
+ osVersion: RuntimePlatform.operatingSystemVersion,
+ arch: runtimeAbi,
+ locale: RuntimePlatform.localeName,
release: kReleaseMode,
);
}
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dart
index b0241ca34..38c602657 100644
--- a/desktop/lib/app_shell.dart
+++ b/desktop/lib/app_shell.dart
@@ -2,6 +2,8 @@ import 'dart:async';
import 'dart:ui' show AppExitResponse;
import 'package:flutter/material.dart';
+import 'package:flutter/foundation.dart'
+ show kIsWeb, LicenseRegistry, LicenseEntryWithLineBreaks;
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -52,13 +54,18 @@ Future<void> startHarness({
TerminalTransportPluginFactory? transportPlugins,
}) async {
WidgetsFlutterBinding.ensureInitialized();
+ LicenseRegistry.addLicense(() async* {
+ yield LicenseEntryWithLineBreaks([
+ 'Roboto Mono',
+ ], await rootBundle.loadString('assets/fonts/roboto-mono/OFL.txt'));
+ });
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());
+ final keymap = AppKeymap(store: kIsWeb ? null : 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()]);
@@ -91,6 +98,8 @@ class HarnessApp extends StatelessWidget {
grid.AppTheme.palette.value = prefs.palette;
return MaterialApp(
title: 'Harness',
+ // OAuth callback paths are consumed by the sign-in adapter during boot.
+ initialRoute: '/',
themeAnimationDuration: Duration.zero,
// Flutter's DEBUG ribbon stays on a debug build: it is how a locally built
// app is told apart from the installed release at a glance (owner,
diff --git a/desktop/lib/auth/auth_session.dart b/desktop/lib/auth/auth_session.dart
index a0d10af05..255e89379 100644
--- a/desktop/lib/auth/auth_session.dart
+++ b/desktop/lib/auth/auth_session.dart
@@ -1,7 +1,7 @@
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.
+/// Persists SSO access + refresh tokens through the platform's state store.
class AuthSession {
final LocalKeyValueStore _storage;
static const _access = 'auth_access_token';
diff --git a/desktop/lib/clipboard/native_clipboard.dart b/desktop/lib/clipboard/native_clipboard.dart
index 0422c3508..02fa3a257 100644
--- a/desktop/lib/clipboard/native_clipboard.dart
+++ b/desktop/lib/clipboard/native_clipboard.dart
@@ -1,7 +1,7 @@
-import 'dart:io';
-
import 'package:flutter/services.dart';
+import '../core/runtime_platform.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
@@ -22,7 +22,7 @@ class NativeClipboard {
/// 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;
+ if (!RuntimePlatform.isMacOS && !RuntimePlatform.isLinux) return null;
try {
final bytes = await _channel.invokeMethod<Uint8List>('readImagePng');
return bytes;
@@ -43,7 +43,7 @@ class NativeClipboard {
/// 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;
+ if (!RuntimePlatform.isMacOS && !RuntimePlatform.isLinux) return false;
try {
final wrote = await _channel.invokeMethod<bool>(
'writeImagePng',
diff --git a/desktop/lib/core/app_version.dart b/desktop/lib/core/app_version.dart
index 8a2271222..e6b0113d9 100644
--- a/desktop/lib/core/app_version.dart
+++ b/desktop/lib/core/app_version.dart
@@ -2,6 +2,8 @@ import 'dart:io';
import 'package:package_info_plus/package_info_plus.dart';
+import 'runtime_platform.dart';
+
/// The version of the build currently running.
///
/// `flutter build linux` has no equivalent of Xcode's Info.plist stamping —
@@ -16,8 +18,8 @@ Future<String> runningAppVersion({
String? executablePath,
Future<String> Function()? packageInfoVersion,
}) async {
- if (Platform.isLinux) {
- final exe = File(executablePath ?? Platform.resolvedExecutable);
+ if (RuntimePlatform.isLinux) {
+ final exe = File(executablePath ?? RuntimePlatform.resolvedExecutable);
final versionFile = File('${exe.parent.path}/version.txt');
try {
// Read synchronously. It is a dozen bytes sitting next to the executable,
diff --git a/desktop/lib/core/apple_fonts.dart b/desktop/lib/core/apple_fonts.dart
index 3a58f5b49..1b56134fd 100644
--- a/desktop/lib/core/apple_fonts.dart
+++ b/desktop/lib/core/apple_fonts.dart
@@ -1,11 +1,11 @@
-import 'dart:io' show Platform;
+import 'runtime_platform.dart';
/// 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
+/// The font chains used to ask `RuntimePlatform.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;
+bool get hasAppleFonts => RuntimePlatform.isMacOS || RuntimePlatform.isIOS;
diff --git a/desktop/lib/core/browser_lock.dart b/desktop/lib/core/browser_lock.dart
new file mode 100644
index 000000000..e644948b3
--- /dev/null
+++ b/desktop/lib/core/browser_lock.dart
@@ -0,0 +1,28 @@
+import 'dart:async';
+import 'dart:js_interop';
+
+import 'package:web/web.dart' as web;
+
+/// One writer across all tabs on this origin. The browser releases the lock
+/// when the callback settles or its tab closes; no expiring lease to race.
+Future<T> withBrowserLock<T>(String name, Future<T> Function() action) async {
+ final zone = Zone.current;
+ late T result;
+ Object? failure;
+ StackTrace? trace;
+ await web.window.navigator.locks
+ .request(
+ 'harness.web.v1.$name',
+ ((web.Lock _) => zone.run(() async {
+ try {
+ result = await action();
+ } catch (error, stack) {
+ failure = error;
+ trace = stack;
+ }
+ }).toJS).toJS,
+ )
+ .toDart;
+ if (failure != null) Error.throwWithStackTrace(failure!, trace!);
+ return result;
+}
diff --git a/desktop/lib/core/browser_storage.dart b/desktop/lib/core/browser_storage.dart
new file mode 100644
index 000000000..1e1382e47
--- /dev/null
+++ b/desktop/lib/core/browser_storage.dart
@@ -0,0 +1,2 @@
+export 'browser_storage_native.dart'
+ if (dart.library.js_interop) 'browser_storage_web.dart';
diff --git a/desktop/lib/core/browser_storage_native.dart b/desktop/lib/core/browser_storage_native.dart
new file mode 100644
index 000000000..f2d6c6500
--- /dev/null
+++ b/desktop/lib/core/browser_storage_native.dart
@@ -0,0 +1,4 @@
+String? readBrowserPreference(String key) =>
+ throw UnsupportedError('Browser storage is only available on web.');
+void writeBrowserPreference(String key, String value) =>
+ throw UnsupportedError('Browser storage is only available on web.');
diff --git a/desktop/lib/core/browser_storage_web.dart b/desktop/lib/core/browser_storage_web.dart
new file mode 100644
index 000000000..b6dc0b5dd
--- /dev/null
+++ b/desktop/lib/core/browser_storage_web.dart
@@ -0,0 +1,6 @@
+import 'package:web/web.dart' as web;
+
+String? readBrowserPreference(String key) =>
+ web.window.localStorage.getItem('harness.web.v1.$key');
+void writeBrowserPreference(String key, String value) =>
+ web.window.localStorage.setItem('harness.web.v1.$key', value);
diff --git a/desktop/lib/core/config.dart b/desktop/lib/core/config.dart
index 24ba266c2..8302d9605 100644
--- a/desktop/lib/core/config.dart
+++ b/desktop/lib/core/config.dart
@@ -11,10 +11,11 @@ class AppConfig {
this.localCliBaseUrl = 'http://127.0.0.1:18473',
});
- static const AppConfig dev = AppConfig(
- apiBaseUrl: 'https://harness-api.autonomous.ai',
- autonomousEnv: 'prod',
+ static const defaultApiUrl = String.fromEnvironment(
+ 'HARNESS_API_URL',
+ defaultValue: 'https://harness-api.autonomous.ai',
);
+ static const AppConfig dev = AppConfig(apiBaseUrl: defaultApiUrl);
/// HTTPS->wss, HTTP->ws for the hub endpoint.
String get wsBaseUrl {
diff --git a/desktop/lib/core/crash_log.dart b/desktop/lib/core/crash_log.dart
index 5131aea05..5283d1abd 100644
--- a/desktop/lib/core/crash_log.dart
+++ b/desktop/lib/core/crash_log.dart
@@ -40,7 +40,7 @@ class CrashLog {
error: error,
stackTrace: stackTrace,
);
- if (kUnderTest && testFile == null) return;
+ if (kIsWeb || (kUnderTest && testFile == null)) return;
try {
final file = _file;
// The directory may not exist yet, and the first run is exactly when this
diff --git a/desktop/lib/core/desktop_window.dart b/desktop/lib/core/desktop_window.dart
index 10af97564..a8240b4c3 100644
--- a/desktop/lib/core/desktop_window.dart
+++ b/desktop/lib/core/desktop_window.dart
@@ -1,8 +1,7 @@
-import 'dart:io' show Platform;
-
import 'package:window_manager/window_manager.dart';
import 'package:flutter/services.dart';
+import 'runtime_platform.dart';
import '../shared/theme/color_palette.dart';
import 'build_identity.dart';
@@ -14,7 +13,7 @@ import 'build_identity.dart';
/// runtime, thrown from `main` before the first frame. The guard therefore has
/// to live here rather than being left to each call site to remember.
bool get hasManagedWindow =>
- Platform.isMacOS || Platform.isWindows || Platform.isLinux;
+ RuntimePlatform.isMacOS || RuntimePlatform.isWindows || RuntimePlatform.isLinux;
/// Configures the native window before the first Flutter frame.
///
@@ -36,7 +35,7 @@ Future<void> configureDesktopWindow({
// The plugin's optional callback is a VoidCallback: an async callback would
// return before native setup finishes and detach any error from this future.
await windowManager.waitUntilReadyToShow(options);
- if (Platform.isMacOS) {
+ if (RuntimePlatform.isMacOS) {
await const MethodChannel('harness/swarm_tabs').invokeMethod('configure', {
'palette': palette.nativeColors,
});
diff --git a/desktop/lib/core/harness_file_store.dart b/desktop/lib/core/harness_file_store.dart
index 37b018bf9..115856aa3 100644
--- a/desktop/lib/core/harness_file_store.dart
+++ b/desktop/lib/core/harness_file_store.dart
@@ -1,234 +1,2 @@
-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;
- // Reads must still repair permissions changed outside this instance, but
- // launching chmod for every already-private directory and lock dominates
- // startup. Check the live mode each time; do not cache it across operations.
- // Include special bits as well as rwx when deciding that no repair is needed.
- final expected = int.parse(mode, radix: 8);
- final actual = (await FileStat.stat(path)).mode;
- if ((actual & 0xfff) == expected) 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';
-}
+export 'harness_file_store_native.dart'
+ if (dart.library.js_interop) 'harness_file_store_web.dart';
diff --git a/desktop/lib/core/harness_file_store_native.dart b/desktop/lib/core/harness_file_store_native.dart
new file mode 100644
index 000000000..37b018bf9
--- /dev/null
+++ b/desktop/lib/core/harness_file_store_native.dart
@@ -0,0 +1,234 @@
+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;
+ // Reads must still repair permissions changed outside this instance, but
+ // launching chmod for every already-private directory and lock dominates
+ // startup. Check the live mode each time; do not cache it across operations.
+ // Include special bits as well as rwx when deciding that no repair is needed.
+ final expected = int.parse(mode, radix: 8);
+ final actual = (await FileStat.stat(path)).mode;
+ if ((actual & 0xfff) == expected) 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/desktop/lib/core/harness_file_store_web.dart b/desktop/lib/core/harness_file_store_web.dart
new file mode 100644
index 000000000..70c68b3c1
--- /dev/null
+++ b/desktop/lib/core/harness_file_store_web.dart
@@ -0,0 +1,101 @@
+import 'package:web/web.dart' as web;
+
+import 'browser_lock.dart';
+import 'local_key_value_store.dart';
+
+/// The browser adapter behind the same state-store entry point as desktop.
+/// Sign-in, machine identity, links, and preferences persist on this origin.
+/// OAuth transactions stay tab-local in DirectLogin. Storage failures propagate.
+class HarnessFileStore
+ implements BatchLocalKeyValueStore, SynchronizedLocalKeyValueStore {
+ static final HarnessFileStore shared = HarnessFileStore();
+ static const _prefix = 'harness.web.v1.';
+ static const _migrated = '${_prefix}persistent_credentials';
+ static const _credentials = [
+ 'auth_access_token',
+ 'auth_refresh_token',
+ 'auth_autonomous_env',
+ 'auth_access_token_expires_at',
+ 'viewer_e2ee_identity_seed',
+ 'viewer_e2ee_machine_peers',
+ ];
+ Future<void>? _migration;
+
+ Future<void>
+ _ready() => _migration ??= withBrowserLock('migration', () async {
+ final local = web.window.localStorage;
+ final legacy = web.window.sessionStorage;
+ if (local.getItem(_migrated) == null &&
+ _credentials.any((key) => legacy.getItem('$_prefix$key') != null)) {
+ for (final key in _credentials) {
+ final value = legacy.getItem('$_prefix$key');
+ if (value != null) local.setItem('$_prefix$key', value);
+ }
+ local.setItem(_migrated, '1');
+ }
+ // An old tab must never resurrect credentials after a subsequent sign-out.
+ for (final key in _credentials) {
+ legacy.removeItem('$_prefix$key');
+ }
+ });
+
+ @override
+ Future<String?> read(String key) async {
+ await _ready();
+ return web.window.localStorage.getItem('$_prefix$key');
+ }
+
+ @override
+ Future<Map<String, String?>> readMany(Iterable<String> keys) async {
+ await _ready();
+ return {
+ for (final key in keys)
+ key: web.window.localStorage.getItem('$_prefix$key'),
+ };
+ }
+
+ @override
+ Future<void> write(String key, String value) async {
+ await _ready();
+ void write() {
+ if (_credentials.contains(key)) {
+ web.window.localStorage.setItem(_migrated, '1');
+ }
+ web.window.localStorage.setItem('$_prefix$key', value);
+ }
+
+ if (_credentials.contains(key)) {
+ await withBrowserLock('migration', () async => write());
+ } else {
+ write();
+ }
+ }
+
+ @override
+ Future<void> delete(String key) async {
+ await _ready();
+ void remove() {
+ if (_credentials.contains(key)) {
+ web.window.localStorage.setItem(_migrated, '1');
+ }
+ web.window.localStorage.removeItem('$_prefix$key');
+ web.window.sessionStorage.removeItem('$_prefix$key');
+ }
+
+ if (_credentials.contains(key)) {
+ await withBrowserLock('migration', () async => remove());
+ } else {
+ remove();
+ }
+ }
+
+ @override
+ Future<T> synchronized<T>(String scope, Future<T> Function() action) =>
+ withBrowserLock(scope, action);
+
+ /// Native-only services must never turn a browser path into a local file.
+ static String defaultDirectoryPath({
+ Map<String, String>? environment,
+ String? name,
+ }) => throw UnsupportedError('The browser has no Harness home directory.');
+}
diff --git a/desktop/lib/core/host_platform.dart b/desktop/lib/core/host_platform.dart
index 91db6e27e..fd3b46912 100644
--- a/desktop/lib/core/host_platform.dart
+++ b/desktop/lib/core/host_platform.dart
@@ -1,13 +1,15 @@
import 'dart:io';
+import 'runtime_platform.dart';
+
/// 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;
+bool get isMobileHost => RuntimePlatform.isIOS || RuntimePlatform.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`
+/// in a private container, and `RuntimePlatform.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
@@ -28,7 +30,7 @@ String? get containerHome {
// 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
+ return RuntimePlatform.isIOS
? '$container/Library/Application Support'
: container;
}
diff --git a/desktop/lib/core/local_hostname.dart b/desktop/lib/core/local_hostname.dart
index 8d96d271c..8db02abcb 100644
--- a/desktop/lib/core/local_hostname.dart
+++ b/desktop/lib/core/local_hostname.dart
@@ -1,4 +1,4 @@
-import 'dart:io';
+import 'runtime_platform.dart';
/// The machine's name exactly as the OS gives it, or null when it has none.
///
@@ -7,7 +7,7 @@ import 'dart:io';
/// label.
String? localHostnameOrNull() {
try {
- final host = Platform.localHostname.trim();
+ final host = RuntimePlatform.localHostname.trim();
return host.isEmpty ? null : host;
} catch (_) {
return null;
diff --git a/desktop/lib/core/local_key_value_store.dart b/desktop/lib/core/local_key_value_store.dart
index 106467ae8..33bf961ca 100644
--- a/desktop/lib/core/local_key_value_store.dart
+++ b/desktop/lib/core/local_key_value_store.dart
@@ -12,6 +12,21 @@ abstract interface class BatchLocalKeyValueStore implements LocalKeyValueStore {
Future<Map<String, String?>> readMany(Iterable<String> keys);
}
+/// A store shared by independent runtimes, such as browser tabs.
+abstract interface class SynchronizedLocalKeyValueStore
+ implements LocalKeyValueStore {
+ Future<T> synchronized<T>(String scope, Future<T> Function() action);
+}
+
+extension LocalKeyValueStoreSynchronization on LocalKeyValueStore {
+ Future<T> synchronized<T>(String scope, Future<T> Function() action) {
+ final store = this;
+ return store is SynchronizedLocalKeyValueStore
+ ? store.synchronized(scope, action)
+ : action();
+ }
+}
+
extension LocalKeyValueStoreBatchRead on LocalKeyValueStore {
/// Falls back to ordinary reads for stores without a batch operation.
Future<Map<String, String?>> readMany(Iterable<String> keys) async {
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index a761a5489..06d3e4b25 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -72,16 +72,19 @@ class SharedHarness {
required this.name,
this.engine,
required this.expiresAt,
+ this.ownerPublicKey,
});
final String id, agentId, name;
final String? engine;
final DateTime expiresAt;
+ final String? ownerPublicKey;
factory SharedHarness.fromJson(Map<String, dynamic> j) => SharedHarness(
id: j['id'] as String,
agentId: j['agentId'] as String,
name: j['name'] as String,
engine: j['engine'] as String?,
expiresAt: DateTime.parse(j['expiresAt'] as String),
+ ownerPublicKey: j['ownerPublicKey'] as String?,
);
}
diff --git a/desktop/lib/core/runtime_architecture.dart b/desktop/lib/core/runtime_architecture.dart
new file mode 100644
index 000000000..af2bb48b2
--- /dev/null
+++ b/desktop/lib/core/runtime_architecture.dart
@@ -0,0 +1,2 @@
+export 'runtime_architecture_native.dart'
+ if (dart.library.js_interop) 'runtime_architecture_web.dart';
diff --git a/desktop/lib/core/runtime_architecture_native.dart b/desktop/lib/core/runtime_architecture_native.dart
new file mode 100644
index 000000000..370f2a0f8
--- /dev/null
+++ b/desktop/lib/core/runtime_architecture_native.dart
@@ -0,0 +1,11 @@
+import 'dart:ffi' show Abi;
+
+String get runtimeAbi => Abi.current().toString();
+
+String get runtimeArchitecture => switch (Abi.current()) {
+ Abi.linuxArm64 || Abi.macosArm64 || Abi.windowsArm64 => 'arm64',
+ Abi.linuxX64 || Abi.macosX64 || Abi.windowsX64 => 'x64',
+ _ => throw UnsupportedError(
+ 'Harness updates do not support ${Abi.current()}',
+ ),
+};
diff --git a/desktop/lib/core/runtime_architecture_web.dart b/desktop/lib/core/runtime_architecture_web.dart
new file mode 100644
index 000000000..4ebec8a2e
--- /dev/null
+++ b/desktop/lib/core/runtime_architecture_web.dart
@@ -0,0 +1,2 @@
+String get runtimeAbi => 'web';
+String get runtimeArchitecture => 'web';
diff --git a/desktop/lib/core/runtime_platform.dart b/desktop/lib/core/runtime_platform.dart
new file mode 100644
index 000000000..e2696217a
--- /dev/null
+++ b/desktop/lib/core/runtime_platform.dart
@@ -0,0 +1,26 @@
+import 'dart:io' as io;
+
+import 'package:flutter/foundation.dart';
+
+/// Native host capabilities. A browser has no local OS API, even when it runs
+/// on a Mac. UI conventions should use Flutter's [defaultTargetPlatform].
+abstract final class RuntimePlatform {
+ static bool get isMacOS => !kIsWeb && io.Platform.isMacOS;
+ static bool get isLinux => !kIsWeb && io.Platform.isLinux;
+ static bool get isWindows => !kIsWeb && io.Platform.isWindows;
+ static bool get isIOS => !kIsWeb && io.Platform.isIOS;
+ static bool get isAndroid => !kIsWeb && io.Platform.isAndroid;
+ static Map<String, String> get environment =>
+ kIsWeb ? const {} : io.Platform.environment;
+ static String get operatingSystem =>
+ kIsWeb ? 'web' : io.Platform.operatingSystem;
+ static String get operatingSystemVersion =>
+ kIsWeb ? '' : io.Platform.operatingSystemVersion;
+ static String get localeName => kIsWeb
+ ? PlatformDispatcher.instance.locale.toLanguageTag()
+ : io.Platform.localeName;
+ static String get pathSeparator => kIsWeb ? '/' : io.Platform.pathSeparator;
+ static String get localHostname =>
+ kIsWeb ? 'Browser' : io.Platform.localHostname;
+ static String get resolvedExecutable => io.Platform.resolvedExecutable;
+}
diff --git a/desktop/lib/core/snapshot_store.dart b/desktop/lib/core/snapshot_store.dart
index cfa7990ef..018ce158f 100644
--- a/desktop/lib/core/snapshot_store.dart
+++ b/desktop/lib/core/snapshot_store.dart
@@ -15,9 +15,8 @@
/// rewrite it.
library;
-import 'dart:io';
-
-import 'harness_file_store.dart';
+export 'snapshot_store_native.dart'
+ if (dart.library.js_interop) 'snapshot_store_web.dart';
abstract interface class SnapshotStore {
/// The blob as it was written, or null when there is none.
@@ -33,56 +32,6 @@ abstract interface class SnapshotStore {
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 {
diff --git a/desktop/lib/core/snapshot_store_native.dart b/desktop/lib/core/snapshot_store_native.dart
new file mode 100644
index 000000000..5ff7813e8
--- /dev/null
+++ b/desktop/lib/core/snapshot_store_native.dart
@@ -0,0 +1,54 @@
+import 'dart:io';
+
+import 'harness_file_store.dart';
+import 'snapshot_store.dart';
+
+/// 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.
+ }
+ }
+}
diff --git a/desktop/lib/core/snapshot_store_web.dart b/desktop/lib/core/snapshot_store_web.dart
new file mode 100644
index 000000000..872be871a
--- /dev/null
+++ b/desktop/lib/core/snapshot_store_web.dart
@@ -0,0 +1,38 @@
+import 'package:web/web.dart' as web;
+
+import 'snapshot_store.dart';
+
+/// Browser implementation of the existing snapshot-store entry point. A cache
+/// may be discarded when storage is unavailable or full, just as on desktop.
+class FileSnapshotStore implements SnapshotStore {
+ FileSnapshotStore(this.name);
+ final String name;
+ String get _key => 'harness.web.v1.snapshot.$name';
+
+ @override
+ Future<String?> read() async {
+ try {
+ return web.window.localStorage.getItem(_key);
+ } on Object {
+ return null;
+ }
+ }
+
+ @override
+ Future<void> write(String contents) async {
+ try {
+ web.window.localStorage.setItem(_key, contents);
+ } on Object {
+ // Recomputed on the next launch.
+ }
+ }
+
+ @override
+ Future<void> clear() async {
+ try {
+ web.window.localStorage.removeItem(_key);
+ } on Object {
+ // Best-effort cache, never a prerequisite for opening the workspace.
+ }
+ }
+}
diff --git a/desktop/lib/core/test_run.dart b/desktop/lib/core/test_run.dart
index b2d627535..f322651de 100644
--- a/desktop/lib/core/test_run.dart
+++ b/desktop/lib/core/test_run.dart
@@ -1,4 +1,6 @@
-import 'dart:io';
+import 'package:flutter/foundation.dart';
+
+import 'runtime_platform.dart';
/// True inside `flutter test`, which sets `FLUTTER_TEST` for every test process.
///
@@ -16,4 +18,6 @@ import 'dart:io';
/// 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');
+final bool kUnderTest =
+ const bool.fromEnvironment('HARNESS_TEST') ||
+ (!kIsWeb && RuntimePlatform.environment.containsKey('FLUTTER_TEST'));
diff --git a/desktop/lib/core/viewer_mode.dart b/desktop/lib/core/viewer_mode.dart
index 431d0c562..1f549bb13 100644
--- a/desktop/lib/core/viewer_mode.dart
+++ b/desktop/lib/core/viewer_mode.dart
@@ -1,4 +1,6 @@
-import 'dart:io';
+import 'package:flutter/foundation.dart';
+
+import 'runtime_platform.dart';
/// Whether this build is a VIEWER: a window onto the user's machines and nothing more.
///
@@ -11,7 +13,8 @@ import 'dart:io';
/// `--dart-define=HARNESS_VIEWER_MODE=true`, which is how the path is developed and tested on a Mac
/// against real machines.
final bool kViewerMode =
+ kIsWeb ||
const bool.fromEnvironment('HARNESS_VIEWER_MODE') ||
- Platform.isIOS ||
- Platform.isAndroid ||
- Platform.isWindows;
+ RuntimePlatform.isIOS ||
+ RuntimePlatform.isAndroid ||
+ RuntimePlatform.isWindows;
diff --git a/desktop/lib/core/wire_counter.dart b/desktop/lib/core/wire_counter.dart
new file mode 100644
index 000000000..f4df37dfb
--- /dev/null
+++ b/desktop/lib/core/wire_counter.dart
@@ -0,0 +1,21 @@
+import 'dart:typed_data';
+
+/// The protocol shares JavaScript's exact integer range with the daemon.
+const maxSafeInteger = 9007199254740991;
+const _word = 4294967296;
+
+/// Write a big-endian u64 using two u32 words. Dart's JS runtime does not
+/// implement ByteData's uint64 accessors, and JS shifts truncate to 32 bits.
+/// Reject overflow rather than rounding a sequence or reusing an AEAD nonce.
+void writeWireCounter(ByteData data, int offset, int value) {
+ RangeError.checkValueInInterval(value, 0, maxSafeInteger, 'counter');
+ data.setUint32(offset, value ~/ _word, Endian.big);
+ data.setUint32(offset + 4, value % _word, Endian.big);
+}
+
+/// Null means a counter outside the exact range; callers discard that frame.
+int? readWireCounter(ByteData data, int offset) {
+ final upper = data.getUint32(offset, Endian.big);
+ if (upper > 0x1fffff) return null;
+ return upper * _word + data.getUint32(offset + 4, Endian.big);
+}
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index 479739730..2ce7afe0a 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -13,6 +13,9 @@ const int e2eVersion = 1;
/// 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 = {
+ 'harness_share_list',
+ 'harness_share_invite',
+ 'harness_share_remove',
// Harness's application RPC extensions (CLI e2ee/applicationFrames.ts).
'grid_fleet_capabilities',
'grid_fleet_run',
diff --git a/desktop/lib/e2ee/password_pake.dart b/desktop/lib/e2ee/password_pake.dart
index ae62819dc..abef64cfe 100644
--- a/desktop/lib/e2ee/password_pake.dart
+++ b/desktop/lib/e2ee/password_pake.dart
@@ -1,6 +1,7 @@
import 'dart:isolate';
import 'dart:typed_data';
+import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:unorm_dart/unorm_dart.dart' as unorm;
import 'bytes.dart';
@@ -27,6 +28,18 @@ const _scryptDkLen = 32;
Future<Uint8List> stretchPassword(String password, String machineId) {
final secret = utf8Bytes(unorm.nfkc(password));
final salt = sha256(utf8Bytes('e2e-remote-password-salt-v1|$machineId'));
+ // Browsers have no Dart isolates. Yield between batches of the same KDF
+ // instead of freezing the workspace or weakening the password cost.
+ if (kIsWeb) {
+ return scryptCooperative(
+ secret,
+ salt,
+ n: _scryptN,
+ r: _scryptR,
+ p: _scryptP,
+ dkLen: _scryptDkLen,
+ );
+ }
return Isolate.run(
() => scrypt(
secret,
@@ -44,5 +57,8 @@ Future<Uint8List> stretchPassword(String password, String machineId) {
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));
+RistrettoPoint pwCpaceGenerator(
+ List<int> stretched,
+ List<int> sid,
+ String ci,
+) => hashToRistretto255(lvCat([_pwDsi, stretched, sid, ci]), utf8Bytes(_pwDsi));
diff --git a/desktop/lib/e2ee/primitives.dart b/desktop/lib/e2ee/primitives.dart
index 3580418c1..2b9844226 100644
--- a/desktop/lib/e2ee/primitives.dart
+++ b/desktop/lib/e2ee/primitives.dart
@@ -4,6 +4,7 @@ import 'package:cryptography/cryptography.dart';
import 'package:cryptography/dart.dart';
import 'bytes.dart';
+import '../core/wire_counter.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/.
@@ -55,7 +56,7 @@ Uint8List hkdfSha256(
/// 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);
+ writeWireCounter(ByteData.sublistView(nonce), 0, counter);
return nonce;
}
diff --git a/desktop/lib/e2ee/replay_window.dart b/desktop/lib/e2ee/replay_window.dart
index 3f22ff5a7..90a4985de 100644
--- a/desktop/lib/e2ee/replay_window.dart
+++ b/desktop/lib/e2ee/replay_window.dart
@@ -1,12 +1,12 @@
+import '../core/wire_counter.dart' show maxSafeInteger;
+export '../core/wire_counter.dart' show maxSafeInteger;
+
/// 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;
diff --git a/desktop/lib/e2ee/scrypt.dart b/desktop/lib/e2ee/scrypt.dart
index a2f003255..7d8818b7f 100644
--- a/desktop/lib/e2ee/scrypt.dart
+++ b/desktop/lib/e2ee/scrypt.dart
@@ -15,8 +15,42 @@ Uint8List scrypt(
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');
+}) => _scryptSteps(password, salt, n: n, r: r, p: p, dkLen: dkLen).last!;
+
+/// Same computation, scheduled in bounded batches where isolates are absent.
+Future<Uint8List> scryptCooperative(
+ List<int> password,
+ List<int> salt, {
+ required int n,
+ required int r,
+ required int p,
+ required int dkLen,
+}) async {
+ for (final result in _scryptSteps(
+ password,
+ salt,
+ n: n,
+ r: r,
+ p: p,
+ dkLen: dkLen,
+ )) {
+ if (result != null) return result;
+ await Future<void>.delayed(Duration.zero);
+ }
+ throw StateError('scrypt: missing result');
+}
+
+Iterable<Uint8List?> _scryptSteps(
+ List<int> password,
+ List<int> salt, {
+ required int n,
+ required int r,
+ required int p,
+ required int dkLen,
+}) sync* {
+ 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));
@@ -25,27 +59,29 @@ Uint8List scrypt(
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);
+ yield* _roMix(b, i * blockWords, r, n, v, x, y, mix);
}
- return _pbkdf2Once(password, _wordsToBytes(b), dkLen);
+ yield _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,
- ]));
+ 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(
+Iterable<Uint8List?> _roMix(
Uint32List b,
int offset,
int r,
@@ -54,12 +90,13 @@ void _roMix(
Uint32List x,
Uint32List y,
Uint32List mix,
-) {
+) sync* {
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);
+ if ((i & 1023) == 1023) yield null;
}
final mask = n - 1;
final last = (2 * r - 1) * 16;
@@ -69,6 +106,7 @@ void _roMix(
x[k] ^= v[base + k];
}
_blockMix(x, y, mix, r);
+ if ((i & 1023) == 1023) yield null;
}
b.setRange(offset, offset + words, x);
}
diff --git a/desktop/lib/e2ee/terminal_cipher.dart b/desktop/lib/e2ee/terminal_cipher.dart
index 48302dfab..af004c38e 100644
--- a/desktop/lib/e2ee/terminal_cipher.dart
+++ b/desktop/lib/e2ee/terminal_cipher.dart
@@ -1,9 +1,9 @@
import 'dart:typed_data';
import '../terminal/terminal_binary.dart';
+import '../core/wire_counter.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
@@ -39,7 +39,8 @@ Uint8List? sealTerminalBinary(
header[4] = terminalBinaryVersion;
header[5] = frame.kind.code;
header[6] = frame.compressed ? _flagZlib : 0;
- final view = ByteData.sublistView(header)..setUint64(8, counter);
+ final view = ByteData.sublistView(header);
+ writeWireCounter(view, 8, counter);
final ciphertext = aeadSeal(
key,
counter,
@@ -66,10 +67,9 @@ Uint8List? sealTerminalBinary(
return null;
}
final view = ByteData.sublistView(raw);
- final counter = view.getUint64(8);
+ final counter = readWireCounter(view, 8);
final length = view.getUint32(16);
- if (counter < 0 ||
- counter > maxSafeInteger ||
+ if (counter == null ||
length < _tagBytes ||
length > maxTerminalPayloadBytesFor(kind) ||
raw.length != terminalBinaryHeaderBytes + length) {
diff --git a/desktop/lib/logging/install.dart b/desktop/lib/logging/install.dart
index 5bdd96e9e..4724c633d 100644
--- a/desktop/lib/logging/install.dart
+++ b/desktop/lib/logging/install.dart
@@ -1,3 +1,5 @@
+import 'package:flutter/foundation.dart';
+
import 'app_log.dart';
import 'cli_log.dart';
import 'debug_surface.dart';
@@ -21,6 +23,11 @@ const String kCliLogBase = 'cli';
/// 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() {
+ if (kIsWeb) {
+ appLog = StreamAppLog(logStream);
+ cliLog = StreamCliLog(logStream);
+ return;
+ }
final directory = DailyLogFile.defaultDirectory;
final file = FileAppLog(DailyLogFile(directory, kAppLogBase));
final cli = FileCliLog(DailyLogFile(directory, kCliLogBase));
diff --git a/desktop/lib/main.dart b/desktop/lib/main.dart
index 3ad85258f..19c59c68a 100644
--- a/desktop/lib/main.dart
+++ b/desktop/lib/main.dart
@@ -1,11 +1,9 @@
-
import 'app_shell.dart';
import 'screens/swarm_screen.dart';
-/// Harness for macOS, Linux and Windows: a swarm of terminal panes in one
+/// Harness for desktop and web: a swarm of terminal panes in one
/// window. Everything before the first frame, and every screen up to sign-in,
/// 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),
-);
+Future<void> main() =>
+ startHarness(authenticatedScreen: (app) => SwarmScreen(notifier: app));
diff --git a/desktop/lib/screens/login_screen.dart b/desktop/lib/screens/login_screen.dart
index 4ca004bcf..e8a1880ac 100644
--- a/desktop/lib/screens/login_screen.dart
+++ b/desktop/lib/screens/login_screen.dart
@@ -1,10 +1,12 @@
import 'package:flutter/material.dart';
+import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
import '../widgets/login_fleet_map.dart';
import '../widgets/login_relay_diagram.dart';
+import '../widgets/web_download_button.dart';
/// The sign-in screen.
///
@@ -12,8 +14,9 @@ import '../widgets/login_relay_diagram.dart';
/// window — the picture is [LoginFleetMap], and it moves only where a packet
/// moves. The privacy guarantee stays in the quiet footer.
///
-/// **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
+/// **All four states live here**, in one layout, rather than the two screens this
+/// used to be. The web uses a full-page fleet map and prominent CTA; native
+/// sign-in retains its compact card. Pressing Sign in once swapped the 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.
@@ -80,89 +83,212 @@ class LoginScreen extends StatelessWidget {
// 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: Stack(
- clipBehavior: Clip.none,
- children: [
- if (onClose != null)
- // Into the card's own padding, so the glyph sits in
- // the CORNER rather than level with the app mark —
- // which read as a misplaced control (owner,
- // 2026-09-23). Negative offsets need Clip.none above.
- Positioned(
- top: compact ? -12 : -16,
- right: compact ? -12 : -16,
- child: IconButton(
- key: const Key('login-close-button'),
- tooltip: 'Close',
- iconSize: 18,
- visualDensity: VisualDensity.compact,
- color: grid.AppPalette.textSecondary,
- icon: const Icon(Icons.close),
- onPressed: onClose,
- ),
+ body: kIsWeb
+ ? _webPage(context, waiting: waiting)
+ : 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,
),
- Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- const _AppMark(),
- SizedBox(height: gap),
- Text(
- 'Your agents, wherever they run',
- textAlign: TextAlign.center,
- style: grid.AppType.title(),
- ),
- const SizedBox(height: 8),
- Text(
- 'At home, at the office, in the cloud — every machine you '
- 'sign in to becomes part of one desk, here.',
- textAlign: TextAlign.center,
- style: Theme.of(context).textTheme.bodySmall,
- ),
- SizedBox(height: gap),
- if (showFleet) ...[
- const LoginFleetMap(),
- SizedBox(height: gap),
+ padding: EdgeInsets.all(compact ? 20 : 24),
+ child: Stack(
+ clipBehavior: Clip.none,
+ children: [
+ if (onClose != null)
+ // Into the card's own padding, so the glyph sits in
+ // the CORNER rather than level with the app mark —
+ // which read as a misplaced control (owner,
+ // 2026-09-23). Negative offsets need Clip.none above.
+ Positioned(
+ top: compact ? -12 : -16,
+ right: compact ? -12 : -16,
+ child: IconButton(
+ key: const Key('login-close-button'),
+ tooltip: 'Close',
+ iconSize: 18,
+ visualDensity: VisualDensity.compact,
+ color: grid.AppPalette.textSecondary,
+ icon: const Icon(Icons.close),
+ onPressed: onClose,
+ ),
+ ),
+ Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const _AppMark(),
+ SizedBox(height: gap),
+ Text(
+ 'Your agents, wherever they run',
+ textAlign: TextAlign.center,
+ style: grid.AppType.title(),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ 'At home, at the office, in the cloud — every machine you '
+ 'sign in to becomes part of one desk, here.',
+ textAlign: TextAlign.center,
+ style: Theme.of(context)
+ .textTheme
+ .bodySmall,
+ ),
+ SizedBox(height: gap),
+ if (showFleet) ...[
+ const LoginFleetMap(),
+ SizedBox(height: gap),
+ ],
+ _Action(notifier: notifier, waiting: waiting),
+ if (notifier.lastError != null &&
+ !notifier.sessionExpired) ...[
+ const SizedBox(height: 16),
+ _ErrorTile(
+ message: notifier.lastError!,
+ onRetry: notifier.login,
+ ),
+ ],
+ SizedBox(height: gap),
+ const _Seal(),
+ ],
+ ),
],
- _Action(notifier: notifier, waiting: waiting),
- if (notifier.lastError != null &&
- !notifier.sessionExpired) ...[
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _webPage(BuildContext context, {required bool waiting}) => Stack(
+ children: [
+ const Positioned.fill(child: LoginAurora()),
+ SafeArea(
+ child: Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 16, 12, 8),
+ child: Row(
+ children: [
+ Image.asset('assets/app_icon.png', width: 28, height: 28),
+ if (MediaQuery.sizeOf(context).width >= 480) ...[
+ const SizedBox(width: 12),
+ Text('Harness', style: grid.AppType.heading()),
+ ],
+ const Spacer(),
+ const WebDownloadButton(),
+ ],
+ ),
+ ),
+ Expanded(
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final compact = constraints.maxHeight < 650;
+ final gap = compact ? 16.0 : 24.0;
+ return SingleChildScrollView(
+ padding: const EdgeInsets.all(24),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ minHeight: (constraints.maxHeight - 48).clamp(
+ 0,
+ double.infinity,
+ ),
+ ),
+ child: Center(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 1000),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: 820,
+ ),
+ child: Text(
+ 'Your agents, wherever they run',
+ textAlign: TextAlign.center,
+ style: grid.AppType.display().copyWith(
+ fontSize:
+ compact || constraints.maxWidth < 600
+ ? 28
+ : 44,
+ height: 1.2,
+ ),
+ ),
+ ),
const SizedBox(height: 16),
- _ErrorTile(
- message: notifier.lastError!,
- onRetry: notifier.login,
+ ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: 650,
+ ),
+ child: Text(
+ 'At home, at the office, in the cloud — every machine you '
+ 'sign in to becomes part of one desk, here.',
+ textAlign: TextAlign.center,
+ style: grid.AppType.body().copyWith(
+ fontSize: 16,
+ height: 1.5,
+ ),
+ ),
+ ),
+ SizedBox(height: gap),
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: compact ? 560 : 960,
+ ),
+ child: const LoginFleetMap(seamless: true),
+ ),
+ SizedBox(height: gap),
+ ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: 520,
+ ),
+ child: _Action(
+ notifier: notifier,
+ waiting: waiting,
+ prominent: true,
+ ),
),
+ if (notifier.lastError != null &&
+ !notifier.sessionExpired) ...[
+ const SizedBox(height: 16),
+ ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: 520,
+ ),
+ child: _ErrorTile(
+ message: notifier.lastError!,
+ onRetry: notifier.login,
+ ),
+ ),
+ ],
+ SizedBox(height: gap),
+ const _Seal(divider: false),
],
- SizedBox(height: gap),
- const _Seal(),
- ],
+ ),
),
- ],
+ ),
),
- ),
- ),
+ );
+ },
),
),
],
),
),
- );
- }
+ ],
+ );
}
/// The button, and what it becomes while the browser is open.
@@ -172,10 +298,15 @@ class LoginScreen extends StatelessWidget {
/// 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});
+ const _Action({
+ required this.notifier,
+ required this.waiting,
+ this.prominent = false,
+ });
final AppNotifier notifier;
final bool waiting;
+ final bool prominent;
@override
State<_Action> createState() => _ActionState();
@@ -230,12 +361,20 @@ class _ActionState extends State<_Action> {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
+ final buttonStyle = widget.prominent
+ ? FilledButton.styleFrom(
+ minimumSize: const Size(248, 56),
+ padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 18),
+ textStyle: grid.AppType.heading(),
+ )
+ : null;
if (!widget.waiting) {
final signingOutFailed = notifier.signOutError != null;
return Column(
children: [
FilledButton.icon(
+ style: buttonStyle,
focusNode: _signInFocus,
autofocus: true,
onPressed: signingOutFailed ? notifier.logout : notifier.login,
@@ -251,7 +390,9 @@ class _ActionState extends State<_Action> {
child: Text(
notifier.signOutError ??
(notifier.sessionExpired ? notifier.lastError : null) ??
- 'Sign in through your browser to continue.',
+ (kIsWeb
+ ? 'Sign in to open your workspace.'
+ : 'Sign in through your browser to continue.'),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall,
),
@@ -269,6 +410,7 @@ class _ActionState extends State<_Action> {
return Column(
children: [
FilledButton.icon(
+ style: buttonStyle,
// Disabled, not hidden: the control the user just pressed has to stay
// where they left it, saying what it is doing.
onPressed: null,
@@ -417,15 +559,18 @@ class _ErrorTile extends StatelessWidget {
/// 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();
+ const _Seal({this.divider = true});
+ final bool divider;
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
return Column(
children: [
- Divider(height: 1, color: grid.AppPalette.divider),
- const SizedBox(height: 16),
+ if (divider) ...[
+ Divider(height: 1, color: grid.AppPalette.divider),
+ const SizedBox(height: 16),
+ ],
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 8154b1dc2..f4e38e3fb 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -1,16 +1,16 @@
import 'dart:math' as math;
import 'dart:async';
import 'dart:convert';
-import 'dart:io' show Platform;
import 'package:file_selector/file_selector.dart';
-import 'package:flutter/foundation.dart' show listEquals;
+import 'package:flutter/foundation.dart' show kIsWeb, listEquals;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:xterm/xterm.dart' show TerminalTheme;
+import '../core/runtime_platform.dart';
import '../analytics/analytics.dart';
import '../core/desktop_window.dart';
import '../core/harness_file_store.dart';
@@ -60,11 +60,11 @@ import '../widgets/engine_identity.dart';
import '../widgets/status_line.dart';
import '../widgets/workspace_status_line.dart';
import '../widgets/workspace_bar_control.dart';
+import '../widgets/web_download_button.dart';
import '../widgets/grid_model_picker.dart';
import '../store/store_mark.dart';
import '../store/store_screen.dart';
import '../widgets/harness_start_page.dart';
-import '../widgets/machines_panel.dart';
import '../widgets/harness_session_manager.dart';
import '../widgets/onboarding_card.dart';
import '../state/toolbar_notices.dart';
@@ -156,7 +156,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
/// tab closes nothing. Null between presses.
String? _middleDownTab;
late final bool _native =
- widget.nativeTabs ?? (Platform.isMacOS && !kUnderTest);
+ widget.nativeTabs ?? (RuntimePlatform.isMacOS && !kUnderTest);
late final SwarmProjectStore _projects =
widget.projectStore ??
SwarmProjectStore(storage: kUnderTest ? null : HarnessFileStore.shared);
@@ -164,7 +164,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
StreamSubscription<void>? _modelsRequests;
final _shellFocus = FocusNode(debugLabel: 'Swarm shell');
final _focusedModelController = GridModelPickerController();
- MachinesPanelHandle? _machinesPanel;
OverlayEntry? _modelsOverlay;
VoidCallback? _unregisterModels;
OverlayEntry? _harnessesOverlay;
@@ -407,7 +406,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.removeListener(_syncToolbarNotices);
_toolbarNotices.removeListener(_toolbarNoticesChanged);
_toolbarNotices.dispose();
- _machinesPanel?.close(restoreFocus: false);
+ _dismissMachinePrompt();
_unregisterModels?.call();
_modelsOverlay?.remove();
_modelsOverlay?.dispose();
@@ -509,8 +508,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
bool get _modelsVisible =>
_modelsOverlay != null || _search?.isModelMode == true;
- bool get _machinesVisible =>
- _machinesPanel != null || _search?.isMachineMode == true;
+ bool get _machinesVisible => _search?.isMachineMode == true;
bool get _harnessesVisible =>
_harnessesOverlay != null || _search?.scopePrefix.isEmpty == true;
@@ -518,7 +516,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
mounted && _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen;
void _runShortcut(String id) {
- _machinesPanel?.close(restoreFocus: false);
_closeModelsControls(restoreFocus: false);
_closeHarnessControls(restoreFocus: false);
if (id != 'navigation.command_bar') _closeCommandBar();
@@ -549,6 +546,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
id != 'models.list' &&
id != 'machines.list' &&
id != 'machine.link' &&
+ id != 'machines.connections' &&
id != 'navigation.needs_input' &&
id != 'swarm.new' &&
id != 'agent.add' &&
@@ -721,7 +719,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
void _onboardingChanged() {
if (!mounted) return;
- _machinesPanel?.rebuild();
_modelsOverlay?.markNeedsBuild();
_harnessesOverlay?.markNeedsBuild();
if (_native) _syncNative();
@@ -904,7 +901,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
void _paletteChanged() {
- _machinesPanel?.rebuild();
_modelsOverlay?.markNeedsBuild();
_harnessesOverlay?.markNeedsBuild();
_searchOverlay?.markNeedsBuild();
@@ -1268,7 +1264,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
return;
}
if (call.method == 'machineControls') {
- unawaited(_showMachinesControls());
+ unawaited(_openMachines());
await WidgetsBinding.instance.endOfFrame;
return;
}
@@ -1278,7 +1274,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
return;
}
if (call.method == 'linkMachine') {
- unawaited(_showMachinesControls());
+ unawaited(_openMachines());
await WidgetsBinding.instance.endOfFrame;
return;
}
@@ -1745,65 +1741,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
}
- Future<void> _showMachinesControls({String? initialMachineId}) async {
- if (_machinesPanel case final panel?) {
- panel.close();
- return;
- }
- if (!_shortcutsEnabled || _newHarness?.requestDismiss() == false) return;
- _closeNewHarness(restoreFocus: false);
- _closeSearch(restoreFocus: false);
- _closeCommandBar(restoreFocus: false);
- dismissTransientMenus();
- _preparePaneFocus();
- _onboarding.acknowledge(OnboardingStep.machines);
- final panel = openMachinesPanel(
- context,
- app,
- keymap: _keymap,
- initialMachineId: initialMachineId,
- onboarding: _onboarding,
- toolbarHeight: _native ? 0 : _tabBarHeight,
- );
- _machinesPanel = panel;
- _syncToolbarNotices();
- if (_native) _syncNative();
- setState(() {});
- final destination = await panel.closed;
- if (!mounted || !identical(_machinesPanel, panel)) return;
- _machinesPanel = null;
- _syncToolbarNotices();
- if (_native) _syncNative();
- setState(() {});
- // Let the removed panel release its focus before opening work.
- await WidgetsBinding.instance.endOfFrame;
- if (!mounted) return;
- final machine = destination == null ? null : app.stateOf(destination);
- if (machine != null) {
- if (machine.agents.isEmpty && !machine.machine.isShared) {
- await _newAgent(
- machineId: destination,
- placement: HarnessPlacement.currentTab,
- );
- } else {
- _openSearch(
- adding: true,
- query: '@',
- placement: HarnessPlacement.currentTab,
- );
- final machineRow = _search?.rows
- .where((row) => row.isMachine && row.machineId == destination)
- .firstOrNull;
- if (machineRow != null) _search!.submit(machineRow);
- }
- } else if (panel.restoreFocus && _shortcutsEnabled) {
- _shellFocus.requestFocus();
- final pane = app.focusedPane;
- if (pane != null) app.focusPane(pane.id, reveal: true);
- await _ensureEmptyEntry();
- }
- }
-
Future<void> _openMachines({String? initialMachineId}) async {
_onboarding.acknowledge(OnboardingStep.machines);
_openResourcePicker('@');
@@ -1888,7 +1825,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
? null
: machine?.projectOf(agent);
if (id == null) {
- await _showMachinesControls();
+ await _openMachines();
return;
}
await Future.wait([app.agentPreference.load(), app.projectHistory.load()]);
@@ -2408,7 +2345,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.machineStates.values.firstOrNull
: app.stateOf(focused.machineId);
if (machine == null) {
- await _showMachinesControls();
+ await _openMachines();
return;
}
final machineId = machine.machine.machineId;
@@ -3123,6 +3060,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_search!.removeListener(_syncSearch);
_search!.dispose();
_search = null;
+ _dismissMachinePrompt();
_modelSelectionTarget = null;
_modelSearchVisible = false;
app.modelManager.setPanelVisible(false);
@@ -3663,14 +3601,22 @@ class _SwarmScreenState extends State<SwarmScreen> {
_linkDialogMachineId = machine.machine.machineId;
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (mounted) {
- await _showMachinesControls(
- initialMachineId: machine.machine.machineId,
- );
+ await _openMachines(initialMachineId: machine.machine.machineId);
}
- _linkDialogMachineId = null;
+ // Keep the prompt's identity until the picker closes. Otherwise Escape
+ // would immediately reopen it on the next workspace update.
+ if (_search?.isMachineMode != true) _linkDialogMachineId = null;
});
}
+ void _dismissMachinePrompt() {
+ final id = _linkDialogMachineId;
+ _linkDialogMachineId = null;
+ if (id != null && app.stateOf(id)?.needsLink == true) {
+ app.dismissLinkPrompt(id);
+ }
+ }
+
// Keyboard actions and search commands execute the same callbacks.
late final Map<ShortcutAction, VoidCallback> _actionHandlers = {
ShortcutAction.newSwarm: _newTab,
@@ -3762,13 +3708,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
},
// `agent.restart` and `agent.clone` come from `_actionHandlers` above:
// both carry a ShortcutAction, so the loop already binds them.
- 'machine.link': _showMachinesControls,
+ 'machine.link': _openMachines,
'machines.manage': _manageMachines,
'machines.list': _openMachines,
'models.list': _togglePaneModels,
'harnesses.list': _toggleSessions,
'harnesses.manage': _toggleHarnessControls,
- 'machines.connections': _showMachinesControls,
+ 'machines.connections': _openMachines,
'models.manage': _toggleModelsControls,
'project.add': _addProject,
'keyboard.open_config': () => openKeyboardConfig(context),
@@ -4564,7 +4510,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
'${index + 1}:${names[app.swarms[index].id]}',
];
final toolHeight = workspaceBarControlHeight(context);
- final contentWidth = math.max(0.0, constraints.maxWidth - cell.width * 7);
+ final downloadWidth = kIsWeb
+ ? WebDownloadButton.widthOf(context) + cell.width
+ : 0.0;
+ final contentWidth = math.max(
+ 0.0,
+ constraints.maxWidth - cell.width * 7 - downloadWidth,
+ );
final tabBudget = contentWidth * .45;
_tabWidths = [
for (final label in labels)
@@ -4760,6 +4712,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
],
+ if (kIsWeb) ...[
+ SizedBox(width: cell.width),
+ const WebDownloadButton(),
+ ],
SizedBox(width: cell.width),
],
),
diff --git a/desktop/lib/settings/config_store.dart b/desktop/lib/settings/config_store.dart
index ec5dcb61f..09d7ce45b 100644
--- a/desktop/lib/settings/config_store.dart
+++ b/desktop/lib/settings/config_store.dart
@@ -16,7 +16,7 @@ class ConfigStore {
// 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';
+ static const String defaultBaseUrl = AppConfig.defaultApiUrl;
ConfigStore({LocalKeyValueStore? storage})
: _storage = storage ?? HarnessFileStore.shared;
diff --git a/desktop/lib/settings/sections/about_section.dart b/desktop/lib/settings/sections/about_section.dart
index 0ac86538a..29d8ce599 100644
--- a/desktop/lib/settings/sections/about_section.dart
+++ b/desktop/lib/settings/sections/about_section.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:harness/terminal/terminal_text.dart';
import '../../core/app_version.dart';
@@ -72,7 +73,9 @@ class _AboutSectionState extends State<AboutSection> {
),
const SizedBox(height: 12),
Text(
- widget.notifier.updateChecksEnabled
+ kIsWeb
+ ? 'Refresh the page to load the latest version.'
+ : widget.notifier.updateChecksEnabled
? 'Harness checks for a newer build when it starts, '
'and every six hours after that.'
: 'Updates are disabled in this build.',
@@ -123,12 +126,14 @@ class _AboutCard extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_Identity(state: _PillState.of(notifier, checking: checking)),
- const SizedBox(height: 18),
- Container(height: 1, color: grid.AppPalette.divider),
- const SizedBox(height: 14),
- _CheckRow(checking: checking, onCheck: onCheck),
- const SizedBox(height: 12),
- const _FlashRow(),
+ if (!kIsWeb) ...[
+ const SizedBox(height: 18),
+ Container(height: 1, color: grid.AppPalette.divider),
+ const SizedBox(height: 14),
+ _CheckRow(checking: checking, onCheck: onCheck),
+ const SizedBox(height: 12),
+ const _FlashRow(),
+ ],
],
),
);
@@ -226,7 +231,7 @@ class _VersionLineState extends State<_VersionLine> {
return Text(version, style: style);
},
),
- _StatusPill(state: state),
+ if (!kIsWeb) _StatusPill(state: state),
],
);
}
diff --git a/desktop/lib/settings/sections/debug_section.dart b/desktop/lib/settings/sections/debug_section.dart
index bcb67b3b0..f0280568f 100644
--- a/desktop/lib/settings/sections/debug_section.dart
+++ b/desktop/lib/settings/sections/debug_section.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../logging/log_file.dart';
@@ -85,19 +86,21 @@ class _DebugSectionState extends State<DebugSection> {
AppTheme.watch(context);
return SectionScaffold(
title: 'Debug',
- subtitle:
- 'Everything this app logged this session, and the dial\'s own log '
- 'as the daemon writes it — the same lines '
- '${DailyLogFile.defaultDirectory.path} keeps for a fortnight (the '
- 'dial\'s for a week). Credentials are stripped before anything is '
- 'written. Export logs zips the last seven days to the Desktop.',
+ subtitle: kIsWeb
+ ? 'Browser logs for this session. Credentials are redacted.'
+ : 'Everything this app logged this session, and the dial\'s own log '
+ 'as the daemon writes it — the same lines '
+ '${DailyLogFile.defaultDirectory.path} keeps for a fortnight (the '
+ 'dial\'s for a week). Credentials are stripped before anything is '
+ 'written. Export logs zips the last seven days to the Desktop.',
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Outside the builder below: what the two CLIs resolved to has nothing
// to do with the log, and a card that re-probed on every socket frame
// would be a second thing to explain.
- DebugPathsCard(probe: widget.probe ?? probeDebugEnvironment),
+ if (!kIsWeb)
+ DebugPathsCard(probe: widget.probe ?? probeDebugEnvironment),
const SizedBox(height: 14),
Expanded(
child: ListenableBuilder(
diff --git a/desktop/lib/settings/sections/debug_toolbar.dart b/desktop/lib/settings/sections/debug_toolbar.dart
index f0af8ec7c..5305c292e 100644
--- a/desktop/lib/settings/sections/debug_toolbar.dart
+++ b/desktop/lib/settings/sections/debug_toolbar.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:flutter/material.dart';
+import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../core/reveal_folder.dart';
@@ -31,10 +32,12 @@ class DebugToolbar extends StatelessWidget {
style: AppType.body(color: AppPalette.textSecondary),
),
),
- const _ExportLogsPill(),
- const SizedBox(width: 6),
- const _OpenLogsPill(),
- const SizedBox(width: 6),
+ if (!kIsWeb) ...[
+ const _ExportLogsPill(),
+ const SizedBox(width: 6),
+ const _OpenLogsPill(),
+ const SizedBox(width: 6),
+ ],
ToolbarPill(
// Visible and dead when there is nothing to clear, rather than gone:
// a control that disappears takes its own explanation with it.
diff --git a/desktop/lib/settings/sections/usage_section.dart b/desktop/lib/settings/sections/usage_section.dart
index f4839676a..8422ab7c2 100644
--- a/desktop/lib/settings/sections/usage_section.dart
+++ b/desktop/lib/settings/sections/usage_section.dart
@@ -23,6 +23,7 @@ library;
import 'dart:async';
import 'package:flutter/material.dart';
+import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../core/test_run.dart';
@@ -106,18 +107,28 @@ class _UsageSectionState extends State<UsageSection> {
// walks every transcript under a real `~/.claude`, and a test run must
// depend on neither the machine it lands on nor whoever was working on it.
// A test that wants figures injects a controller already holding them.
- if (!kUnderTest) unawaited(_controller.load());
+ if (!kUnderTest && !kIsWeb) unawaited(_controller.load());
}
@override
void dispose() {
- if (_ownsController) _controller.dispose();
+ if (_ownsController && !kIsWeb) _controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
+ if (kIsWeb) {
+ return SectionScaffold(
+ title: 'Usage',
+ subtitle: 'Activity in this browser. Local transcript usage is available in the desktop app.',
+ child: ListenableBuilder(
+ listenable: _stats,
+ builder: (context, _) => StatsSummaryCards(summary: _stats.summary),
+ ),
+ );
+ }
return SectionScaffold(
title: 'Usage',
subtitle:
diff --git a/desktop/lib/settings/settings_section.dart b/desktop/lib/settings/settings_section.dart
index 4f3fc110d..a7d60dbd8 100644
--- a/desktop/lib/settings/settings_section.dart
+++ b/desktop/lib/settings/settings_section.dart
@@ -1,4 +1,5 @@
import 'package:flutter/widgets.dart';
+import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../logging/debug_surface.dart';
@@ -61,7 +62,8 @@ List<SettingsGroup> get settingsGroups =>
@visibleForTesting
List<SettingsGroup> settingsGroupsFor({required bool debugSurface}) {
bool visible(SettingsSection section) =>
- debugSurface || !_kDeveloperSections.contains(section);
+ (!kIsWeb || section != SettingsSection.devices) &&
+ (debugSurface || !_kDeveloperSections.contains(section));
return [
for (final group in _kSettingsGroups)
if (group.sections.any(visible))
diff --git a/desktop/lib/sharing/shared_harness_panel.dart b/desktop/lib/sharing/shared_harness_panel.dart
index a2c4f29d3..b28c50bf0 100644
--- a/desktop/lib/sharing/shared_harness_panel.dart
+++ b/desktop/lib/sharing/shared_harness_panel.dart
@@ -15,6 +15,7 @@ import '../terminal/terminal_binary.dart';
import '../terminal/terminal_session.dart';
import '../widgets/terminal_panel.dart';
import '../ws/ws_conn.dart';
+import '../viewer/observer_relay_codec.dart';
class SharedHarnessPanel extends StatefulWidget {
const SharedHarnessPanel({
@@ -60,6 +61,7 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
void _start() {
final generation = ++_generation;
+ final viewer = widget.notifier.viewer;
final uri = Uri.parse(widget.notifier.config.localCliBaseUrl)
.replace(scheme: 'ws', path: '/api/local-ws');
_terminal = TerminalSession(
@@ -74,14 +76,31 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
resyncTimeout: const Duration(seconds: 15),
);
_connection = WsConn(
- wsBaseUrl: '',
+ wsBaseUrl: widget.notifier.config.wsBaseUrl,
autonomousEnv: widget.notifier.config.autonomousEnv,
machineId: widget.pane.machineId,
observerShareId: widget.grant.id,
- transportKind: WsTransportKind.localPlaintext,
+ transportKind: viewer == null
+ ? WsTransportKind.localPlaintext
+ : WsTransportKind.cloudE2ee,
localWsUri: uri,
- localTransport: widget.notifier.localDaemonTransport,
- accessTokenProvider: (_, _) async => '',
+ localTransport: viewer == null
+ ? widget.notifier.localDaemonTransport
+ : null,
+ accessTokenProvider: (force, failedToken) async => viewer == null
+ ? ''
+ : viewer.auth.accessToken(force: force, failedToken: failedToken),
+ relayCodecs: viewer == null
+ ? null
+ : (_) async {
+ final owner = widget.grant.ownerPublicKey;
+ if (owner == null || owner.isEmpty) return null;
+ return ObserverRelayCodec.create(
+ machineId: widget.pane.machineId,
+ shareId: widget.grant.id,
+ ownerPublicKey: owner,
+ );
+ },
onAuthFailure: (reason) {
if (generation == _generation) _end(reason);
},
@@ -186,7 +205,9 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
if (!widget.hasAccess && !_ended) {
_end('Access removed or invitation expired.');
} else if (widget.hasAccess &&
- (!oldWidget.hasAccess || widget.grant.id != oldWidget.grant.id)) {
+ (!oldWidget.hasAccess ||
+ widget.grant.id != oldWidget.grant.id ||
+ widget.grant.ownerPublicKey != oldWidget.grant.ownerPublicKey)) {
unawaited(_connection.close());
_terminal.dispose();
_ended = false;
diff --git a/desktop/lib/shortcuts/app_keymap.dart b/desktop/lib/shortcuts/app_keymap.dart
index 14e737d9a..d15dd5e20 100644
--- a/desktop/lib/shortcuts/app_keymap.dart
+++ b/desktop/lib/shortcuts/app_keymap.dart
@@ -1,5 +1,6 @@
import 'dart:io';
+import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/widgets.dart';
import 'app_shortcuts.dart';
@@ -199,7 +200,8 @@ List<ShortcutRow> effectiveShortcutRows(
.toList();
return matches.length == 1 &&
matches.single.keys.length == 1 &&
- matches.single.keys.single == KeyStroke.parse('cmd+${i + 1}');
+ matches.single.keys.single ==
+ KeyStroke.parse(platformWorkspaceBinding('cmd+${i + 1}'));
}).every((value) => value);
final shortcuts = appShortcuts();
return [
@@ -238,7 +240,7 @@ List<ShortcutRow> effectiveShortcutRows(
const ShortcutRow(
label: 'Select tabs 1–9',
chords: [
- ['⌘', '1 – 9'],
+ [kIsWeb ? 'Alt' : '⌘', '1 – 9'],
],
group: ShortcutGroup.navigate,
),
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index 611b8e553..bd98d9b7d 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -349,33 +349,76 @@ const AppShortcut kDebugShortcut = AppShortcut(
/// 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)
- for (final shortcut in kSwarmShortcuts)
- if (shortcut.action == ShortcutAction.addAgent &&
- defaultTargetPlatform == TargetPlatform.linux)
- AppShortcut(
- action: shortcut.action,
- activator: const SingleActivator(
- LogicalKeyboardKey.keyO,
- control: true,
- ),
- label: shortcut.label,
- group: shortcut.group,
+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)
+ for (final shortcut in kSwarmShortcuts)
+ if (!kIsWeb &&
+ shortcut.action == ShortcutAction.addAgent &&
+ defaultTargetPlatform == TargetPlatform.linux)
+ AppShortcut(
+ action: shortcut.action,
+ activator: const SingleActivator(
+ LogicalKeyboardKey.keyO,
+ control: true,
+ ),
+ label: shortcut.label,
+ group: shortcut.group,
+ )
+ else
+ shortcut,
+ if (kDebugSurfaceEnabled) kDebugShortcut,
+ ]
+ .where(
+ (shortcut) =>
+ !kIsWeb || shortcut.activator.trigger != LogicalKeyboardKey.tab,
)
- else
- shortcut,
- if (kDebugSurfaceEnabled) kDebugShortcut,
-];
+ .map(_platformShortcut)
+ .toList(growable: false);
+
+/// The browser owns Command/Control keys such as Print, New Tab and Close.
+/// Web uses Option/Alt as its workspace prefix. Editing and terminal Control
+/// keys keep their normal behavior; help and live bindings share this mapping.
+String get workspaceCommandModifier => kIsWeb ? 'alt' : 'cmd';
+
+String platformWorkspaceBinding(String keys) {
+ if (!kIsWeb || !keys.split('+').contains('cmd')) return keys;
+ final parts = keys.split('+');
+ return {
+ for (final part in parts) part == 'cmd' ? workspaceCommandModifier : part,
+ }.join('+');
+}
+
+SingleActivator _platformActivator(SingleActivator keys) {
+ if (!kIsWeb || !keys.meta) return keys;
+ final modifier = workspaceCommandModifier;
+ return SingleActivator(
+ keys.trigger,
+ meta: modifier == 'cmd',
+ control: keys.control || modifier == 'ctrl',
+ alt: keys.alt || modifier == 'alt',
+ shift: keys.shift,
+ includeRepeats: keys.includeRepeats,
+ );
+}
+
+AppShortcut _platformShortcut(AppShortcut shortcut) => !kIsWeb
+ ? shortcut
+ : AppShortcut(
+ action: shortcut.action,
+ activator: _platformActivator(shortcut.activator),
+ label: shortcut.label,
+ group: shortcut.group,
+ );
/// Swarm bindings replace the old workspace navigation in the retained legacy
/// screen. Live Swarm bindings, tooltips, and help all use this same catalog.
@@ -519,7 +562,7 @@ const kSwarmShortcuts = [
/// shortcut sheet prints one row; pane movement uses Command-arrows.
const int kTabDigitCount = 9;
-List<SingleActivator> tabDigitActivators() => const [
+List<SingleActivator> tabDigitActivators() => (const [
SingleActivator(LogicalKeyboardKey.digit1, meta: true),
SingleActivator(LogicalKeyboardKey.digit2, meta: true),
SingleActivator(LogicalKeyboardKey.digit3, meta: true),
@@ -529,7 +572,7 @@ List<SingleActivator> tabDigitActivators() => const [
SingleActivator(LogicalKeyboardKey.digit7, meta: true),
SingleActivator(LogicalKeyboardKey.digit8, meta: true),
SingleActivator(LogicalKeyboardKey.digit9, meta: true),
-];
+]).map(_platformActivator).toList(growable: false);
/// One line in the shortcuts UI: what it does, and every chord that does it.
///
@@ -587,7 +630,7 @@ List<ShortcutRow> shortcutRows() {
final digits = ShortcutRow(
label: 'Select tabs 1–9',
chords: const [
- ['⌘', '1 – $kTabDigitCount'],
+ [kIsWeb ? 'Alt' : '⌘', '1 – $kTabDigitCount'],
],
group: ShortcutGroup.navigate,
);
@@ -666,16 +709,16 @@ 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) '⌘',
+ if (activator.control) kIsWeb ? 'Ctrl' : '⌃',
+ if (activator.alt) kIsWeb ? 'Alt' : '⌥',
+ if (activator.shift) kIsWeb ? 'Shift' : '⇧',
+ if (activator.meta) kIsWeb ? 'Cmd' : '⌘',
_keyLabel(activator.trigger),
];
/// "⇧⌘]" — the way a Mac menu prints it, in the order Apple prints it.
String describeShortcut(SingleActivator activator) =>
- describeShortcutKeys(activator).join();
+ describeShortcutKeys(activator).join(kIsWeb ? '+' : '');
String _keyLabel(LogicalKeyboardKey key) {
// keyLabel spells these out ("Arrow Left"), which is not how a Mac prints a
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 7dcf89e84..7c2ab7a54 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -28,23 +28,30 @@ class HarnessCommand {
/// 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 {
- if (id == 'navigation.commands' &&
+ if (!kIsWeb &&
+ id == 'navigation.commands' &&
defaultTargetPlatform == TargetPlatform.linux) {
return const ['ctrl+shift+p'];
}
- if (id == 'harnesses.list' &&
+ if (!kIsWeb &&
+ id == 'harnesses.list' &&
defaultTargetPlatform == TargetPlatform.linux) {
return const ['ctrl+p'];
}
- if (id == 'models.list' && defaultTargetPlatform == TargetPlatform.linux) {
+ if (!kIsWeb &&
+ id == 'models.list' &&
+ defaultTargetPlatform == TargetPlatform.linux) {
return const ['ctrl+i', 'cmd+i'];
}
- if (id == 'picker.complete' &&
+ if (!kIsWeb &&
+ id == 'picker.complete' &&
defaultTargetPlatform == TargetPlatform.linux) {
// Ctrl-I opens Models on Linux, including from another picker scope.
return const ['tab'];
}
- return action == null ? extraKeys : _workspaceKeys[action] ?? const [];
+ return action == null
+ ? extraKeys.map(platformWorkspaceBinding).toList(growable: false)
+ : _workspaceKeys[action] ?? const [];
}
final ShortcutAction? action;
@@ -777,10 +784,10 @@ ResolvedKeymap get harnessDefaultKeymap =>
);
List<String> describeKeyStrokeKeys(KeyStroke stroke) => [
- if (stroke.control) '⌃',
- if (stroke.alt) '⌥',
- if (stroke.shift) '⇧',
- if (stroke.command) '⌘',
+ if (stroke.control) kIsWeb ? 'Ctrl' : '⌃',
+ if (stroke.alt) kIsWeb ? 'Alt' : '⌥',
+ if (stroke.shift) kIsWeb ? 'Shift' : '⇧',
+ if (stroke.command) kIsWeb ? 'Cmd' : '⌘',
const {
'left': '←',
'right': '→',
@@ -809,6 +816,6 @@ List<String> describeKeyStrokeKeys(KeyStroke stroke) => [
stroke.key.toUpperCase(),
];
String describeKeyStroke(KeyStroke stroke) =>
- describeKeyStrokeKeys(stroke).join();
+ describeKeyStrokeKeys(stroke).join(kIsWeb ? '+' : '');
String describeKeyBinding(KeyBinding binding) =>
binding.keys.map(describeKeyStroke).join(' ');
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 9cb78aedd..cf84a9ee9 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -510,7 +510,8 @@ class AppNotifier extends ChangeNotifier {
/// [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;
+ CliLink? _cliLink;
+ CliLink get cliLink => _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
@@ -1733,7 +1734,6 @@ class AppNotifier extends ChangeNotifier {
projectHistory = ProjectHistory(paneLayoutStore?.storage),
session = authSession,
_store = configStore,
- cliLink = cliLink ?? CliLink(),
config = configStore?.config ?? config,
viewer =
viewer ??
@@ -1743,6 +1743,7 @@ class AppNotifier extends ChangeNotifier {
session: authSession,
)
: null) {
+ _cliLink = cliLink;
this.cliLogin = cliLogin ?? this.viewer?.login ?? CliLogin();
this.peerLinks = peerLinks ?? this.viewer?.links ?? this.cliLink;
_autonomousEnv = this.config.autonomousEnv;
@@ -1769,7 +1770,7 @@ class AppNotifier extends ChangeNotifier {
config: config,
session: session,
auth: viewer?.auth,
- localTransport: localDaemonTransport,
+ localTransport: viewer == null ? localDaemonTransport : null,
);
/// How this app reaches the local CLI — its Unix socket or the loopback
@@ -2579,6 +2580,9 @@ class AppNotifier extends ChangeNotifier {
debugPrint('bootstrap: fallback to login after error: $error\n$stack');
currentUser = null;
status = AppStatus.unauthenticated;
+ if (viewer != null) {
+ _lastError = 'Could not complete sign-in. Please sign in again.';
+ }
notifyListeners();
} finally {
// A `finally` rather than a call per exit path: bootstrap resolves four
@@ -2731,6 +2735,9 @@ class AppNotifier extends ChangeNotifier {
);
currentUser = null;
status = AppStatus.unauthenticated;
+ if (viewer != null) {
+ _lastError = 'Could not complete sign-in. Please sign in again.';
+ }
notifyListeners();
}
}
@@ -2945,7 +2952,9 @@ class AppNotifier extends ChangeNotifier {
// 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…';
+ _bootStatusMessage = viewer == null
+ ? 'Starting local service…'
+ : 'Opening workspace…';
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
@@ -4024,7 +4033,7 @@ class AppNotifier extends ChangeNotifier {
void _ensurePool() {
if (_pool != null) return;
_pool = WsPool(
- localTransport: localDaemonTransport,
+ localTransport: viewer == null ? localDaemonTransport : null,
wsBaseUrl: config.wsBaseUrl,
autonomousEnv: _autonomousEnv,
// Every real desktop WsConn dials the local CLI's loopback WS (transportKind.localPlaintext, see
@@ -9499,7 +9508,7 @@ class AppNotifier extends ChangeNotifier {
/// 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: selecting it brings up the Machines panel
+ /// already needs linking: selecting it brings up the Machines picker
/// (`SwarmScreen._maybeLink`), so opening a tile here too would just be a
/// redundant "not linked" pane sitting behind it. Selecting is still worth
/// doing — it's what makes that gate notice this machine — the tile is not.
@@ -11740,6 +11749,7 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
+ viewer?.auth.dispose();
_modelManager?.dispose();
_modelsMenu?.dispose();
for (final project in _orchestratorProjects.values) {
diff --git a/desktop/lib/state/grid_pictures.dart b/desktop/lib/state/grid_pictures.dart
index 625e42845..c4ce27ace 100644
--- a/desktop/lib/state/grid_pictures.dart
+++ b/desktop/lib/state/grid_pictures.dart
@@ -25,7 +25,9 @@ class GridPictures extends ChangeNotifier {
/// How many answers [machineId]'s picture has taken so far. A read captures it when it starts, so
/// that an answer which was already on its way when a push landed cannot overwrite the push.
int epochOf(String machineId) =>
- (_generation << 32) | (_epochs[machineId] ?? 0);
+ // JavaScript bitwise operations truncate to 32 bits. Keep account
+ // generations distinct from machine revisions in the browser too.
+ _generation * 4294967296 + (_epochs[machineId] ?? 0);
/// Take [answer] as [machineId]'s picture. With [ifEpoch], only when nothing else has been
/// adopted for that machine since the caller read [epochOf]. Returns whether it was adopted.
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index c7a4d1a4d..7ca42a732 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -8,6 +8,7 @@ import 'package:collection/collection.dart' show compareNatural;
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
+import '../core/runtime_platform.dart';
import '../analytics/analytics.dart';
import '../core/codex_profiles.dart';
import '../core/dsh_catalog.dart';
@@ -415,7 +416,7 @@ class NewHarnessController extends ChangeNotifier {
_machineId = draft?.machineId ?? machineId,
_autoProject = autoProject || draft?.project.generated != null,
_now = now ?? DateTime.now,
- _home = home ?? Platform.environment['HOME'] {
+ _home = home ?? RuntimePlatform.environment['HOME'] {
final explicitSelection =
draft != null || engine != null || harnessId != null;
_rememberedAgent = !explicitSelection;
diff --git a/desktop/lib/terminal/terminal_binary.dart b/desktop/lib/terminal/terminal_binary.dart
index e9b21c37b..3887395bf 100644
--- a/desktop/lib/terminal/terminal_binary.dart
+++ b/desktop/lib/terminal/terminal_binary.dart
@@ -1,5 +1,7 @@
import 'dart:typed_data';
+import '../core/wire_counter.dart';
+
const terminalLocalVersion = 1;
const terminalLocalHeaderBytes = 12;
const terminalLocalMaxPayloadBytes = 512 * 1024;
@@ -115,7 +117,7 @@ String _uuidString(Uint8List bytes) {
Uint8List? encodeTerminalPlain(TerminalBinaryFrame frame) {
final id = _uuidBytes(frame.streamId);
- if (id == null || frame.seq < 0) return null;
+ if (id == null || frame.seq < 0 || frame.seq > maxSafeInteger) return null;
if ((frame.kind == TerminalBinaryKind.input ||
frame.kind == TerminalBinaryKind.sync ||
frame.kind == TerminalBinaryKind.paste ||
@@ -129,8 +131,8 @@ Uint8List? encodeTerminalPlain(TerminalBinaryFrame frame) {
}
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);
+ final view = ByteData.sublistView(output);
+ writeWireCounter(view, 16, frame.seq);
if (frame.kind == TerminalBinaryKind.keyframe) {
final cols = frame.cols;
final rows = frame.rows;
@@ -169,10 +171,12 @@ TerminalBinaryFrame? decodeTerminalPlain(
return null;
}
final view = ByteData.sublistView(plaintext);
+ final seq = readWireCounter(view, 16);
+ if (seq == null) return null;
return TerminalBinaryFrame(
kind: kind,
streamId: _uuidString(Uint8List.sublistView(plaintext, 0, 16)),
- seq: view.getUint64(16, Endian.big),
+ seq: seq,
bytes: Uint8List.fromList(plaintext.sublist(metaBytes)),
compressed: (flags & _flagZlib) != 0,
cols: kind == TerminalBinaryKind.keyframe
diff --git a/desktop/lib/terminal/terminal_font_store.dart b/desktop/lib/terminal/terminal_font_store.dart
index db623cce3..d822bf483 100644
--- a/desktop/lib/terminal/terminal_font_store.dart
+++ b/desktop/lib/terminal/terminal_font_store.dart
@@ -28,6 +28,7 @@ import 'terminal_typography.dart';
/// carried to a Linux box still loads, and the Settings dropdown keeps showing
/// whatever is actually selected (see `_FamilyDropdown`).
enum TerminalFontChoice {
+ robotoMono('Roboto Mono', webTerminalFontFamily, []),
sfMono('SF Mono', macTerminalFontFamily, macTerminalFontFallback),
menlo('Menlo', 'Menlo', ['Monaco', 'Courier New', 'monospace']),
monaco('Monaco', 'Monaco', ['Menlo', 'Courier New', 'monospace']),
@@ -85,12 +86,13 @@ enum TerminalFontChoice {
/// 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;
+ static List<TerminalFontChoice> get available => kIsWeb
+ ? const [robotoMono]
+ : (hasAppleFonts ? _macChoices : _linuxChoices);
/// What a fresh install opens with, and what `reset()` returns to.
static TerminalFontChoice get defaultForPlatform =>
- hasAppleFonts ? sfMono : dejaVuSansMono;
+ kIsWeb ? robotoMono : (hasAppleFonts ? sfMono : dejaVuSansMono);
}
/// The user's chosen terminal typography (family + size), remembered across
@@ -153,7 +155,11 @@ class TerminalFontStore extends ValueNotifier<TerminalStyle> {
final savedFamily = saved[_familyKey];
final savedSize = saved[_sizeKey];
final choice = TerminalFontChoice.values
- .where((c) => c.name == savedFamily)
+ .where(
+ (c) =>
+ c.name == savedFamily &&
+ (!kIsWeb || c == TerminalFontChoice.robotoMono),
+ )
.firstOrNull;
final size = savedSize == null ? null : double.tryParse(savedSize);
value = _styleFor(
diff --git a/desktop/lib/terminal/terminal_link_opener.dart b/desktop/lib/terminal/terminal_link_opener.dart
index 21d04a3ff..f88f15d48 100644
--- a/desktop/lib/terminal/terminal_link_opener.dart
+++ b/desktop/lib/terminal/terminal_link_opener.dart
@@ -1,10 +1,13 @@
import 'dart:io';
+import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:url_launcher/url_launcher.dart';
import 'terminal_links.dart';
import 'remote_media_download.dart';
+import '../core/runtime_platform.dart';
+
/// Uses the existing OS launcher, never a shell command built from agent text.
class TerminalLinkOpener {
TerminalLinkOpener({
@@ -16,9 +19,9 @@ class TerminalLinkOpener {
_fileExists = fileExists ?? _exists,
_homeDirectory =
homeDirectory ??
- Platform.environment['HOME'] ??
- Platform.environment['USERPROFILE'],
- _windows = windows ?? Platform.isWindows;
+ RuntimePlatform.environment['HOME'] ??
+ RuntimePlatform.environment['USERPROFILE'],
+ _windows = windows ?? RuntimePlatform.isWindows;
final Future<bool> Function(Uri) _launch;
final Future<bool> Function(String) _fileExists;
@@ -42,6 +45,9 @@ class TerminalLinkOpener {
try {
final parsed = Uri.tryParse(target);
if (parsed == null) return 'This link is not supported.';
+ if (kIsWeb && parsed.scheme != 'https' && parsed.scheme != 'http') {
+ return 'File previews are available in the desktop app.';
+ }
Uri uri;
if (parsed.scheme == 'https' || parsed.scheme == 'http') {
if (parsed.host.isEmpty) return 'This link is not supported.';
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index fa427c556..46750faea 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -1,9 +1,9 @@
import 'dart:async';
import 'dart:convert';
-import 'dart:io';
import 'dart:math';
import 'package:flutter/foundation.dart';
+import 'package:archive/archive.dart' show ZLibDecoder;
import 'package:xterm/xterm.dart';
import '../core/crash_log.dart';
@@ -837,7 +837,7 @@ class TerminalSession extends ChangeNotifier {
Uint8List? _decodeBinaryBytes(TerminalBinaryFrame frame) {
try {
return frame.compressed
- ? Uint8List.fromList(ZLibDecoder().convert(frame.bytes))
+ ? const ZLibDecoder().decodeBytes(frame.bytes, verify: true)
: frame.bytes;
} catch (_) {
return null;
diff --git a/desktop/lib/terminal/terminal_typography.dart b/desktop/lib/terminal/terminal_typography.dart
index a60e6662f..0a50d055f 100644
--- a/desktop/lib/terminal/terminal_typography.dart
+++ b/desktop/lib/terminal/terminal_typography.dart
@@ -1,5 +1,7 @@
import '../core/apple_fonts.dart';
+import 'package:flutter/foundation.dart' show kIsWeb;
+
/// The default terminal face, per platform.
///
/// Every family named here has to actually resolve on the OS it is named for,
@@ -56,6 +58,9 @@ const macTerminalFontFallback = <String>[
/// goes ragged in exactly the places a coding agent puts its output.
const linuxTerminalFontFamily = 'DejaVu Sans Mono';
+/// Bundled with the app: CanvasKit cannot resolve the browser's system fonts.
+const webTerminalFontFamily = 'Roboto Mono';
+
const linuxTerminalFontFallback = <String>[
'Ubuntu Sans Mono',
'Noto Sans Mono',
@@ -68,11 +73,13 @@ const linuxTerminalFontFallback = <String>[
/// 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;
+String get terminalFontFamily => kIsWeb
+ ? webTerminalFontFamily
+ : (hasAppleFonts ? macTerminalFontFamily : linuxTerminalFontFamily);
-List<String> get terminalFontFallback =>
- hasAppleFonts ? macTerminalFontFallback : linuxTerminalFontFallback;
+List<String> get terminalFontFallback => kIsWeb
+ ? const []
+ : (hasAppleFonts ? macTerminalFontFallback : linuxTerminalFontFallback);
/// The default terminal font size — the same on every platform.
const terminalFontSize = 13.0;
diff --git a/desktop/lib/update/desktop_updater.dart b/desktop/lib/update/desktop_updater.dart
index 0bfe21538..af64a1077 100644
--- a/desktop/lib/update/desktop_updater.dart
+++ b/desktop/lib/update/desktop_updater.dart
@@ -1,11 +1,12 @@
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/runtime_architecture.dart';
+import '../core/runtime_platform.dart';
import '../core/app_version.dart';
/// Published by `scripts/upload-desktop.sh` (`make upload-desktop`) — see
@@ -39,13 +40,7 @@ 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 updates do not support ${Abi.current()}',
- ),
-};
+String _currentArchitecture() => runtimeArchitecture;
String get _metadataUrl => _metadataUrlOverride.isNotEmpty
? _metadataUrlOverride
@@ -135,16 +130,16 @@ String _singleQuote(String value) => "'${value.replaceAll("'", "'\\''")}'";
/// `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`.
+/// `RuntimePlatform.resolvedExecutable`.
String? currentBundlePath({
String? executablePath,
bool? isLinux,
String? appImagePath,
}) {
- if (isLinux ?? Platform.isLinux) {
- return appImagePath ?? Platform.environment['APPIMAGE'];
+ if (isLinux ?? RuntimePlatform.isLinux) {
+ return appImagePath ?? RuntimePlatform.environment['APPIMAGE'];
}
- final resolved = executablePath ?? Platform.resolvedExecutable;
+ final resolved = executablePath ?? RuntimePlatform.resolvedExecutable;
var dir = File(resolved).parent;
for (var i = 0; i < 6; i++) {
if (dir.path.endsWith('.app')) return dir.path;
@@ -156,7 +151,7 @@ String? currentBundlePath({
}
Future<void> _defaultLaunchDetached(String command) async {
- await Process.start(Platform.isLinux ? '/bin/bash' : '/bin/zsh', [
+ await Process.start(RuntimePlatform.isLinux ? '/bin/bash' : '/bin/zsh', [
'-l',
'-c',
command,
@@ -188,7 +183,7 @@ class DesktopUpdater {
/// own self-updater polls on the same order (`cli/src/lib/selfUpdate.ts`).
static const checkInterval = Duration(minutes: 5);
- bool get canCheck => _enabled && _releaseMode;
+ bool get canCheck => !kIsWeb && _enabled && _releaseMode;
DesktopUpdater({
this._enabled = true,
@@ -219,7 +214,7 @@ class DesktopUpdater {
_launchDetached = launchDetached ?? _defaultLaunchDetached,
_metadataUrlForInstance = metadataUrl ?? _metadataUrl,
_releaseMode = releaseMode ?? (kReleaseMode || _forceUpdateChecks),
- _isLinux = isLinux ?? Platform.isLinux,
+ _isLinux = isLinux ?? RuntimePlatform.isLinux,
_architecture = architecture ?? _currentArchitecture();
/// The manifest entries this build may install, most preferred first — [_newestEntry] takes the
diff --git a/desktop/lib/usage/ledger/codex_ledger_scanner.dart b/desktop/lib/usage/ledger/codex_ledger_scanner.dart
index 3222d91d5..20b6a29b9 100644
--- a/desktop/lib/usage/ledger/codex_ledger_scanner.dart
+++ b/desktop/lib/usage/ledger/codex_ledger_scanner.dart
@@ -18,6 +18,8 @@ import 'ledger_scanner.dart';
import 'ledger_types.dart';
import 'jsonl_ledger_scan.dart';
+import '../../core/runtime_platform.dart';
+
class CodexLedgerScanner implements LedgerScanner {
CodexLedgerScanner({String? home, Map<String, String>? environment})
: _environment = environment,
@@ -33,7 +35,7 @@ class CodexLedgerScanner implements LedgerScanner {
/// `~/.codex`, and reads `archived_sessions/` beside `sessions/` so a session
/// Codex has since filed away still counts — it was paid for either way.
List<String> get roots {
- final env = _environment ?? Platform.environment;
+ final env = _environment ?? RuntimePlatform.environment;
final codexHome = env['CODEX_HOME']?.trim();
final base = codexHome != null && codexHome.isNotEmpty
? codexHome
diff --git a/desktop/lib/usage/ledger/jsonl_ledger_scan.dart b/desktop/lib/usage/ledger/jsonl_ledger_scan.dart
index ded00adc5..e485bede1 100644
--- a/desktop/lib/usage/ledger/jsonl_ledger_scan.dart
+++ b/desktop/lib/usage/ledger/jsonl_ledger_scan.dart
@@ -6,6 +6,8 @@ import 'dart:typed_data';
import 'ledger_scanner.dart';
import 'ledger_types.dart';
+import '../../core/runtime_platform.dart';
+
/// Shared file lifecycle; each provider retains its own usage parser.
Future<LedgerScanResult> scanJsonlUsage({
required LedgerProvider provider,
@@ -29,7 +31,7 @@ Future<LedgerScanResult> scanJsonlUsage({
// Unused/older roots normally do not exist. Other listing failures must
// not look like a provider that simply has no logs on this machine.
if (error.osError?.errorCode != 2 &&
- !(Platform.isWindows && error.osError?.errorCode == 3)) {
+ !(RuntimePlatform.isWindows && error.osError?.errorCode == 3)) {
failures.add(error.osError?.message ?? error.message);
}
}
diff --git a/desktop/lib/usage/ledger/ledger_scanner.dart b/desktop/lib/usage/ledger/ledger_scanner.dart
index 7c03d1a51..07642e8a6 100644
--- a/desktop/lib/usage/ledger/ledger_scanner.dart
+++ b/desktop/lib/usage/ledger/ledger_scanner.dart
@@ -13,6 +13,8 @@ import 'dart:io';
import 'ledger_types.dart';
+import '../../core/runtime_platform.dart';
+
/// One file or database a scan read, and what came out of it.
///
/// [mtimeMs] and [size] together fingerprint the append-mostly JSONL logs.
@@ -111,10 +113,10 @@ abstract class LedgerScanner {
/// nowhere to look reports [LedgerStatus.unavailable] like any other machine
/// that has nothing to read.
String? homeDirectory([Map<String, String>? environment]) {
- final env = environment ?? Platform.environment;
+ final env = environment ?? RuntimePlatform.environment;
final home = env['HOME'];
if (home != null && home.isNotEmpty) return home;
- if (Platform.isWindows) {
+ if (RuntimePlatform.isWindows) {
final profile = env['USERPROFILE'];
if (profile != null && profile.isNotEmpty) return profile;
}
diff --git a/desktop/lib/usage/ledger/opencode_ledger_scanner.dart b/desktop/lib/usage/ledger/opencode_ledger_scanner.dart
index 92e17d6a3..c102e99d6 100644
--- a/desktop/lib/usage/ledger/opencode_ledger_scanner.dart
+++ b/desktop/lib/usage/ledger/opencode_ledger_scanner.dart
@@ -1,278 +1,2 @@
-/// What OpenCode has spent on this computer, read out of its own database.
-///
-/// The odd one of the three. OpenCode keeps no transcript to walk: it writes a
-/// SQLite database at `$XDG_DATA_HOME/opencode/opencode.db` and maintains
-/// per-session token and cost totals inside it. So there is no parsing here at
-/// all — one query, one row per session — and no pricing table either, because
-/// **OpenCode records the cost itself** and a figure the provider computed beats
-/// one we inferred from a model name.
-///
-/// ⚠️ **A zero cost from OpenCode is a measurement, not a silence.** Every
-/// session run against a Grid records `cost = 0.0`, because Grid inference is
-/// free (grid ADR 0039 D-g). That must not read the same as Claude's unpriced
-/// models, which is why `LedgerEntry.costUsd` is nullable and this scanner is
-/// the only one that ever fills it in.
-library;
-
-import 'dart:convert';
-import 'dart:io';
-import 'dart:isolate';
-
-import 'package:sqlite3/sqlite3.dart';
-
-import 'ledger_scanner.dart';
-import 'ledger_types.dart';
-
-class _UnsupportedUsageFormat implements Exception {
- const _UnsupportedUsageFormat();
-}
-
-class OpenCodeLedgerScanner implements LedgerScanner {
- OpenCodeLedgerScanner({
- String? dataDirectory,
- Map<String, String>? environment,
- }) : _dataDirectory = dataDirectory ?? _resolveDataDirectory(environment);
-
- final String? _dataDirectory;
-
- @override
- LedgerProvider get provider => LedgerProvider.opencode;
-
- /// Where OpenCode keeps its data — XDG first, as OpenCode itself resolves it.
- static String? _resolveDataDirectory([Map<String, String>? environment]) {
- final env = environment ?? Platform.environment;
- final xdg = env['XDG_DATA_HOME']?.trim();
- if (xdg != null && xdg.isNotEmpty) return '$xdg/opencode';
- final home = homeDirectory(env);
- return home == null ? null : '$home/.local/share/opencode';
- }
-
- @override
- Future<LedgerScanResult> scan(Map<String, ScannedSource> previous) =>
- Isolate.run(() => _scanDirectory(_dataDirectory));
-
- static Future<LedgerScanResult> _scanDirectory(String? directory) async {
- if (directory == null) {
- return const LedgerScanResult.unavailable(
- 'No home directory to read the OpenCode database from',
- );
- }
- final List<File> databases;
- try {
- databases = await _listDatabases(directory);
- } on FileSystemException catch (error) {
- return LedgerScanResult(
- status: LedgerStatus.failed,
- message:
- 'Could not read OpenCode usage: ${error.osError?.message ?? error.message}',
- );
- }
- if (databases.isEmpty) {
- return const LedgerScanResult.unavailable(
- 'No OpenCode database on this computer',
- );
- }
-
- final sources = <ScannedSource>[];
- final failures = <String>[];
- for (final file in databases) {
- try {
- final stat = await file.stat();
- if (stat.type != FileSystemEntityType.file) {
- failures.add('A database is no longer available.');
- continue;
- }
- // The main database can keep its size and mtime while commits change
- // only its WAL. WAL files can also be reused. Query SQLite's committed
- // snapshot on every requested scan instead of trusting file metadata.
- // This aggregate query runs off the UI isolate; the store still avoids
- // rescanning on every visit through its five-minute snapshot lifetime.
- final entries = _read(file.path);
- sources.add(
- ScannedSource(
- path: file.path,
- mtimeMs: stat.modified.millisecondsSinceEpoch,
- size: stat.size,
- entries: entries,
- ),
- );
- } on SqliteException catch (error) {
- failures.add(error.message);
- } on FileSystemException catch (error) {
- failures.add(error.osError?.message ?? error.message);
- } on _UnsupportedUsageFormat {
- failures.add('This OpenCode usage format is not supported yet.');
- }
- }
- return LedgerScanResult(
- sources: sources,
- status: failures.isEmpty
- ? LedgerStatus.ok
- : sources.isEmpty
- ? LedgerStatus.failed
- : LedgerStatus.partial,
- message: failures.isEmpty
- ? null
- : sources.isEmpty
- ? 'Could not read OpenCode usage: ${failures.first}'
- : 'Could not read ${failures.length} of ${databases.length} OpenCode databases. '
- 'Figures are incomplete. ${failures.first}',
- );
- }
-
- /// `opencode.db` and its siblings, canonical one first.
- ///
- /// The canonical database is the live one and must claim a duplicated session
- /// ahead of a stale copy beside it; remaining ties go in path order so
- /// ownership is the same on every rescan.
- static Future<List<File>> _listDatabases(String directory) async {
- final dir = Directory(directory);
- final pattern = RegExp(r'^opencode(?:-[A-Za-z0-9_.-]+)?\.db$');
- final files = <File>[];
- try {
- await for (final entity in dir.list(followLinks: false)) {
- if (entity is! File) continue;
- if (pattern.hasMatch(entity.uri.pathSegments.last)) files.add(entity);
- }
- } on FileSystemException catch (error) {
- if (error.osError?.errorCode == 2) return const [];
- rethrow;
- }
- files.sort((a, b) {
- final aRank = a.uri.pathSegments.last == 'opencode.db' ? 0 : 1;
- final bRank = b.uri.pathSegments.last == 'opencode.db' ? 0 : 1;
- if (aRank != bRank) return aRank - bRank;
- return a.path.compareTo(b.path);
- });
- return files;
- }
-
- static List<LedgerEntry> _read(String path) {
- // Read-only, so a scan can never write to a database the CLI owns — and
- // opening a live WAL database this way is fine, which is the case that
- // matters since OpenCode may be running while this scan happens.
- final db = sqlite3.open(path, mode: OpenMode.readOnly);
- try {
- if (!_hasTable(db, 'session')) throw const _UnsupportedUsageFormat();
- final columns = _columns(db, 'session');
- // Newer OpenCode keeps per-session totals. One aggregate row per session
- // is both cheaper and more accurate than re-adding every message blob.
- const required = [
- 'id',
- 'directory',
- 'time_created',
- 'cost',
- 'tokens_input',
- 'tokens_output',
- 'tokens_reasoning',
- 'tokens_cache_read',
- ];
- if (!required.every(columns.contains)) {
- throw const _UnsupportedUsageFormat();
- }
- final hasCacheWrite = columns.contains('tokens_cache_write');
- final hasModel = columns.contains('model');
-
- final rows = db.select(
- 'SELECT id, directory, time_created, cost, '
- 'tokens_input, tokens_output, tokens_reasoning, tokens_cache_read'
- '${hasCacheWrite ? ', tokens_cache_write' : ''}'
- '${hasModel ? ', model' : ''} '
- 'FROM session '
- 'WHERE tokens_input > 0 OR tokens_output > 0 OR tokens_reasoning > 0 OR tokens_cache_read > 0 '
- '${hasCacheWrite ? 'OR tokens_cache_write > 0 ' : ''}'
- 'ORDER BY time_created, id',
- );
-
- return [
- for (final row in rows)
- ?_entry(row, hasCacheWrite: hasCacheWrite, hasModel: hasModel),
- ];
- } finally {
- db.dispose();
- }
- }
-
- static LedgerEntry? _entry(
- Row row, {
- required bool hasCacheWrite,
- required bool hasModel,
- }) {
- final id = row['id'];
- if (id is! String) return null;
- final created = row['time_created'];
- if (created is! int) return null;
-
- return LedgerEntry(
- provider: LedgerProvider.opencode,
- sessionId: id,
- // Epoch MILLISECONDS, unlike the seconds most SQLite schemas store — read
- // off a live database rather than assumed.
- timestamp: DateTime.fromMillisecondsSinceEpoch(created),
- totals: UsageTotals(
- // `tokens_input` is a peer of `tokens_cache_read` here, as it is for
- // Claude, so no subtraction — see `UsageTotals.freshInput`.
- freshInput: _int(row['tokens_input']),
- // Reasoning folded into output to match the shared bucket's meaning; it
- // is billed at the output rate, and reported separately as a subset.
- output: _int(row['tokens_output']) + _int(row['tokens_reasoning']),
- reasoning: _int(row['tokens_reasoning']),
- cacheRead: _int(row['tokens_cache_read']),
- // OpenCode reports one cache-write figure and no TTL split, so it lands
- // on the 5m bucket rather than being guessed at as long-lived.
- cacheWrite5m: hasCacheWrite ? _int(row['tokens_cache_write']) : 0,
- ),
- model: hasModel ? _modelName(row['model']) : null,
- directory: row['directory'] as String?,
- costUsd: (row['cost'] as num?)?.toDouble(),
- // The session id is already unique per database, and the canonical-first
- // ordering above means a stale sibling copy of the same session is dropped
- // rather than counted twice.
- dedupeKey: 'opencode:$id',
- );
- }
-
- /// The model id out of OpenCode's `model` column.
- ///
- /// ⚠️ **That column holds JSON, not a name** — `{"id":"...","providerID":"..."}`
- /// — which is a real difference from Orca, whose query treats it as a plain
- /// string. Read off a live database. The plain-string form is still accepted
- /// because older schemas wrote one.
- static String? _modelName(Object? value) {
- if (value is! String || value.isEmpty) return null;
- if (!value.startsWith('{')) return value;
- try {
- final decoded = jsonDecode(value);
- if (decoded is Map<String, Object?>) {
- final id = decoded['id'];
- if (id is String && id.isNotEmpty) {
- final provider = decoded['providerID'];
- // Qualified, because the same model id means different things (and
- // different prices) behind two providers — `autonomous-ai` is a Grid,
- // and free.
- return provider is String && provider.isNotEmpty
- ? '$provider/$id'
- : id;
- }
- }
- } on FormatException {
- // A column that is neither JSON nor a bare name tells us nothing; an
- // unnamed model is already an ordinary state here, since OpenCode carries
- // its own cost and never needs the name to price anything.
- }
- return null;
- }
-
- static bool _hasTable(Database db, String name) => db.select(
- "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
- [name],
- ).isNotEmpty;
-
- static Set<String> _columns(Database db, String table) => {
- for (final row in db.select('PRAGMA table_info($table)'))
- if (row['name'] case final String name) name,
- };
-
- static int _int(Object? value) =>
- value is num && value.isFinite && value > 0 ? value.toInt() : 0;
-}
+export 'opencode_ledger_scanner_native.dart'
+ if (dart.library.js_interop) 'opencode_ledger_scanner_web.dart';
diff --git a/desktop/lib/usage/ledger/opencode_ledger_scanner_native.dart b/desktop/lib/usage/ledger/opencode_ledger_scanner_native.dart
new file mode 100644
index 000000000..92e17d6a3
--- /dev/null
+++ b/desktop/lib/usage/ledger/opencode_ledger_scanner_native.dart
@@ -0,0 +1,278 @@
+/// What OpenCode has spent on this computer, read out of its own database.
+///
+/// The odd one of the three. OpenCode keeps no transcript to walk: it writes a
+/// SQLite database at `$XDG_DATA_HOME/opencode/opencode.db` and maintains
+/// per-session token and cost totals inside it. So there is no parsing here at
+/// all — one query, one row per session — and no pricing table either, because
+/// **OpenCode records the cost itself** and a figure the provider computed beats
+/// one we inferred from a model name.
+///
+/// ⚠️ **A zero cost from OpenCode is a measurement, not a silence.** Every
+/// session run against a Grid records `cost = 0.0`, because Grid inference is
+/// free (grid ADR 0039 D-g). That must not read the same as Claude's unpriced
+/// models, which is why `LedgerEntry.costUsd` is nullable and this scanner is
+/// the only one that ever fills it in.
+library;
+
+import 'dart:convert';
+import 'dart:io';
+import 'dart:isolate';
+
+import 'package:sqlite3/sqlite3.dart';
+
+import 'ledger_scanner.dart';
+import 'ledger_types.dart';
+
+class _UnsupportedUsageFormat implements Exception {
+ const _UnsupportedUsageFormat();
+}
+
+class OpenCodeLedgerScanner implements LedgerScanner {
+ OpenCodeLedgerScanner({
+ String? dataDirectory,
+ Map<String, String>? environment,
+ }) : _dataDirectory = dataDirectory ?? _resolveDataDirectory(environment);
+
+ final String? _dataDirectory;
+
+ @override
+ LedgerProvider get provider => LedgerProvider.opencode;
+
+ /// Where OpenCode keeps its data — XDG first, as OpenCode itself resolves it.
+ static String? _resolveDataDirectory([Map<String, String>? environment]) {
+ final env = environment ?? Platform.environment;
+ final xdg = env['XDG_DATA_HOME']?.trim();
+ if (xdg != null && xdg.isNotEmpty) return '$xdg/opencode';
+ final home = homeDirectory(env);
+ return home == null ? null : '$home/.local/share/opencode';
+ }
+
+ @override
+ Future<LedgerScanResult> scan(Map<String, ScannedSource> previous) =>
+ Isolate.run(() => _scanDirectory(_dataDirectory));
+
+ static Future<LedgerScanResult> _scanDirectory(String? directory) async {
+ if (directory == null) {
+ return const LedgerScanResult.unavailable(
+ 'No home directory to read the OpenCode database from',
+ );
+ }
+ final List<File> databases;
+ try {
+ databases = await _listDatabases(directory);
+ } on FileSystemException catch (error) {
+ return LedgerScanResult(
+ status: LedgerStatus.failed,
+ message:
+ 'Could not read OpenCode usage: ${error.osError?.message ?? error.message}',
+ );
+ }
+ if (databases.isEmpty) {
+ return const LedgerScanResult.unavailable(
+ 'No OpenCode database on this computer',
+ );
+ }
+
+ final sources = <ScannedSource>[];
+ final failures = <String>[];
+ for (final file in databases) {
+ try {
+ final stat = await file.stat();
+ if (stat.type != FileSystemEntityType.file) {
+ failures.add('A database is no longer available.');
+ continue;
+ }
+ // The main database can keep its size and mtime while commits change
+ // only its WAL. WAL files can also be reused. Query SQLite's committed
+ // snapshot on every requested scan instead of trusting file metadata.
+ // This aggregate query runs off the UI isolate; the store still avoids
+ // rescanning on every visit through its five-minute snapshot lifetime.
+ final entries = _read(file.path);
+ sources.add(
+ ScannedSource(
+ path: file.path,
+ mtimeMs: stat.modified.millisecondsSinceEpoch,
+ size: stat.size,
+ entries: entries,
+ ),
+ );
+ } on SqliteException catch (error) {
+ failures.add(error.message);
+ } on FileSystemException catch (error) {
+ failures.add(error.osError?.message ?? error.message);
+ } on _UnsupportedUsageFormat {
+ failures.add('This OpenCode usage format is not supported yet.');
+ }
+ }
+ return LedgerScanResult(
+ sources: sources,
+ status: failures.isEmpty
+ ? LedgerStatus.ok
+ : sources.isEmpty
+ ? LedgerStatus.failed
+ : LedgerStatus.partial,
+ message: failures.isEmpty
+ ? null
+ : sources.isEmpty
+ ? 'Could not read OpenCode usage: ${failures.first}'
+ : 'Could not read ${failures.length} of ${databases.length} OpenCode databases. '
+ 'Figures are incomplete. ${failures.first}',
+ );
+ }
+
+ /// `opencode.db` and its siblings, canonical one first.
+ ///
+ /// The canonical database is the live one and must claim a duplicated session
+ /// ahead of a stale copy beside it; remaining ties go in path order so
+ /// ownership is the same on every rescan.
+ static Future<List<File>> _listDatabases(String directory) async {
+ final dir = Directory(directory);
+ final pattern = RegExp(r'^opencode(?:-[A-Za-z0-9_.-]+)?\.db$');
+ final files = <File>[];
+ try {
+ await for (final entity in dir.list(followLinks: false)) {
+ if (entity is! File) continue;
+ if (pattern.hasMatch(entity.uri.pathSegments.last)) files.add(entity);
+ }
+ } on FileSystemException catch (error) {
+ if (error.osError?.errorCode == 2) return const [];
+ rethrow;
+ }
+ files.sort((a, b) {
+ final aRank = a.uri.pathSegments.last == 'opencode.db' ? 0 : 1;
+ final bRank = b.uri.pathSegments.last == 'opencode.db' ? 0 : 1;
+ if (aRank != bRank) return aRank - bRank;
+ return a.path.compareTo(b.path);
+ });
+ return files;
+ }
+
+ static List<LedgerEntry> _read(String path) {
+ // Read-only, so a scan can never write to a database the CLI owns — and
+ // opening a live WAL database this way is fine, which is the case that
+ // matters since OpenCode may be running while this scan happens.
+ final db = sqlite3.open(path, mode: OpenMode.readOnly);
+ try {
+ if (!_hasTable(db, 'session')) throw const _UnsupportedUsageFormat();
+ final columns = _columns(db, 'session');
+ // Newer OpenCode keeps per-session totals. One aggregate row per session
+ // is both cheaper and more accurate than re-adding every message blob.
+ const required = [
+ 'id',
+ 'directory',
+ 'time_created',
+ 'cost',
+ 'tokens_input',
+ 'tokens_output',
+ 'tokens_reasoning',
+ 'tokens_cache_read',
+ ];
+ if (!required.every(columns.contains)) {
+ throw const _UnsupportedUsageFormat();
+ }
+ final hasCacheWrite = columns.contains('tokens_cache_write');
+ final hasModel = columns.contains('model');
+
+ final rows = db.select(
+ 'SELECT id, directory, time_created, cost, '
+ 'tokens_input, tokens_output, tokens_reasoning, tokens_cache_read'
+ '${hasCacheWrite ? ', tokens_cache_write' : ''}'
+ '${hasModel ? ', model' : ''} '
+ 'FROM session '
+ 'WHERE tokens_input > 0 OR tokens_output > 0 OR tokens_reasoning > 0 OR tokens_cache_read > 0 '
+ '${hasCacheWrite ? 'OR tokens_cache_write > 0 ' : ''}'
+ 'ORDER BY time_created, id',
+ );
+
+ return [
+ for (final row in rows)
+ ?_entry(row, hasCacheWrite: hasCacheWrite, hasModel: hasModel),
+ ];
+ } finally {
+ db.dispose();
+ }
+ }
+
+ static LedgerEntry? _entry(
+ Row row, {
+ required bool hasCacheWrite,
+ required bool hasModel,
+ }) {
+ final id = row['id'];
+ if (id is! String) return null;
+ final created = row['time_created'];
+ if (created is! int) return null;
+
+ return LedgerEntry(
+ provider: LedgerProvider.opencode,
+ sessionId: id,
+ // Epoch MILLISECONDS, unlike the seconds most SQLite schemas store — read
+ // off a live database rather than assumed.
+ timestamp: DateTime.fromMillisecondsSinceEpoch(created),
+ totals: UsageTotals(
+ // `tokens_input` is a peer of `tokens_cache_read` here, as it is for
+ // Claude, so no subtraction — see `UsageTotals.freshInput`.
+ freshInput: _int(row['tokens_input']),
+ // Reasoning folded into output to match the shared bucket's meaning; it
+ // is billed at the output rate, and reported separately as a subset.
+ output: _int(row['tokens_output']) + _int(row['tokens_reasoning']),
+ reasoning: _int(row['tokens_reasoning']),
+ cacheRead: _int(row['tokens_cache_read']),
+ // OpenCode reports one cache-write figure and no TTL split, so it lands
+ // on the 5m bucket rather than being guessed at as long-lived.
+ cacheWrite5m: hasCacheWrite ? _int(row['tokens_cache_write']) : 0,
+ ),
+ model: hasModel ? _modelName(row['model']) : null,
+ directory: row['directory'] as String?,
+ costUsd: (row['cost'] as num?)?.toDouble(),
+ // The session id is already unique per database, and the canonical-first
+ // ordering above means a stale sibling copy of the same session is dropped
+ // rather than counted twice.
+ dedupeKey: 'opencode:$id',
+ );
+ }
+
+ /// The model id out of OpenCode's `model` column.
+ ///
+ /// ⚠️ **That column holds JSON, not a name** — `{"id":"...","providerID":"..."}`
+ /// — which is a real difference from Orca, whose query treats it as a plain
+ /// string. Read off a live database. The plain-string form is still accepted
+ /// because older schemas wrote one.
+ static String? _modelName(Object? value) {
+ if (value is! String || value.isEmpty) return null;
+ if (!value.startsWith('{')) return value;
+ try {
+ final decoded = jsonDecode(value);
+ if (decoded is Map<String, Object?>) {
+ final id = decoded['id'];
+ if (id is String && id.isNotEmpty) {
+ final provider = decoded['providerID'];
+ // Qualified, because the same model id means different things (and
+ // different prices) behind two providers — `autonomous-ai` is a Grid,
+ // and free.
+ return provider is String && provider.isNotEmpty
+ ? '$provider/$id'
+ : id;
+ }
+ }
+ } on FormatException {
+ // A column that is neither JSON nor a bare name tells us nothing; an
+ // unnamed model is already an ordinary state here, since OpenCode carries
+ // its own cost and never needs the name to price anything.
+ }
+ return null;
+ }
+
+ static bool _hasTable(Database db, String name) => db.select(
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
+ [name],
+ ).isNotEmpty;
+
+ static Set<String> _columns(Database db, String table) => {
+ for (final row in db.select('PRAGMA table_info($table)'))
+ if (row['name'] case final String name) name,
+ };
+
+ static int _int(Object? value) =>
+ value is num && value.isFinite && value > 0 ? value.toInt() : 0;
+}
diff --git a/desktop/lib/usage/ledger/opencode_ledger_scanner_web.dart b/desktop/lib/usage/ledger/opencode_ledger_scanner_web.dart
new file mode 100644
index 000000000..279bd0c6e
--- /dev/null
+++ b/desktop/lib/usage/ledger/opencode_ledger_scanner_web.dart
@@ -0,0 +1,15 @@
+import 'ledger_scanner.dart';
+import 'ledger_types.dart';
+
+/// Local transcript/database scans require the desktop app. Remote account
+/// usage continues through the shared daemon RPC client.
+class OpenCodeLedgerScanner implements LedgerScanner {
+ OpenCodeLedgerScanner({String? dataDirectory, Map<String, String>? environment});
+
+ @override
+ LedgerProvider get provider => LedgerProvider.opencode;
+
+ @override
+ Future<LedgerScanResult> scan(Map<String, ScannedSource> previous) async =>
+ const LedgerScanResult.unavailable('Local usage is available in the desktop app.');
+}
diff --git a/desktop/lib/usage/usage_credentials.dart b/desktop/lib/usage/usage_credentials.dart
index b76945f5d..4c47ff306 100644
--- a/desktop/lib/usage/usage_credentials.dart
+++ b/desktop/lib/usage/usage_credentials.dart
@@ -15,6 +15,8 @@ import 'dart:io';
import 'package:cryptography/dart.dart';
+import '../core/runtime_platform.dart';
+
/// A token, and when it stops working.
class UsageToken {
const UsageToken({required this.accessToken, this.expiresAt});
@@ -48,8 +50,8 @@ class UsageCredentials {
/// 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'];
- Map<String, String> get _env => environment ?? Platform.environment;
+ String? get _home => home ?? RuntimePlatform.environment['HOME'];
+ Map<String, String> get _env => environment ?? RuntimePlatform.environment;
/// The Keychain SERVICE Claude Code writes its OAuth token under — its own rule, read off
/// Claude Code 2.1.272: `Claude Code-credentials`, plus `-<sha256(configDir)[0..8]>` when
@@ -165,7 +167,7 @@ class UsageCredentials {
String? _readFile(String relative) {
final home = _home;
if (home == null) return null;
- final file = File('$home${Platform.pathSeparator}$relative');
+ final file = File('$home${RuntimePlatform.pathSeparator}$relative');
if (!file.existsSync()) return null;
try {
return file.readAsStringSync();
@@ -182,7 +184,7 @@ class UsageCredentials {
/// 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 && runProcess == null) return null;
+ if (!RuntimePlatform.isMacOS && runProcess == null) return null;
final run = runProcess ?? Process.run;
final env = _env;
try {
diff --git a/desktop/lib/viewer/browser_login.dart b/desktop/lib/viewer/browser_login.dart
new file mode 100644
index 000000000..89b476c2e
--- /dev/null
+++ b/desktop/lib/viewer/browser_login.dart
@@ -0,0 +1,172 @@
+import 'dart:async';
+import 'dart:convert';
+
+import '../auth/cli_login.dart' show CliAuthStatus;
+import '../auth/sign_in_client.dart';
+import 'direct_auth.dart';
+import 'direct_auth_api.dart';
+
+/// Browser-only operations behind a seam so OAuth can be tested without a
+/// browser, a real account, or opening an authorization page.
+abstract interface class LoginBrowser {
+ Uri get uri;
+ String? get transaction;
+ set transaction(String? value);
+ void replaceLocation(String path);
+}
+
+/// Same-tab OAuth using the backend's existing PKCE transaction endpoints.
+/// The callback must match the attempt started in this tab. Neither tokens nor
+/// transaction identifiers are placed in a public workspace URL.
+class BrowserLogin implements SignInClient {
+ BrowserLogin({
+ required this.auth,
+ required this.browser,
+ DateTime Function()? clock,
+ }) : _clock = clock ?? DateTime.now;
+
+ final DirectAuth auth;
+ final LoginBrowser browser;
+ final DateTime Function() _clock;
+ int _revision = 0;
+ Completer<void>? _departing;
+ Future<CliAuthStatus>? _checking;
+ static const _lifetime = Duration(minutes: 10);
+
+ static bool _isLoopback(Uri location) =>
+ const {'http', 'https'}.contains(location.scheme) &&
+ const {'127.0.0.1', 'localhost', '::1'}.contains(location.host);
+
+ // SSO registers /callback for native loopback clients; hosted web apps use
+ // /auth/callback on their configured origin.
+ static String _callbackPath(Uri location) =>
+ _isLoopback(location) ? '/callback' : '/auth/callback';
+
+ @override
+ Future<CliAuthStatus> checkStatus() =>
+ _checking ??= _checkStatus().whenComplete(() {
+ _checking = null;
+ });
+
+ Future<CliAuthStatus> _checkStatus() async {
+ final uri = browser.uri;
+ final revision = _revision;
+ if (uri.path == _callbackPath(uri)) {
+ final raw = browser.transaction;
+ browser.transaction = null;
+ // Remove the one-use code before any API call or application telemetry.
+ browser.replaceLocation('/');
+ try {
+ final saved = raw == null ? null : jsonDecode(raw);
+ final now = _clock().millisecondsSinceEpoch;
+ if (saved is! Map ||
+ saved['tx'] is! String ||
+ saved['state'] is! String ||
+ saved['createdAt'] is! int ||
+ now < (saved['createdAt'] as int) ||
+ now - (saved['createdAt'] as int) > _lifetime.inMilliseconds ||
+ uri.queryParameters['state'] != saved['state']) {
+ throw const DirectAuthException(
+ 'This sign-in expired or started in another tab. Sign in again.',
+ );
+ }
+ if (uri.queryParameters.containsKey('error')) {
+ throw const DirectAuthException(
+ 'Sign-in was not completed. Try again.',
+ );
+ }
+ final code = uri.queryParameters['code'];
+ if (code == null || code.isEmpty) {
+ throw const DirectAuthException(
+ 'Sign-in returned no authorization code.',
+ );
+ }
+ final tokens = await auth.api.exchange(
+ code: code,
+ state: saved['state'] as String,
+ tx: saved['tx'] as String,
+ );
+ _requireCurrent(revision);
+ await auth.signIn(tokens, stillCurrent: () => revision == _revision);
+ _requireCurrent(revision);
+ } on FormatException {
+ throw const DirectAuthException('This sign-in expired. Sign in again.');
+ }
+ }
+ final loggedIn = await auth.hasSession();
+ _requireCurrent(revision);
+ return CliAuthStatus(loggedIn: loggedIn);
+ }
+
+ @override
+ Future<void> login({
+ required void Function(String url) onAuthorizeUrl,
+ }) async {
+ cancel();
+ final revision = _revision;
+ final location = browser.uri;
+ final origin = location.origin;
+ final callbackPath = _callbackPath(location);
+ // Local previews need their own callback, just like the native app's
+ // loopback listener. The hosted web endpoint only accepts configured
+ // origins and otherwise returns the production site's callback.
+ final start = await (_isLoopback(location)
+ ? auth.api.authorizeNative('$origin$callbackPath')
+ : auth.api.authorizeWeb(origin));
+ _requireCurrent(revision);
+ final authorize = Uri.tryParse(start.authorizeUrl);
+ final redirect = Uri.tryParse(
+ authorize?.queryParameters['redirect_uri'] ?? '',
+ );
+ final state = authorize?.queryParameters['state'];
+ if (authorize == null ||
+ !const {'https', 'http'}.contains(authorize.scheme) ||
+ state == null ||
+ state.isEmpty ||
+ redirect == null ||
+ !redirect.hasAuthority ||
+ redirect.origin != origin ||
+ redirect.path != callbackPath) {
+ throw const DirectAuthException(
+ 'Sign-in is not enabled for this web address.',
+ );
+ }
+ browser.transaction = jsonEncode({
+ 'tx': start.tx,
+ 'state': state,
+ 'createdAt': _clock().millisecondsSinceEpoch,
+ });
+ final departing = _departing = Completer<void>();
+ onAuthorizeUrl(start.authorizeUrl);
+ try {
+ // A successful redirect replaces this runtime. Until then the shared
+ // login screen can retry opening the same URL or cancel the attempt.
+ await departing.future.timeout(_lifetime);
+ _requireCurrent(revision);
+ } on TimeoutException {
+ cancel();
+ throw const DirectAuthException('Sign-in timed out. Try again.');
+ }
+ }
+
+ void _requireCurrent(int revision) {
+ if (revision != _revision) {
+ throw const DirectAuthException('Sign-in was cancelled.');
+ }
+ }
+
+ @override
+ void cancel() {
+ ++_revision;
+ browser.transaction = null;
+ final departing = _departing;
+ _departing = null;
+ if (departing != null && !departing.isCompleted) departing.complete();
+ }
+
+ @override
+ Future<void> logout() {
+ cancel();
+ return auth.signOut();
+ }
+}
diff --git a/desktop/lib/viewer/direct_auth.dart b/desktop/lib/viewer/direct_auth.dart
index 88a96c218..66b27a0bd 100644
--- a/desktop/lib/viewer/direct_auth.dart
+++ b/desktop/lib/viewer/direct_auth.dart
@@ -16,6 +16,9 @@ class DirectAuth implements AccessTokenSource {
static const _refreshSkew = Duration(seconds: 60);
+ /// Browser adapters release their cross-tab session listener here.
+ void dispose() {}
+
Future<bool> hasSession() async {
final revision = _revision;
await _writes;
diff --git a/desktop/lib/viewer/direct_auth_api.dart b/desktop/lib/viewer/direct_auth_api.dart
index 812bc3e4c..aec3046d0 100644
--- a/desktop/lib/viewer/direct_auth_api.dart
+++ b/desktop/lib/viewer/direct_auth_api.dart
@@ -78,13 +78,39 @@ class DirectAuthApi {
final data = unwrapApiResponse(
await _dio.post(
'/api/auth/authorize-native',
- data: {'redirectUri': redirectUri, 'autonomousEnv': config.autonomousEnv},
+ 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.');
+ throw const DirectAuthException(
+ 'The server did not return a sign-in page.',
+ );
+ }
+ return (authorizeUrl: url, tx: tx);
+ }
+
+ Future<({String authorizeUrl, String tx})> authorizeWeb(String origin) async {
+ final data = unwrapApiResponse(
+ await _dio.post(
+ '/api/auth/authorize',
+ data: {
+ 'origin': origin,
+ 'next': '/',
+ '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);
}
diff --git a/desktop/lib/viewer/direct_login.dart b/desktop/lib/viewer/direct_login.dart
index 3ccb8d207..a424723da 100644
--- a/desktop/lib/viewer/direct_login.dart
+++ b/desktop/lib/viewer/direct_login.dart
@@ -1,143 +1,2 @@
-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;
- int _loginRevision = 0;
-
- 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 {
- cancel();
- final revision = _loginRevision;
- final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
- _LoopbackCallback? callback;
- try {
- _requireCurrent(revision);
- callback = _pending = _LoopbackCallback(server);
- final start = await auth.api.authorizeNative(
- 'http://127.0.0.1:${server.port}/callback',
- );
- _requireCurrent(revision);
- onAuthorizeUrl(start.authorizeUrl);
- _requireCurrent(revision);
- final redirect = await callback.result.timeout(
- _callbackTimeout,
- onTimeout: () => throw const DirectAuthException('Sign-in timed out.'),
- );
- _requireCurrent(revision);
- if (redirect == null) throw callback.error!;
- final tokens = await auth.api.exchange(
- code: redirect.code,
- state: redirect.state,
- tx: start.tx,
- );
- _requireCurrent(revision);
- await auth.signIn(tokens, stillCurrent: () => revision == _loginRevision);
- _requireCurrent(revision);
- } finally {
- if (identical(_pending, callback)) _pending = null;
- await server.close(force: true);
- }
- }
-
- @override
- void cancel() {
- ++_loginRevision;
- final callback = _pending;
- _pending = null;
- callback?.cancel();
- }
-
- void _requireCurrent(int revision) {
- if (revision != _loginRevision) {
- throw const DirectAuthException('Sign-in was cancelled.');
- }
- }
-
- @override
- Future<void> logout() {
- cancel();
- return 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(this._server) {
- _server.listen(_onRequest);
- }
-
- final HttpServer _server;
- // Cancellation can precede the authorization response and its listener.
- // Keep the outcome as data until login awaits it, without an unhandled error.
- final _completer = Completer<({String code, String state})?>();
- DirectAuthException? error;
-
- 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 {
- this.error = DirectAuthException(
- 'Sign-in failed: ${error ?? 'no code returned'}',
- );
- _completer.complete(null);
- }
- }
-
- void cancel() {
- if (!_completer.isCompleted) {
- error = const DirectAuthException('Sign-in was cancelled.');
- _completer.complete(null);
- }
- unawaited(_server.close(force: true));
- }
-}
-
-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>';
+export 'direct_login_native.dart'
+ if (dart.library.js_interop) 'direct_login_web.dart';
diff --git a/desktop/lib/viewer/direct_login_native.dart b/desktop/lib/viewer/direct_login_native.dart
new file mode 100644
index 000000000..3ccb8d207
--- /dev/null
+++ b/desktop/lib/viewer/direct_login_native.dart
@@ -0,0 +1,143 @@
+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;
+ int _loginRevision = 0;
+
+ 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 {
+ cancel();
+ final revision = _loginRevision;
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ _LoopbackCallback? callback;
+ try {
+ _requireCurrent(revision);
+ callback = _pending = _LoopbackCallback(server);
+ final start = await auth.api.authorizeNative(
+ 'http://127.0.0.1:${server.port}/callback',
+ );
+ _requireCurrent(revision);
+ onAuthorizeUrl(start.authorizeUrl);
+ _requireCurrent(revision);
+ final redirect = await callback.result.timeout(
+ _callbackTimeout,
+ onTimeout: () => throw const DirectAuthException('Sign-in timed out.'),
+ );
+ _requireCurrent(revision);
+ if (redirect == null) throw callback.error!;
+ final tokens = await auth.api.exchange(
+ code: redirect.code,
+ state: redirect.state,
+ tx: start.tx,
+ );
+ _requireCurrent(revision);
+ await auth.signIn(tokens, stillCurrent: () => revision == _loginRevision);
+ _requireCurrent(revision);
+ } finally {
+ if (identical(_pending, callback)) _pending = null;
+ await server.close(force: true);
+ }
+ }
+
+ @override
+ void cancel() {
+ ++_loginRevision;
+ final callback = _pending;
+ _pending = null;
+ callback?.cancel();
+ }
+
+ void _requireCurrent(int revision) {
+ if (revision != _loginRevision) {
+ throw const DirectAuthException('Sign-in was cancelled.');
+ }
+ }
+
+ @override
+ Future<void> logout() {
+ cancel();
+ return 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(this._server) {
+ _server.listen(_onRequest);
+ }
+
+ final HttpServer _server;
+ // Cancellation can precede the authorization response and its listener.
+ // Keep the outcome as data until login awaits it, without an unhandled error.
+ final _completer = Completer<({String code, String state})?>();
+ DirectAuthException? error;
+
+ 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 {
+ this.error = DirectAuthException(
+ 'Sign-in failed: ${error ?? 'no code returned'}',
+ );
+ _completer.complete(null);
+ }
+ }
+
+ void cancel() {
+ if (!_completer.isCompleted) {
+ error = const DirectAuthException('Sign-in was cancelled.');
+ _completer.complete(null);
+ }
+ unawaited(_server.close(force: true));
+ }
+}
+
+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/desktop/lib/viewer/direct_login_web.dart b/desktop/lib/viewer/direct_login_web.dart
new file mode 100644
index 000000000..750d30738
--- /dev/null
+++ b/desktop/lib/viewer/direct_login_web.dart
@@ -0,0 +1,27 @@
+import 'package:web/web.dart' as web;
+
+import 'browser_login.dart';
+
+class DirectLogin extends BrowserLogin {
+ DirectLogin({required super.auth}) : super(browser: _WebLoginBrowser());
+}
+
+class _WebLoginBrowser implements LoginBrowser {
+ static const _key = 'harness.web.v1.auth_transaction';
+ @override
+ Uri get uri => Uri.parse(web.window.location.href);
+ @override
+ String? get transaction => web.window.sessionStorage.getItem(_key);
+ @override
+ set transaction(String? value) {
+ if (value == null) {
+ web.window.sessionStorage.removeItem(_key);
+ } else {
+ web.window.sessionStorage.setItem(_key, value);
+ }
+ }
+
+ @override
+ void replaceLocation(String path) =>
+ web.window.history.replaceState(null, '', path);
+}
diff --git a/desktop/lib/viewer/observer_relay_codec.dart b/desktop/lib/viewer/observer_relay_codec.dart
new file mode 100644
index 000000000..5b6619872
--- /dev/null
+++ b/desktop/lib/viewer/observer_relay_codec.dart
@@ -0,0 +1,127 @@
+import 'dart:typed_data';
+
+import '../core/wire_counter.dart';
+import '../e2ee/bytes.dart';
+import '../e2ee/envelope.dart';
+import '../e2ee/keys.dart';
+import '../ws/relay_codec.dart';
+
+/// cli/src/sharing/crypto.ts's recipient session. Each connection belongs to
+/// one grant, verifies the owner's signed ephemeral key, and can only observe.
+/// It never receives a machine group key or becomes a machine peer link.
+class ObserverRelayCodec implements RelayCodec {
+ ObserverRelayCodec._(this._ephemeral, this._owner, this.context);
+
+ static Future<ObserverRelayCodec> create({
+ required String machineId,
+ required String shareId,
+ required String ownerPublicKey,
+ }) async => ObserverRelayCodec._(
+ await Ephemeral.generate(),
+ b64d(ownerPublicKey),
+ 'harness-observer-v1:$machineId:$shareId',
+ );
+
+ final Ephemeral _ephemeral;
+ final Uint8List _owner;
+ final String context;
+ SessionKeys? _keys;
+ int _tx = 0, _rx = -1;
+
+ @override
+ Map<String, dynamic> helloFrame() => {
+ 'type': 'observer_hello',
+ 'payload': {'ephemeral': b64e(_ephemeral.pub)},
+ };
+
+ @override
+ Future<bool> handleWelcome(Map<String, dynamic> payload) async {
+ if (_keys != null) return false;
+ try {
+ final peer = b64d(payload['ephemeral'] as String);
+ final signature = b64d(payload['signature'] as String);
+ if (_owner.length != 32 ||
+ peer.length != 32 ||
+ !await welcomeVerify(
+ _owner,
+ context,
+ _ephemeral.pub,
+ peer,
+ signature,
+ )) {
+ return false;
+ }
+ _keys = sessionKeys(_ephemeral, peer, context, _ephemeral.pub, peer);
+ return true;
+ } on Object {
+ return false;
+ }
+ }
+
+ static const _allowed = {
+ 'terminal_capabilities',
+ 'terminal_open',
+ 'terminal_alive',
+ 'terminal_ack',
+ 'terminal_resync',
+ 'terminal_close',
+ 'observer_viewer',
+ };
+
+ @override
+ Map<String, dynamic>? encodeFrame(Map<String, dynamic> frame) {
+ final keys = _keys;
+ if (keys == null ||
+ !_allowed.contains(frame['type']) ||
+ _tx > maxSafeInteger) {
+ return null;
+ }
+ return {
+ 'type': 'observer_frame',
+ 'payload': wrapPayload(
+ keys.c2s,
+ 'p',
+ _tx++,
+ 'observer_frame',
+ context,
+ frame,
+ ),
+ };
+ }
+
+ @override
+ Map<String, dynamic>? decodeFrame(Map<String, dynamic> frame) {
+ final keys = _keys;
+ final payload = frame['payload'];
+ if (keys == null || frame['type'] != 'observer_frame' || payload is! Map) {
+ return null;
+ }
+ final envelope = payload['__e2e'];
+ if (envelope is! Map<String, dynamic>) return null;
+ final n = envelope['n'], ct = envelope['ct'];
+ if (envelope['v'] != 1 ||
+ envelope['k'] != 'p' ||
+ n is! int ||
+ n <= _rx ||
+ n > maxSafeInteger ||
+ ct is! String ||
+ ct.length > 3 * 1024 * 1024) {
+ return null;
+ }
+ final clear = unwrapPayload(keys.s2c, envelope, 'observer_frame', context);
+ if (clear == null || clear['type'] is! String || clear['payload'] is! Map) {
+ return null;
+ }
+ _rx = n;
+ return clear;
+ }
+
+ @override
+ Uint8List? encodeBinary(Uint8List localFrame) => null;
+ @override
+ Uint8List? decodeBinary(Uint8List wireFrame) => null;
+ @override
+ bool handleRekey(Map<String, dynamic> payload) => false;
+ @override
+ int get terminalP2pVersion => 0;
+}
diff --git a/desktop/lib/viewer/platform_auth.dart b/desktop/lib/viewer/platform_auth.dart
new file mode 100644
index 000000000..8309279e7
--- /dev/null
+++ b/desktop/lib/viewer/platform_auth.dart
@@ -0,0 +1,2 @@
+export 'platform_auth_native.dart'
+ if (dart.library.js_interop) 'platform_auth_web.dart';
diff --git a/desktop/lib/viewer/platform_auth_native.dart b/desktop/lib/viewer/platform_auth_native.dart
new file mode 100644
index 000000000..4de12df0e
--- /dev/null
+++ b/desktop/lib/viewer/platform_auth_native.dart
@@ -0,0 +1,8 @@
+import '../auth/auth_session.dart';
+import 'direct_auth.dart';
+import 'direct_auth_api.dart';
+
+DirectAuth createViewerAuth({
+ required AuthSession session,
+ required DirectAuthApi api,
+}) => DirectAuth(session: session, api: api);
diff --git a/desktop/lib/viewer/platform_auth_web.dart b/desktop/lib/viewer/platform_auth_web.dart
new file mode 100644
index 000000000..8932d4f68
--- /dev/null
+++ b/desktop/lib/viewer/platform_auth_web.dart
@@ -0,0 +1,122 @@
+import 'dart:js_interop';
+
+import 'package:web/web.dart' as web;
+
+import '../auth/auth_session.dart';
+import '../core/browser_lock.dart';
+import 'direct_auth.dart';
+import 'direct_auth_api.dart';
+
+DirectAuth createViewerAuth({
+ required AuthSession session,
+ required DirectAuthApi api,
+}) => BrowserAuth(session: session, api: api);
+
+/// Shares one persisted session across tabs while keeping refresh-token
+/// rotation, login, and logout mutually exclusive. The existing DirectAuth
+/// still owns expiry and provider errors inside that browser-wide lock.
+class BrowserAuth extends DirectAuth {
+ BrowserAuth({
+ required super.session,
+ required super.api,
+ void Function()? reload,
+ }) : _delegate = DirectAuth(session: session, api: api),
+ _reload = reload ?? (() => web.window.location.reload()) {
+ _generation = web.window.localStorage.getItem(_generationKey);
+ _listener = ((web.Event event) {
+ final change = event as web.StorageEvent;
+ if (change.storageArea == web.window.localStorage &&
+ (change.key == null || change.key == _generationKey)) {
+ _checkGeneration();
+ }
+ }).toJS;
+ web.window.addEventListener('storage', _listener);
+ }
+
+ static const _generationKey = 'harness.web.v1.auth_generation';
+ static const _changed = DirectAuthException('Sign-in changed. Try again.');
+ final DirectAuth _delegate;
+ final void Function() _reload;
+ late final JSFunction _listener;
+ String? _generation;
+ int _revision = 0;
+ bool _reloading = false;
+
+ bool _checkGeneration() {
+ if (web.window.localStorage.getItem(_generationKey) == _generation) {
+ return !_reloading;
+ }
+ if (!_reloading) {
+ _reloading = true;
+ ++_revision;
+ // Close this account's live transports and restore the new session via
+ // normal bootstrap, including when another tab explicitly signs out.
+ _reload();
+ }
+ return false;
+ }
+
+ Future<T> _run<T>(
+ Future<T> Function() action, {
+ bool changesSession = false,
+ }) {
+ final revision = _revision;
+ return withBrowserLock('auth', () async {
+ if (!_checkGeneration() || revision != _revision) throw _changed;
+ final before = await session.accessToken();
+ try {
+ final result = await action();
+ if (revision != _revision) throw _changed;
+ return result;
+ } finally {
+ if (changesSession ||
+ (before != null && await session.accessToken() == null)) {
+ _generation = web.window.crypto.randomUUID();
+ web.window.localStorage.setItem(_generationKey, _generation!);
+ }
+ }
+ });
+ }
+
+ @override
+ Future<bool> hasSession() => _run(_delegate.hasSession);
+
+ @override
+ Future<void> signIn(IssuedTokens tokens, {bool Function()? stillCurrent}) {
+ final revision = ++_revision;
+ return _run(
+ () => _delegate.signIn(
+ tokens,
+ stillCurrent: () =>
+ revision == _revision && (stillCurrent?.call() ?? true),
+ ),
+ changesSession: true,
+ );
+ }
+
+ @override
+ Future<void> signOut() {
+ ++_revision;
+ return _run(_delegate.signOut, changesSession: true);
+ }
+
+ @override
+ Future<String> accessToken({bool force = false, String? failedToken}) async {
+ final revision = _revision;
+ // Capture the failed token before waiting, so a second tab can reuse a
+ // refresh that finished while it was queued instead of rotating again.
+ final previous =
+ failedToken ?? (force ? await session.accessToken() : null);
+ if (revision != _revision) throw _changed;
+ return _run(
+ () => _delegate.accessToken(force: force, failedToken: previous),
+ );
+ }
+
+ @override
+ void dispose() {
+ ++_revision;
+ _reloading = true;
+ web.window.removeEventListener('storage', _listener);
+ }
+}
diff --git a/desktop/lib/viewer/sign_in_browser.dart b/desktop/lib/viewer/sign_in_browser.dart
index 8b760ace7..4f8243bf0 100644
--- a/desktop/lib/viewer/sign_in_browser.dart
+++ b/desktop/lib/viewer/sign_in_browser.dart
@@ -1,7 +1,9 @@
-import 'dart:io';
+import 'package:flutter/foundation.dart';
import 'package:url_launcher/url_launcher.dart';
+import '../core/runtime_platform.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
@@ -14,11 +16,12 @@ import 'package:url_launcher/url_launcher.dart';
/// has to answer.
Future<bool> openSignInPage(Uri url) => launchUrl(
url,
- mode: Platform.isIOS || Platform.isAndroid
+ webOnlyWindowName: kIsWeb ? '_self' : null,
+ mode: RuntimePlatform.isIOS || RuntimePlatform.isAndroid
? LaunchMode.inAppBrowserView
: LaunchMode.externalApplication,
);
Future<void> closeSignInPage() async {
- if (Platform.isIOS || Platform.isAndroid) await closeInAppWebView();
+ if (RuntimePlatform.isIOS || RuntimePlatform.isAndroid) await closeInAppWebView();
}
diff --git a/desktop/lib/viewer/viewer_key_store.dart b/desktop/lib/viewer/viewer_key_store.dart
index 8514aa9f7..d36d676a6 100644
--- a/desktop/lib/viewer/viewer_key_store.dart
+++ b/desktop/lib/viewer/viewer_key_store.dart
@@ -66,13 +66,14 @@ class ViewerKeyStore {
/// 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;
- }
+ Future<E2eeIdentity> _loadOrMintIdentity() =>
+ _storage.synchronized('viewer_identity', () 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 {
@@ -96,27 +97,31 @@ class ViewerKeyStore {
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(),
- ),
- ]);
- }
+ Future<void> pin(String machineId, List<int> pub, {String label = ''}) =>
+ _storage.synchronized('viewer_peers', () 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<bool> unlink(String machineId) =>
+ _storage.synchronized('viewer_peers', () 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,
diff --git a/desktop/lib/viewer/viewer_services.dart b/desktop/lib/viewer/viewer_services.dart
index d99814709..10eb84d9e 100644
--- a/desktop/lib/viewer/viewer_services.dart
+++ b/desktop/lib/viewer/viewer_services.dart
@@ -7,6 +7,7 @@ import 'direct_auth_api.dart';
import 'direct_link.dart';
import 'direct_login.dart';
import 'e2ee_relay_codec.dart';
+import 'platform_auth.dart';
import 'viewer_key_store.dart';
/// The second wire a viewer build offers its relay connections — the phone's WebRTC
@@ -37,7 +38,7 @@ class ViewerServices {
TerminalTransportPluginFactory? transportPlugins,
}) {
final store = keys ?? ViewerKeyStore();
- final auth = DirectAuth(
+ final auth = createViewerAuth(
session: session,
api: DirectAuthApi(config: config),
);
diff --git a/desktop/lib/widgets/login_fleet_map.dart b/desktop/lib/widgets/login_fleet_map.dart
index 6da5d8d10..22102b22d 100644
--- a/desktop/lib/widgets/login_fleet_map.dart
+++ b/desktop/lib/widgets/login_fleet_map.dart
@@ -2,6 +2,7 @@ import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
+import 'package:flutter/foundation.dart' show kIsWeb;
import '../shared/theme/app_theme.dart' as grid;
@@ -17,7 +18,8 @@ import '../shared/theme/app_theme.dart' as grid;
/// A fully drawn still shows a sealed packet and a plain packet together,
/// without an entrance delay or a continuous idle repaint loop.
class LoginFleetMap extends StatelessWidget {
- const LoginFleetMap({super.key});
+ const LoginFleetMap({super.key, this.seamless = false});
+ final bool seamless;
static const double aspectRatio = 512 / 190;
// Show both sealed and plain packets without running a ticker while idle.
@@ -30,7 +32,7 @@ class LoginFleetMap extends StatelessWidget {
// from a paint callback.
final palette = _MapPalette(
dot: grid.AppPalette.guide,
- field: grid.AppGlass.surfaceFill,
+ field: seamless ? Colors.transparent : grid.AppGlass.surfaceFill,
arc: grid.AppPalette.accentOnSurface,
pinFill: grid.AppCard.inset,
pinRim: grid.AppPalette.textSecondary,
@@ -55,7 +57,12 @@ class LoginFleetMap extends StatelessWidget {
child: AspectRatio(
aspectRatio: LoginFleetMap.aspectRatio,
child: CustomPaint(
- painter: _MapPainter(entrance: 1, t: _reducedPhase, palette: palette),
+ painter: _MapPainter(
+ entrance: 1,
+ t: _reducedPhase,
+ palette: palette,
+ seamless: seamless,
+ ),
size: Size.infinite,
),
),
@@ -151,7 +158,13 @@ Color _fade(Color color, double k) => color.withValues(alpha: color.a * k);
/// The drawing, in its own 512×190 space; the canvas is scaled to fit so every
/// number here is the one from the mockup rather than a fraction to re-derive.
class _MapPainter extends CustomPainter {
- _MapPainter({required this.entrance, required this.t, required this.palette});
+ _MapPainter({
+ required this.entrance,
+ required this.t,
+ required this.palette,
+ this.seamless = false,
+ });
+ final bool seamless;
/// 0 → 1 over the first sight of the field; 1 forever after.
final double entrance;
@@ -245,6 +258,11 @@ class _MapPainter extends CustomPainter {
final dot = Paint()..color = _fade(palette.dot, 0.55);
for (var y = 5.0; y < _design.height; y += 10) {
for (var x = 5.0; x < _design.width; x += 10) {
+ if (seamless) {
+ final dx = (x / _design.width * 2 - 1).abs();
+ final dy = (y / _design.height * 2 - 1).abs();
+ dot.color = _fade(palette.dot, 0.55 * (1 - dx * dx) * (1 - dy * dy));
+ }
canvas.drawCircle(Offset(x, y), 0.8, dot);
}
}
@@ -324,7 +342,7 @@ class _MapPainter extends CustomPainter {
);
_text(
canvas,
- '● this Mac · 4 linked',
+ kIsWeb ? 'this browser · 4 linked' : '● this Mac · 4 linked',
Offset(_window.left + 7, _window.top + 6),
color: _fade(palette.ink2, landed),
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index d253c998a..e09dd1799 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -986,8 +986,12 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
? 'No matching projects'
: search.isMachineMode
? 'No matching machines'
- : search.adding && search.query.isEmpty
+ : search.adding &&
+ search.query.isEmpty &&
+ search.capacity <= 0
? 'This tab is full (${AppNotifier.maxPanes} panes). Open a new tab to add more.'
+ : search.adding && search.query.isEmpty
+ ? 'No harnesses yet. Start an agent or choose @ machines to connect a machine.'
: search.adding
? 'No matching harnesses'
: 'No matching results',
diff --git a/desktop/lib/widgets/web_download_button.dart b/desktop/lib/widgets/web_download_button.dart
new file mode 100644
index 000000000..a464b878b
--- /dev/null
+++ b/desktop/lib/widgets/web_download_button.dart
@@ -0,0 +1,44 @@
+import 'package:flutter/material.dart';
+import 'package:url_launcher/link.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/theme/workspace_bar_style.dart';
+import 'workspace_bar_control.dart';
+
+/// The browser's consistent handoff to the existing macOS/Linux download page.
+class WebDownloadButton extends StatelessWidget {
+ const WebDownloadButton({super.key});
+
+ static final uri = Uri.parse('https://harness.autonomous.ai/download');
+ static const _text = '[ Download app ]';
+
+ static double widthOf(BuildContext context) =>
+ workspaceBarTextSizeOf(context, _text).width +
+ workspaceBarCellSizeOf(context).width * 2;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Link(
+ uri: uri,
+ target: LinkTarget.blank,
+ builder: (context, followLink) => WorkspaceBarControl(
+ label: 'Download app',
+ onPressed: followLink,
+ builder: (context, emphasized) => SizedBox(
+ width: widthOf(context),
+ height: workspaceBarControlHeight(context),
+ child: Center(
+ child: Text(
+ _text,
+ style: workspaceBarTextStyle(
+ color: grid.AppPalette.textPrimary,
+ emphasized: emphasized,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/web_pane_panel.dart b/desktop/lib/widgets/web_pane_panel.dart
index a452fa5b8..4232effdd 100644
--- a/desktop/lib/widgets/web_pane_panel.dart
+++ b/desktop/lib/widgets/web_pane_panel.dart
@@ -1,10 +1,9 @@
-import 'dart:io' show Platform;
-
import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
+import '../core/runtime_platform.dart';
import '../core/models.dart' show AgentVerdict;
import '../core/test_run.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -71,7 +70,7 @@ class WebPanePanel extends StatefulWidget {
/// Whether this build can put a real webview on screen. One place, so the
/// panel and its tests agree on when the placeholder is the right answer.
- static bool get webviewAvailable => !kUnderTest && Platform.isMacOS;
+ static bool get webviewAvailable => !kUnderTest && RuntimePlatform.isMacOS;
@override
State<WebPanePanel> createState() => _WebPanePanelState();
@@ -152,7 +151,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
// while a viewer loads. WKWebView on macOS has no such setting (the plugin
// throws UnimplementedError, seen live 2026-09-15 as a red pane), so only
// platforms that do get it.
- if (!Platform.isMacOS) {
+ if (!RuntimePlatform.isMacOS) {
controller.setBackgroundColor(grid.AppPalette.windowBg);
}
controller.loadRequest(uri);
diff --git a/desktop/lib/widgets/window_chrome.dart b/desktop/lib/widgets/window_chrome.dart
index d4685c109..ff1dff898 100644
--- a/desktop/lib/widgets/window_chrome.dart
+++ b/desktop/lib/widgets/window_chrome.dart
@@ -1,14 +1,13 @@
-import 'dart:io' show Platform;
-
import 'package:flutter/widgets.dart';
import 'package:window_manager/window_manager.dart';
+import '../core/runtime_platform.dart';
import '../core/desktop_window.dart';
import '../shared/theme/app_theme.dart' as grid;
/// How far a full-width strip drawn at the very top of the window has to
/// start from the left to clear the traffic lights.
-double get trafficLightClearance => Platform.isMacOS ? 78.0 : 0.0;
+double get trafficLightClearance => RuntimePlatform.isMacOS ? 78.0 : 0.0;
/// The traffic lights' own row, as a drag handle.
///
@@ -38,11 +37,11 @@ class HarnessTopBar extends StatelessWidget {
/// Zero off macOS: there the native caption bar already holds this space, and
/// a second strip under it would be a gap with nothing in it.
- static double get height => Platform.isMacOS ? 32.0 : 0.0;
+ static double get height => RuntimePlatform.isMacOS ? 32.0 : 0.0;
@override
Widget build(BuildContext context) {
- if (!Platform.isMacOS) return const SizedBox.shrink();
+ if (!RuntimePlatform.isMacOS) return const SizedBox.shrink();
grid.AppTheme.watch(context);
// Drag only. The native tab strip above this bar owns the title-bar
// double-click and zooms the window itself; DragToMoveArea's own
@@ -116,7 +115,7 @@ class WindowDragStrip extends StatelessWidget {
Widget build(BuildContext context) {
return DragToMoveArea(
child: SizedBox(
- height: Platform.isMacOS ? windowDragBandHeight : 0,
+ height: RuntimePlatform.isMacOS ? windowDragBandHeight : 0,
width: double.infinity,
),
);
diff --git a/desktop/lib/widgets/workspace_welcome.dart b/desktop/lib/widgets/workspace_welcome.dart
index a544d3939..9fd67f2ea 100644
--- a/desktop/lib/widgets/workspace_welcome.dart
+++ b/desktop/lib/widgets/workspace_welcome.dart
@@ -45,6 +45,9 @@ class WorkspaceWelcome extends StatefulWidget {
}
class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
+ // Resolve the icon at compile time. Lazy initialization of Lucide's large
+ // generated library overflows the browser debug runtime's stack here.
+ static const _phoneIcon = LucideIcons.smartphone500;
WelcomeSessions? _sessions;
int _cursor = 0;
final _focus = FocusNode(debugLabel: 'Welcome sessions');
@@ -399,7 +402,7 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
alignment: Alignment.centerLeft,
// Drawn at the weight and height of the ⌘ keys beside it.
child: Icon(
- LucideIcons.smartphone500,
+ _phoneIcon,
color: accent,
size: (style.fontSize ?? 13) * 1.15,
),
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index 6451a83e9..b65479862 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -88,6 +88,7 @@ class WsConn {
/// Retained only for fixture constructor compatibility. Local transport ignores it.
final String? localApiKey;
final String? observerShareId;
+ bool get _directObserver => !isLocal && observerShareId != null;
final int localProtocolVersion;
/// A flat delay between reconnect attempts instead of the exponential backoff (1s→30s). Set for
@@ -129,6 +130,7 @@ class WsConn {
bool _ready = false;
int _attempt = 0;
Timer? _reconnectTimer;
+ Timer? _observerHandshakeTimer;
String? _tokenUsed;
bool _forceRelayReconnect = false;
final _pending = <String, _PendingRpc>{};
@@ -250,11 +252,19 @@ class WsConn {
if (_closing) return;
_tokenUsed = token;
final codecs = isLocal ? null : relayCodecs;
+ if (_directObserver && codecs == null) {
+ _refusePeer('Shared harnesses require a verified owner identity.');
+ return;
+ }
if (codecs != null) {
final codec = await codecs(machineId);
if (_closing) return;
if (codec == null) {
- _refusePeer('NO_PEER_LINK');
+ _refusePeer(
+ _directObserver
+ ? 'This invitation has no owner identity. Ask the owner to share it again.'
+ : 'NO_PEER_LINK',
+ );
return;
}
_codec = codec;
@@ -272,11 +282,14 @@ class WsConn {
}
uri = local;
} else {
- final base = Uri.parse('$wsBaseUrl/api/web-ws');
+ final base = Uri.parse(
+ '$wsBaseUrl/api/${_directObserver ? 'observer-ws' : 'web-ws'}',
+ );
uri = base.replace(
queryParameters: {
...base.queryParameters,
'autonomousEnv': autonomousEnv,
+ if (_directObserver) 'share': observerShareId!,
},
);
}
@@ -292,7 +305,20 @@ class WsConn {
return;
}
_channel = channel;
- await channel.ready;
+ if (_directObserver) {
+ _observerHandshakeTimer?.cancel();
+ _observerHandshakeTimer = Timer(const Duration(seconds: 15), () {
+ if (!_closing && !_ready && identical(_channel, channel)) {
+ unawaited(channel.sink.close());
+ _onDone(channel);
+ }
+ });
+ }
+ if (_directObserver) {
+ await channel.ready.timeout(const Duration(seconds: 15));
+ } else {
+ await channel.ready;
+ }
if (_closing || !identical(_channel, channel)) {
await channel.sink.close();
return;
@@ -304,16 +330,19 @@ class WsConn {
);
final forceRelayReconnect = _forceRelayReconnect;
_forceRelayReconnect = false;
- await sendFrame({
- 'type': 'machine_select',
- 'payload': {
- 'machineId': machineId,
- if (observerShareId != null) 'shareId': observerShareId,
- if (isLocal) 'localProtocolVersion': localProtocolVersion,
- if (isLocal && forceRelayReconnect) 'forceReconnect': true,
- },
- });
+ if (!_directObserver) {
+ await sendFrame({
+ 'type': 'machine_select',
+ 'payload': {
+ 'machineId': machineId,
+ if (observerShareId != null) 'shareId': observerShareId,
+ if (isLocal) 'localProtocolVersion': localProtocolVersion,
+ if (isLocal && forceRelayReconnect) 'forceReconnect': true,
+ },
+ });
+ }
} catch (_) {
+ _observerHandshakeTimer?.cancel();
if (!_closing) _scheduleReconnect();
} finally {
_connecting = false;
@@ -375,6 +404,7 @@ class WsConn {
}
void _markReady() {
+ _observerHandshakeTimer?.cancel();
_ready = true;
_attempt = 0;
onStatus(ConnectionStatus.connected);
@@ -389,9 +419,32 @@ class WsConn {
RelayCodec codec,
Map<String, dynamic> message,
) async {
+ if (_closing || !identical(_codec, codec)) return;
final payload = (message['payload'] as Map<String, dynamic>?) ?? {};
switch (message['type']) {
+ case 'observer_connected':
+ if (_directObserver) _channel?.sink.add(jsonEncode(codec.helloFrame()));
+ return;
+ case 'observer_welcome':
+ if (!_directObserver) return;
+ final verified = await codec.handleWelcome(payload);
+ if (_closing || !identical(_codec, codec)) return;
+ if (verified) {
+ _markReady();
+ } else {
+ _refusePeer('The shared harness identity could not be verified.');
+ }
+ return;
+ case 'observer_closed':
+ if (!_directObserver) return;
+ if (payload['retry'] == true) {
+ unawaited(_channel?.sink.close());
+ } else {
+ _refusePeer(payload['reason'] as String? ?? 'Sharing ended.');
+ }
+ return;
case 'connected':
+ if (_directObserver) return;
// 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) {
@@ -402,7 +455,10 @@ class WsConn {
}
return;
case 'e2e_welcome':
- if (await codec.handleWelcome(payload)) {
+ if (_directObserver) return;
+ final verified = await codec.handleWelcome(payload);
+ if (_closing || !identical(_codec, codec)) return;
+ if (verified) {
_markReady();
_plugin?.onSessionReady();
} else {
@@ -417,7 +473,17 @@ class WsConn {
return;
}
final clear = codec.decodeFrame(message);
- if (clear == null) return;
+ if (clear == null) {
+ if (_directObserver && message['type'] == 'observer_frame') {
+ _refusePeer('Shared harness verification failed.');
+ }
+ return;
+ }
+ if (_directObserver && clear['type'] == 'observer_binary') {
+ final bytes = (clear['payload'] as Map?)?['bytes'];
+ if (bytes is String) await onBinaryFrame?.call(base64Decode(bytes));
+ return;
+ }
final plain = <String, dynamic>{
...clear,
'payload': (clear['payload'] as Map<String, dynamic>?) ?? {},
@@ -445,6 +511,8 @@ class WsConn {
void _refusePeer(String reason) {
_closing = true;
_ready = false;
+ _observerHandshakeTimer?.cancel();
+ _rejectPending(reason);
_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
@@ -737,6 +805,7 @@ class WsConn {
void _onDone(WebSocketChannel channel) {
if (!identical(_channel, channel)) return;
+ _observerHandshakeTimer?.cancel();
_channel = null;
_sub = null;
_codec = null;
@@ -778,6 +847,10 @@ class WsConn {
if (code == 4403) {
_closing = true;
onStatus(ConnectionStatus.disconnected);
+ if (_directObserver) {
+ onLocalFailure?.call(4403, 'Sharing ended or invitation expired.');
+ return;
+ }
onAuthFailure('SSO environment does not match this backend');
return;
}
@@ -822,6 +895,7 @@ class WsConn {
Future<void> close() async {
_closing = true;
+ _observerHandshakeTimer?.cancel();
_ready = false;
_codec = null;
_disposePlugin();
@@ -854,6 +928,7 @@ class WsConn {
// 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;
+ _observerHandshakeTimer?.cancel();
_forceRelayReconnect = true;
_reconnectTimer?.cancel();
_ready = false;
diff --git a/desktop/pubspec.lock b/desktop/pubspec.lock
index 21f62cc7d..01ce3a39b 100644
--- a/desktop/pubspec.lock
+++ b/desktop/pubspec.lock
@@ -1,6 +1,14 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
+ archive:
+ dependency: "direct main"
+ description:
+ name: archive
+ sha256: "6c5bcd986e06b94e3c40244af471750840a3d2341d1f9763a1100a14add517b4"
+ url: "https://pub.dev"
+ source: hosted
+ version: "4.3.0"
args:
dependency: transitive
description:
@@ -447,6 +455,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.8"
+ posix:
+ dependency: transitive
+ description:
+ name: posix
+ sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.5.2"
process:
dependency: transitive
description:
@@ -725,7 +741,7 @@ packages:
source: hosted
version: "15.3.0"
web:
- dependency: transitive
+ dependency: "direct main"
description:
name: web
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yaml
index e537aebd3..926e81969 100644
--- a/desktop/pubspec.yaml
+++ b/desktop/pubspec.yaml
@@ -28,6 +28,8 @@ environment:
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
+ web: ^1.1.1
+ archive: ^4.0.9
flutter:
sdk: flutter
# Natural ordering for numbered agents, projects, and completion candidates.
@@ -107,12 +109,19 @@ dev_dependencies:
# The following section is specific to Flutter packages.
flutter:
+ fonts:
+ - family: Roboto Mono
+ fonts:
+ - asset: assets/fonts/roboto-mono/RobotoMono.ttf
+ - asset: assets/fonts/roboto-mono/RobotoMono-Italic.ttf
+ style: italic
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
assets:
+ - assets/fonts/roboto-mono/OFL.txt
- assets/machines.svg
- assets/models.svg
- assets/harnesses.svg
diff --git a/desktop/scripts/build-web-release.sh b/desktop/scripts/build-web-release.sh
new file mode 100644
index 000000000..f5917940a
--- /dev/null
+++ b/desktop/scripts/build-web-release.sh
@@ -0,0 +1,54 @@
+#!/usr/bin/env bash
+# Build the shared Flutter app for the existing harness.autonomous.ai host.
+set -euo pipefail
+
+version="${1:-}"
+if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ echo 'Usage: bash scripts/build-web-release.sh X.Y.Z' >&2
+ exit 1
+fi
+
+cd "$(dirname "$0")/.."
+if [[ -n "$(git status --porcelain -- .)" ]]; then
+ echo 'Commit the Flutter source before building a release.' >&2
+ exit 1
+fi
+source_commit="$(git rev-parse HEAD)"
+"${FLUTTER_BIN:-flutter}" build web --release --no-wasm-dry-run \
+ --no-web-resources-cdn --base-href=/harness-web/ \
+ --output=build/web-release --build-name="$version"
+
+python3 - "$version" "$source_commit" <<'PY'
+import hashlib
+import json
+from pathlib import Path
+import tarfile
+import sys
+
+version, commit = sys.argv[1:]
+root = Path('build/web-release')
+release = {
+ 'version': version,
+ 'sourceCommit': commit,
+ 'baseHref': '/harness-web/',
+ 'apiUrl': 'https://harness-api.autonomous.ai',
+}
+(root / 'release.json').write_text(json.dumps(release, indent=2) + '\n')
+output = Path('build/web-dist')
+output.mkdir(parents=True, exist_ok=True)
+archive = output / f'harness-web-{version}.tar.gz'
+with tarfile.open(archive, 'w:gz') as bundle:
+ for path in sorted(root.rglob('*')):
+ if path.is_symlink():
+ raise ValueError(f'Release assets must be regular files: {path}')
+ if path.is_file():
+ bundle.add(path, arcname=path.relative_to(root), recursive=False)
+checksum = hashlib.sha256(archive.read_bytes()).hexdigest()
+(output / f'{archive.name}.sha256').write_text(f'{checksum} {archive.name}\n')
+release.update({
+ 'archiveUrl': f'https://github.com/autonomous-ai/openharness/releases/download/v{version}_web/{archive.name}',
+ 'sha256': checksum,
+})
+(output / 'harness-web-release.json').write_text(json.dumps(release, indent=2) + '\n')
+print(json.dumps(release, indent=2))
+PY
diff --git a/desktop/scripts/serve-web.py b/desktop/scripts/serve-web.py
new file mode 100644
index 000000000..fc4bfeb01
--- /dev/null
+++ b/desktop/scripts/serve-web.py
@@ -0,0 +1,42 @@
+#!/usr/bin/env python3
+"""Preview build/web on loopback, including the OAuth callback route."""
+
+import argparse
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from urllib.parse import urlsplit
+
+
+class WebPreview(SimpleHTTPRequestHandler):
+ def do_GET(self):
+ if urlsplit(self.path).path in {"/callback", "/auth/callback"}:
+ self.path = "/index.html"
+ super().do_GET()
+
+ def end_headers(self):
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("Referrer-Policy", "no-referrer")
+ self.send_header("X-Content-Type-Options", "nosniff")
+ super().end_headers()
+
+ def log_request(self, code="-", size="-"):
+ # Authorization codes and state must not appear in the preview log.
+ self.log_message('"%s %s" %s %s', self.command,
+ urlsplit(self.path).path, code, size)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--port", type=int, default=3000)
+ args = parser.parse_args()
+ root = Path(__file__).resolve().parents[1] / "build" / "web"
+ if not (root / "index.html").is_file():
+ parser.error("Build the app first with flutter build web")
+ handler = partial(WebPreview, directory=str(root))
+ with ThreadingHTTPServer(("127.0.0.1", args.port), handler) as server:
+ print(f"Harness preview: http://127.0.0.1:{args.port}", flush=True)
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ pass
diff --git a/desktop/test/browser_login_test.dart b/desktop/test/browser_login_test.dart
new file mode 100644
index 000000000..3229fba53
--- /dev/null
+++ b/desktop/test/browser_login_test.dart
@@ -0,0 +1,296 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/viewer/browser_login.dart';
+import 'package:harness/viewer/direct_auth.dart';
+import 'package:harness/viewer/direct_auth_api.dart';
+
+class _Storage implements LocalKeyValueStore {
+ final values = <String, String>{};
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+class _Browser implements LoginBrowser {
+ @override
+ Uri uri = Uri.parse('https://harness.example/');
+ @override
+ String? transaction;
+ @override
+ void replaceLocation(String path) => uri = uri.resolve(path);
+}
+
+class _Api extends DirectAuthApi {
+ _Api() : super(config: AppConfig.dev);
+ final authorization = Completer<({String authorizeUrl, String tx})>();
+ final exchanged = Completer<IssuedTokens>();
+ final requests = <({String code, String state, String tx})>[];
+ String? origin;
+ String? nativeRedirect;
+ @override
+ Future<({String authorizeUrl, String tx})> authorizeNative(
+ String redirectUri,
+ ) {
+ nativeRedirect = redirectUri;
+ return authorization.future;
+ }
+
+ @override
+ Future<({String authorizeUrl, String tx})> authorizeWeb(String origin) {
+ this.origin = origin;
+ return authorization.future;
+ }
+
+ @override
+ Future<IssuedTokens> exchange({
+ required String code,
+ required String state,
+ required String tx,
+ }) {
+ requests.add((code: code, state: state, tx: tx));
+ return exchanged.future;
+ }
+}
+
+void main() {
+ final now = DateTime.utc(2026, 9, 27);
+ late _Browser browser;
+ late _Api api;
+ late AuthSession session;
+ late BrowserLogin login;
+
+ void callback({
+ String origin = 'https://harness.example',
+ String path = '/auth/callback',
+ String state = 'expected',
+ int? createdAt,
+ }) {
+ browser.uri = Uri.parse('$origin$path?code=one-use&state=$state');
+ browser.transaction = jsonEncode({
+ 'tx': 'transaction',
+ 'state': 'expected',
+ 'createdAt': createdAt ?? now.millisecondsSinceEpoch,
+ });
+ }
+
+ setUp(() {
+ browser = _Browser();
+ api = _Api();
+ session = AuthSession(storage: _Storage());
+ login = BrowserLogin(
+ auth: DirectAuth(session: session, api: api),
+ browser: browser,
+ clock: () => now,
+ );
+ });
+
+ test(
+ 'authorization stays in this tab and cancellation discards its transaction',
+ () async {
+ String? opened;
+ final pending = login.login(onAuthorizeUrl: (url) => opened = url);
+ final cancelled = expectLater(
+ pending,
+ throwsA(isA<DirectAuthException>()),
+ );
+ final url = Uri.https('sso.example', '/authorize', {
+ 'state': 'expected',
+ 'redirect_uri': 'https://harness.example/auth/callback',
+ }).toString();
+ api.authorization.complete((authorizeUrl: url, tx: 'transaction'));
+ await Future<void>.delayed(Duration.zero);
+ expect(api.origin, 'https://harness.example');
+ expect(api.nativeRedirect, isNull);
+ expect(opened, url);
+ expect(jsonDecode(browser.transaction!)['tx'], 'transaction');
+ login.cancel();
+ await cancelled;
+ expect(browser.transaction, isNull);
+ expect(await session.accessToken(), isNull);
+ },
+ );
+
+ for (final address in [
+ 'http://127.0.0.1:54732/workspace?tab=one#terminal',
+ 'http://localhost:3000/',
+ 'http://[::1]:3000/',
+ 'https://localhost/',
+ ]) {
+ test(
+ 'local preview at $address uses its exact loopback callback',
+ () async {
+ browser.uri = Uri.parse(address);
+ final redirectUri = '${browser.uri.origin}/callback';
+ String? opened;
+ final pending = login.login(onAuthorizeUrl: (url) => opened = url);
+ final cancelled = expectLater(
+ pending,
+ throwsA(isA<DirectAuthException>()),
+ );
+ expect(api.nativeRedirect, redirectUri);
+ expect(api.origin, isNull);
+ final url = Uri.https('sso.example', '/authorize', {
+ 'state': 'expected',
+ 'redirect_uri': redirectUri,
+ }).toString();
+ api.authorization.complete((authorizeUrl: url, tx: 'transaction'));
+ await Future<void>.delayed(Duration.zero);
+ expect(opened, url);
+ expect(jsonDecode(browser.transaction!)['tx'], 'transaction');
+ login.cancel();
+ await cancelled;
+ },
+ );
+ }
+
+ for (final address in [
+ 'https://localhost.example/',
+ 'https://127.0.0.1.example/',
+ 'http://192.168.1.10:3000/',
+ ]) {
+ test(
+ 'non-loopback preview at $address still requires a web origin',
+ () async {
+ browser.uri = Uri.parse(address);
+ final pending = login.login(
+ onAuthorizeUrl: (_) => fail('Must not navigate'),
+ );
+ expect(api.origin, browser.uri.origin);
+ expect(api.nativeRedirect, isNull);
+ api.authorization.complete((
+ authorizeUrl: Uri.https('sso.example', '/authorize', {
+ 'state': 'expected',
+ 'redirect_uri': 'https://harness.example/auth/callback',
+ }).toString(),
+ tx: 'transaction',
+ ));
+ await expectLater(pending, throwsA(isA<DirectAuthException>()));
+ expect(browser.transaction, isNull);
+ },
+ );
+ }
+
+ test('loopback sign-in rejects a callback on another port', () async {
+ browser.uri = Uri.parse('http://127.0.0.1:54732/');
+ final pending = login.login(
+ onAuthorizeUrl: (_) => fail('Must not navigate'),
+ );
+ api.authorization.complete((
+ authorizeUrl: Uri.https('sso.example', '/authorize', {
+ 'state': 'expected',
+ 'redirect_uri': 'http://127.0.0.1:3000/callback',
+ }).toString(),
+ tx: 'transaction',
+ ));
+ await expectLater(pending, throwsA(isA<DirectAuthException>()));
+ expect(browser.transaction, isNull);
+ });
+
+ test('rejects a backend callback for a different origin', () async {
+ final pending = login.login(
+ onAuthorizeUrl: (_) => fail('Must not navigate'),
+ );
+ api.authorization.complete((
+ authorizeUrl: Uri.https('sso.example', '/authorize', {
+ 'state': 'expected',
+ 'redirect_uri': 'https://another.example/auth/callback',
+ }).toString(),
+ tx: 'transaction',
+ ));
+ await expectLater(pending, throwsA(isA<DirectAuthException>()));
+ expect(browser.transaction, isNull);
+ });
+
+ for (final (origin, path) in [
+ ('https://harness.example', '/auth/callback'),
+ ('http://127.0.0.1:54732', '/callback'),
+ ]) {
+ test(
+ 'callback on $origin cleans the URL, exchanges once, and persists the session',
+ () async {
+ callback(origin: origin, path: path);
+ final first = login.checkStatus();
+ final second = login.checkStatus();
+ expect(identical(first, second), isTrue);
+ expect(browser.uri.toString(), '$origin/');
+ expect(browser.transaction, isNull);
+ expect(api.requests.single, (
+ code: 'one-use',
+ state: 'expected',
+ tx: 'transaction',
+ ));
+ api.exchanged.complete(
+ const IssuedTokens(
+ token: 'fixture-token',
+ refreshToken: 'fixture-refresh',
+ ),
+ );
+ expect((await first).loggedIn, isTrue);
+ expect(await session.accessToken(), 'fixture-token');
+ expect((await login.checkStatus()).loggedIn, isTrue);
+ expect(api.requests, hasLength(1));
+ },
+ );
+ }
+
+ test(
+ 'rejects unsolicited, expired and mismatched callbacks without an exchange',
+ () async {
+ for (final mode in ['missing', 'expired', 'state']) {
+ callback(
+ state: mode == 'state' ? 'wrong' : 'expected',
+ createdAt: mode == 'expired'
+ ? now.subtract(const Duration(minutes: 11)).millisecondsSinceEpoch
+ : null,
+ );
+ if (mode == 'missing') browser.transaction = null;
+ await expectLater(
+ login.checkStatus(),
+ throwsA(isA<DirectAuthException>()),
+ );
+ expect(browser.uri.query, isEmpty);
+ expect(browser.transaction, isNull);
+ }
+ expect(api.requests, isEmpty);
+ expect(await session.accessToken(), isNull);
+ },
+ );
+
+ test('logout while exchanging cannot restore a departed session', () async {
+ callback();
+ final pending = login.checkStatus();
+ final rejected = expectLater(pending, throwsA(isA<DirectAuthException>()));
+ await login.logout();
+ api.exchanged.complete(const IssuedTokens(token: 'stale'));
+ await rejected;
+ expect(await session.accessToken(), isNull);
+ });
+
+ test(
+ 'cancelled authorization cannot navigate or leave a transaction behind',
+ () async {
+ final pending = login.login(
+ onAuthorizeUrl: (_) => fail('Cancelled navigation'),
+ );
+ final cancelled = expectLater(
+ pending,
+ throwsA(isA<DirectAuthException>()),
+ );
+ login.cancel();
+ api.authorization.complete((
+ authorizeUrl: 'https://sso.example/',
+ tx: 'stale',
+ ));
+ await cancelled;
+ expect(browser.transaction, isNull);
+ },
+ );
+}
diff --git a/desktop/test/machines_panel_test.dart b/desktop/test/machines_panel_test.dart
index de0660bd5..0c24671ea 100644
--- a/desktop/test/machines_panel_test.dart
+++ b/desktop/test/machines_panel_test.dart
@@ -1,4 +1,5 @@
import 'support/workspace_tools.dart';
+import 'support/resource_picker.dart';
import 'dart:async';
import 'dart:io';
@@ -21,7 +22,6 @@ import 'package:harness/shortcuts/app_keymap.dart';
import 'package:harness/shortcuts/keymap_host.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/widgets/machines_panel.dart';
-import 'package:harness/widgets/toolbar_icon.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'keymap_host_test.dart' show MemoryKeymap, key;
@@ -360,7 +360,7 @@ void main() {
);
testWidgets(
- 'toolbar panel is anchored, resizes, and closes outside without dimming work',
+ 'workspace connection commands use the shared machine picker and inline forms',
(tester) async {
final previous = newHarnessOpensInBox;
newHarnessOpensInBox = true;
@@ -389,88 +389,51 @@ void main() {
});
app.add('server', 'Build server', online: false);
await mount(tester, size: const Size(1280, 800), workspace: true);
- final panel = find.byKey(const ValueKey('machines-panel'));
- expect(find.byType(Dialog), findsNothing);
- for (final barrier in tester.widgetList<ModalBarrier>(
- find.byType(ModalBarrier),
- )) {
- expect(
- barrier.color?.a ?? 0,
- 0,
- reason: 'The workspace stays undimmed',
- );
- }
- expect(tester.getRect(panel).top, greaterThan(40));
- expect(tester.getRect(panel).right, closeTo(1270, 2));
- expect(remoteInput, findsNothing);
- expect(localInput, findsNothing);
- expect(find.text('Set password'), findsOneWidget);
- expect(find.text('View harnesses'), findsNothing);
- expect(
- tester.getTopLeft(find.text('M2')).dy,
- lessThan(tester.getTopLeft(find.text('Mac mini')).dy),
- );
- expect(
- tester.getTopLeft(find.text('Mac mini')).dy,
- lessThan(tester.getTopLeft(find.text('iMac · Office')).dy),
+ final localInput = find.byKey(const ValueKey('remote-password-field'));
+ final remoteInput = find.byKey(
+ const ValueKey('remote-password-connect-field'),
);
- expect(
- tester.getTopLeft(find.text('iMac · Office')).dy,
- lessThan(tester.getTopLeft(find.text('Build server')).dy),
- );
- expect(
- find.text('12 harnesses · CPU 18% · RAM 10/32 GB'),
- findsOneWidget,
- );
- expect(find.text('8 harnesses · CPU 42% · RAM 24/64 GB'), findsOneWidget);
- expect(find.text('Connected'), findsNothing);
- expect(app.resourceReadIds, unorderedEquals(['local', 'office']));
- final widths = ['Set password', 'Connect'].map(
- (label) => tester
- .getSize(
- find.ancestor(
- of: find.text(label),
- matching: find.byType(TextButton),
- ),
- )
- .width,
- );
- expect(widths.toSet(), hasLength(1));
- for (final id in ['remote', 'office', 'server']) {
- expect(
- tester.getSize(find.byKey(ValueKey('machine-$id'))).height,
- lessThan(85),
- );
- }
- expect(
- find.byKey(const ValueKey('connect-machine-remote')),
- findsOneWidget,
+ expect(resourceScope('@'), findsOneWidget);
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ expect(find.byType(Dialog), findsNothing);
+ expect(resourceSearch(tester).rows.map((row) => row.title), [
+ 'Mac mini',
+ 'M2',
+ 'iMac · Office',
+ 'Build server',
+ 'Add machine',
+ ]);
+ expect(app.resourceReadIds, containsAll(['local', 'office']));
+ await selectResource(tester, 'machine:local');
+ await tap(
+ tester,
+ find.byKey(const ValueKey('resource-action:picker.resource_settings')),
);
- expect(find.byKey(const ValueKey('machine-office')), findsOneWidget);
- await capture(tester, 'machines-toolbar-panel');
- await tap(tester, find.text('Set password'));
expect(tester.widget<TextField>(localInput).focusNode!.hasFocus, isTrue);
- await capture(tester, 'machines-toolbar-set-password');
+ expect(resourceScope('@'), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- await openWorkspaceManagement(tester, 'machines');
- await tester.pumpAndSettle();
- expect(localInput, findsNothing);
- await tap(tester, find.byKey(const ValueKey('connect-machine-remote')));
+ await key(tester, LogicalKeyboardKey.escape);
+ await selectResource(tester, 'machine:remote');
+ await tap(
+ tester,
+ find.byKey(const ValueKey('resource-action:picker.resource_connect')),
+ );
expect(tester.widget<TextField>(remoteInput).focusNode!.hasFocus, isTrue);
- await capture(tester, 'machines-toolbar-connect');
+ expect(resourceScope('@'), findsOneWidget);
+ await capture(tester, 'machines-picker-connect');
tester.view.physicalSize = const Size(760, 620);
await tester.pumpAndSettle();
- expect(tester.getRect(panel).right, closeTo(750, 2));
- expect(tester.getRect(panel).bottom, lessThanOrEqualTo(620));
+ expect(remoteInput, findsOneWidget);
expect(tester.takeException(), isNull);
- await tester.tapAt(const Offset(30, 200));
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(panel, findsNothing);
+ expect(resourceField, findsNothing);
await mount(tester, workspace: true, brightness: Brightness.light);
- expect(find.byType(ToolbarIcon), findsNothing);
- expect(panel, findsOneWidget);
- await tap(tester, find.byTooltip('Close Machines'));
+ expect(resourceScope('@'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
expect(
find.byKey(const ValueKey('swarm-new-tab-button')).hitTestable(),
findsOneWidget,
@@ -1201,7 +1164,7 @@ void main() {
);
testWidgets(
- 'Machines toolbar remains usable in a short narrow workspace at large text size',
+ 'Machines picker remains usable in a short narrow workspace at large text size',
(tester) async {
final previous = newHarnessOpensInBox;
newHarnessOpensInBox = true;
@@ -1212,8 +1175,10 @@ void main() {
scale: 1.7,
workspace: true,
);
- expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
- await tap(tester, find.byTooltip('Close Machines'));
+ expect(resourceScope('@'), findsOneWidget);
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
expect(
find.byKey(const ValueKey('swarm-new-tab-button')).hitTestable(),
findsOneWidget,
diff --git a/desktop/test/observer_codec_test.dart b/desktop/test/observer_codec_test.dart
new file mode 100644
index 000000000..1a3d5f0d1
--- /dev/null
+++ b/desktop/test/observer_codec_test.dart
@@ -0,0 +1,137 @@
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/envelope.dart';
+import 'package:harness/e2ee/keys.dart';
+import 'package:harness/viewer/observer_relay_codec.dart';
+
+void main() {
+ test('observer verifies the owner and keeps the grant read-only', () async {
+ final owner = await E2eeIdentity.generate();
+ final codec = await ObserverRelayCodec.create(
+ machineId: 'm',
+ shareId: 's',
+ ownerPublicKey: b64e(owner.pub),
+ );
+ final peer = b64d(codec.helloFrame()['payload']['ephemeral'] as String);
+ final ephemeral = await Ephemeral.generate();
+ final keys = sessionKeys(
+ ephemeral,
+ peer,
+ codec.context,
+ peer,
+ ephemeral.pub,
+ );
+ final welcome = <String, dynamic>{
+ 'ephemeral': b64e(ephemeral.pub),
+ 'signature': b64e(
+ await owner.sign(
+ lvCat(['e2e-welcome-v1', codec.context, peer, ephemeral.pub]),
+ ),
+ ),
+ };
+ expect(
+ codec.encodeFrame({
+ 'type': 'terminal_open',
+ 'payload': <String, dynamic>{},
+ }),
+ isNull,
+ );
+ expect(await codec.handleWelcome(welcome), isTrue);
+ final outgoing = codec.encodeFrame({
+ 'type': 'terminal_open',
+ 'payload': {'agentId': 'a'},
+ })!;
+ expect(outgoing['type'], 'observer_frame');
+ expect(
+ unwrapPayload(
+ keys.c2s,
+ Map<String, dynamic>.from(outgoing['payload']['__e2e'] as Map),
+ 'observer_frame',
+ codec.context,
+ )?['type'],
+ 'terminal_open',
+ );
+ for (final type in [
+ 'terminal_input',
+ 'terminal_resize',
+ 'agent_create',
+ 'agent_read_file',
+ 'question_response',
+ ]) {
+ expect(
+ codec.encodeFrame({'type': type, 'payload': <String, dynamic>{}}),
+ isNull,
+ reason: type,
+ );
+ }
+ expect(codec.encodeBinary(Uint8List(1)), isNull);
+ final incoming = <String, dynamic>{
+ 'type': 'observer_frame',
+ 'payload': wrapPayload(
+ keys.s2c,
+ 'p',
+ 0,
+ 'observer_frame',
+ codec.context,
+ {
+ 'type': 'observer_viewer',
+ 'payload': {'state': 'live'},
+ },
+ ),
+ };
+ expect(codec.decodeFrame(incoming)?['type'], 'observer_viewer');
+ expect(codec.decodeFrame(incoming), isNull, reason: 'replay');
+ expect(
+ codec.decodeFrame({
+ 'type': 'observer_frame',
+ 'payload': wrapPayload(
+ keys.s2c,
+ 'p',
+ 1,
+ 'observer_frame',
+ 'harness-observer-v1:m:other-grant',
+ {'type': 'observer_viewer', 'payload': {}},
+ ),
+ }),
+ isNull,
+ );
+ expect(
+ await codec.handleWelcome(welcome),
+ isFalse,
+ reason: 'cannot reset an established session',
+ );
+ });
+
+ test(
+ 'an owner signature for another invitation cannot open this grant',
+ () async {
+ final owner = await E2eeIdentity.generate();
+ final codec = await ObserverRelayCodec.create(
+ machineId: 'm',
+ shareId: 's',
+ ownerPublicKey: b64e(owner.pub),
+ );
+ final peer = b64d(codec.helloFrame()['payload']['ephemeral'] as String);
+ final ephemeral = await Ephemeral.generate();
+ expect(
+ await codec.handleWelcome({
+ 'ephemeral': b64e(ephemeral.pub),
+ 'signature': b64e(
+ await owner.sign(
+ lvCat([
+ 'e2e-welcome-v1',
+ 'harness-observer-v1:m:other',
+ peer,
+ ephemeral.pub,
+ ]),
+ ),
+ ),
+ }),
+ isFalse,
+ );
+ expect(codec.encodeFrame({'type': 'terminal_open'}), isNull);
+ },
+ );
+}
diff --git a/desktop/test/observer_transport_test.dart b/desktop/test/observer_transport_test.dart
new file mode 100644
index 000000000..ad3d5b556
--- /dev/null
+++ b/desktop/test/observer_transport_test.dart
@@ -0,0 +1,166 @@
+@TestOn('vm')
+library;
+
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/envelope.dart';
+import 'package:harness/e2ee/keys.dart';
+import 'package:harness/viewer/observer_relay_codec.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+void main() {
+ test('a direct observer without a codec fails before dialing', () async {
+ String? refusal;
+ final conn = WsConn(
+ wsBaseUrl: 'ws://127.0.0.1:1',
+ autonomousEnv: 'prod',
+ machineId: 'machine',
+ observerShareId: 'grant',
+ accessTokenProvider: (_, _) async => 'fixture-token',
+ onAuthFailure: (reason) => fail(reason),
+ onLocalFailure: (_, reason) => refusal = reason,
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ addTearDown(conn.close);
+ await conn.connect();
+ expect(conn.isClosed, isTrue);
+ expect(conn.isReady, isFalse);
+ expect(refusal, contains('verified owner identity'));
+ });
+
+ test(
+ 'direct observer uses the grant socket and only forwards verified output',
+ () async {
+ const context = 'harness-observer-v1:machine:grant';
+ final owner = await E2eeIdentity.generate();
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ final sockets = <WebSocket>[];
+ addTearDown(() async {
+ for (final socket in sockets) {
+ await socket.close();
+ }
+ await server.close(force: true);
+ });
+ final frames = <Map<String, dynamic>>[];
+ server.listen((request) async {
+ expect(request.uri.path, '/api/observer-ws');
+ expect(request.uri.queryParameters['share'], 'grant');
+ expect(
+ request.headers.value('sec-websocket-protocol'),
+ 'fixture-token',
+ );
+ final socket = await WebSocketTransformer.upgrade(
+ request,
+ protocolSelector: (p) => p.first,
+ );
+ sockets.add(socket);
+ SessionKeys? keys;
+ socket.listen((raw) async {
+ expect(
+ raw,
+ isA<String>(),
+ reason: 'observers never send binary input',
+ );
+ final frame = jsonDecode(raw as String) as Map<String, dynamic>;
+ if (frame['type'] == 'observer_hello') {
+ final peer = b64d(frame['payload']['ephemeral'] as String);
+ final eph = await Ephemeral.generate();
+ keys = sessionKeys(eph, peer, context, peer, eph.pub);
+ socket.add(
+ jsonEncode({
+ 'type': 'observer_welcome',
+ 'payload': {
+ 'ephemeral': b64e(eph.pub),
+ 'signature': b64e(
+ await owner.sign(
+ lvCat(['e2e-welcome-v1', context, peer, eph.pub]),
+ ),
+ ),
+ },
+ }),
+ );
+ } else {
+ expect(frame['type'], 'observer_frame');
+ final clear = unwrapPayload(
+ keys!.c2s,
+ Map<String, dynamic>.from(frame['payload']['__e2e'] as Map),
+ 'observer_frame',
+ context,
+ )!;
+ frames.add(clear);
+ socket.add(
+ jsonEncode({
+ 'type': 'observer_frame',
+ 'payload': wrapPayload(
+ keys!.s2c,
+ 'p',
+ 0,
+ 'observer_frame',
+ context,
+ {
+ 'type': 'observer_binary',
+ 'payload': {
+ 'bytes': base64Encode([1, 2, 3]),
+ },
+ },
+ ),
+ }),
+ );
+ }
+ });
+ socket.add(jsonEncode({'type': 'observer_connected'}));
+ });
+ final connected = Completer<void>();
+ final received = Completer<Uint8List>();
+ final conn =
+ WsConn(
+ wsBaseUrl: 'ws://127.0.0.1:${server.port}',
+ autonomousEnv: 'prod',
+ machineId: 'machine',
+ observerShareId: 'grant',
+ relayCodecs: (_) => ObserverRelayCodec.create(
+ machineId: 'machine',
+ shareId: 'grant',
+ ownerPublicKey: b64e(owner.pub),
+ ),
+ accessTokenProvider: (_, _) async => 'fixture-token',
+ onAuthFailure: (reason) => fail(reason),
+ onEvent: (_) {},
+ onStatus: (status) {
+ if (status == ConnectionStatus.connected &&
+ !connected.isCompleted) {
+ connected.complete();
+ }
+ },
+ )
+ ..onBinaryFrame = (bytes) async {
+ if (!received.isCompleted) received.complete(bytes);
+ };
+ addTearDown(conn.close);
+ await conn.connect();
+ await connected.future.timeout(const Duration(seconds: 5));
+ expect(
+ await conn.sendTerminalFrame('terminal_input', {'data': 'forbidden'}),
+ isFalse,
+ );
+ expect(await conn.sendTerminalBinary(Uint8List(1)), isFalse);
+ expect(
+ await conn.sendTerminalFrame('terminal_open', {'agentId': 'a'}),
+ isTrue,
+ );
+ expect(await received.future.timeout(const Duration(seconds: 5)), [
+ 1,
+ 2,
+ 3,
+ ]);
+ expect(frames.single['type'], 'terminal_open');
+ },
+ );
+}
diff --git a/desktop/test/password_stretch_test.dart b/desktop/test/password_stretch_test.dart
new file mode 100644
index 000000000..81befdc25
--- /dev/null
+++ b/desktop/test/password_stretch_test.dart
@@ -0,0 +1,56 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart' show kIsWeb;
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/password_pake.dart';
+import 'package:harness/e2ee/scrypt.dart';
+
+void main() {
+ test(
+ 'native and cooperative scrypt match the RFC empty-password vector',
+ () async {
+ const expected =
+ '77d6576238657b203b19ca42c18a0497'
+ 'f16b4844e3074ae8dfdffa3fede21442'
+ 'fcd0069ded0948f8326a753a0fc81f17'
+ 'e8d3e0fb2e0d3628cf35e20c38d18906';
+ expect(hexOf(scrypt([], [], n: 16, r: 1, p: 1, dkLen: 64)), expected);
+ expect(
+ hexOf(await scryptCooperative([], [], n: 16, r: 1, p: 1, dkLen: 64)),
+ expected,
+ );
+ },
+ );
+
+ test(
+ 'machine password stretching matches Node at the production cost',
+ () async {
+ // Generated independently with node:crypto.scryptSync, N=2^17,r=8,p=1,
+ // maxmem=256MiB; salt=SHA256("e2e-remote-password-salt-v1|fixture-machine").
+ var ticks = 0;
+ final timer = Timer.periodic(
+ const Duration(milliseconds: 1),
+ (_) => ticks++,
+ );
+ addTearDown(timer.cancel);
+ final stretched = await stretchPassword(
+ 'browser-fixture-only',
+ 'fixture-machine',
+ );
+ timer.cancel();
+ expect(
+ hexOf(stretched),
+ '0bcc55a7792882037a7fd20323b14128a31a44d2c0ddf6d45e44ad2cdb5536b2',
+ );
+ if (kIsWeb) {
+ expect(
+ ticks,
+ greaterThan(1),
+ reason: 'The browser must remain responsive while linking',
+ );
+ }
+ },
+ timeout: const Timeout(Duration(minutes: 2)),
+ );
+}
diff --git a/desktop/test/web/browser_persistence_test.dart b/desktop/test/web/browser_persistence_test.dart
new file mode 100644
index 000000000..239513007
--- /dev/null
+++ b/desktop/test/web/browser_persistence_test.dart
@@ -0,0 +1,279 @@
+@TestOn('browser')
+library;
+
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/harness_file_store.dart';
+import 'package:harness/viewer/direct_auth_api.dart';
+import 'package:harness/viewer/platform_auth_web.dart';
+import 'package:harness/viewer/viewer_key_store.dart';
+import 'package:web/web.dart' as web;
+
+class _Api extends DirectAuthApi {
+ _Api() : super(config: AppConfig.dev);
+ int refreshCount = 0;
+ Completer<IssuedTokens>? refreshGate;
+
+ @override
+ Future<IssuedTokens> refresh(
+ String refreshToken, {
+ required String autonomousEnv,
+ }) async {
+ refreshCount++;
+ expect(refreshToken, 'fixture-refresh');
+ return await refreshGate?.future ??
+ const IssuedTokens(
+ token: 'renewed',
+ refreshToken: 'rotated-refresh',
+ expiresIn: 3600,
+ );
+ }
+}
+
+Future<void> _until(bool Function() ready) async {
+ for (var i = 0; i < 100 && !ready(); i++) {
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ }
+ expect(ready(), isTrue);
+}
+
+void main() {
+ const prefix = 'harness.web.v1.';
+ late HarnessFileStore store;
+ late AuthSession session;
+ late _Api api;
+ final clients = <BrowserAuth>[];
+
+ BrowserAuth client({void Function()? reload}) {
+ final auth = BrowserAuth(
+ session: AuthSession(storage: HarnessFileStore()),
+ api: api,
+ reload: reload ?? () => fail('Unexpected account change'),
+ );
+ clients.add(auth);
+ return auth;
+ }
+
+ setUp(() {
+ // Flutter's isolated test origin; never the user's browser profile.
+ web.window.localStorage.clear();
+ web.window.sessionStorage.clear();
+ store = HarnessFileStore();
+ session = AuthSession(storage: store);
+ api = _Api();
+ });
+ tearDown(() {
+ for (final auth in clients) {
+ auth.dispose();
+ }
+ clients.clear();
+ web.window.localStorage.clear();
+ web.window.sessionStorage.clear();
+ });
+
+ test('reopening retains sign-in, identity and machine links', () async {
+ final auth = client();
+ await auth.signIn(
+ const IssuedTokens(
+ token: 'fixture-token',
+ refreshToken: 'fixture-refresh',
+ ),
+ );
+ final keys = ViewerKeyStore(storage: store);
+ final identity = await keys.identity();
+ await keys.pin('fixture-machine', List.filled(32, 7), label: 'Fixture');
+
+ web.window.sessionStorage.clear();
+ final reopened = client();
+ final reopenedKeys = ViewerKeyStore(storage: HarnessFileStore());
+ expect(await reopened.hasSession(), isTrue);
+ expect(await reopened.accessToken(), 'fixture-token');
+ expect((await reopenedKeys.identity()).seed, identity.seed);
+ expect((await reopenedKeys.peer('fixture-machine'))?.label, 'Fixture');
+
+ await reopened.signOut();
+ expect(await session.accessToken(), isNull);
+ expect(await session.refreshToken(), isNull);
+ // Signing out should not force the browser to pair its machines again.
+ expect((await reopenedKeys.identity()).seed, identity.seed);
+ expect(await reopenedKeys.peer('fixture-machine'), isNotNull);
+ });
+
+ test('migrates existing tab credentials once, leaving OAuth tab-local', () async {
+ web.window.sessionStorage.setItem('${prefix}auth_access_token', 'legacy');
+ web.window.sessionStorage.setItem('${prefix}auth_refresh_token', 'refresh');
+ web.window.sessionStorage.setItem(
+ '${prefix}viewer_e2ee_identity_seed',
+ 'seed',
+ );
+ web.window.sessionStorage.setItem(
+ '${prefix}viewer_e2ee_machine_peers',
+ '[]',
+ );
+ web.window.sessionStorage.setItem(
+ '${prefix}auth_transaction',
+ 'transaction',
+ );
+ expect(await session.accessToken(), 'legacy');
+ expect(await store.read('viewer_e2ee_identity_seed'), 'seed');
+ expect(
+ web.window.sessionStorage.getItem('${prefix}auth_access_token'),
+ isNull,
+ );
+ expect(
+ web.window.localStorage.getItem('${prefix}auth_transaction'),
+ isNull,
+ );
+ expect(
+ web.window.sessionStorage.getItem('${prefix}auth_transaction'),
+ 'transaction',
+ );
+
+ await session.clear();
+ // Simulate an older tab returning after sign-out; never revive its tokens.
+ web.window.sessionStorage.setItem('${prefix}auth_access_token', 'legacy');
+ expect(await HarnessFileStore().read('auth_access_token'), isNull);
+ });
+
+ test('two runtimes rotate an expired refresh token only once', () async {
+ await session.saveLogin(
+ token: 'fixture-token',
+ refreshToken: 'fixture-refresh',
+ );
+ await store.write('auth_access_token_expires_at', '1');
+ final first = client(), second = client();
+ final values = await Future.wait([
+ first.accessToken(),
+ second.accessToken(),
+ ]);
+ expect(values, ['renewed', 'renewed']);
+ expect(api.refreshCount, 1);
+ expect(await session.refreshToken(), 'rotated-refresh');
+ });
+
+ test(
+ 'concurrent forced retries reuse the refresh that won the lock',
+ () async {
+ await session.saveLogin(
+ token: 'fixture-token',
+ refreshToken: 'fixture-refresh',
+ );
+ final first = client(), second = client();
+ final values = await Future.wait([
+ first.accessToken(force: true, failedToken: 'fixture-token'),
+ second.accessToken(force: true, failedToken: 'fixture-token'),
+ ]);
+ expect(values, ['renewed', 'renewed']);
+ expect(api.refreshCount, 1);
+ },
+ );
+
+ test(
+ 'logout during refresh leaves no credentials and rejects its result',
+ () async {
+ await session.saveLogin(
+ token: 'fixture-token',
+ refreshToken: 'fixture-refresh',
+ );
+ api.refreshGate = Completer<IssuedTokens>();
+ final auth = client();
+ final pending = auth.accessToken(force: true);
+ final rejected = expectLater(
+ pending,
+ throwsA(isA<DirectAuthException>()),
+ );
+ await _until(() => api.refreshCount == 1);
+ final logout = auth.signOut();
+ api.refreshGate!.complete(
+ const IssuedTokens(token: 'late', refreshToken: 'late'),
+ );
+ await rejected;
+ await logout;
+ expect(await session.accessToken(), isNull);
+ expect(await session.refreshToken(), isNull);
+ },
+ );
+
+ for (final expires in [false, true]) {
+ test(
+ 'refresh failure ${expires ? 'expires' : 'preserves'} the saved login',
+ () async {
+ await session.saveLogin(
+ token: 'fixture-token',
+ refreshToken: 'fixture-refresh',
+ );
+ api.refreshGate = Completer<IssuedTokens>();
+ final auth = client();
+ final pending = auth.accessToken(force: true);
+ final rejected = expectLater(
+ pending,
+ throwsA(isA<DirectAuthException>()),
+ );
+ await _until(() => api.refreshCount == 1);
+ api.refreshGate!.completeError(
+ DirectAuthException('Fixture failure', signedOut: expires),
+ );
+ await rejected;
+ expect(await auth.hasSession(), !expires);
+ },
+ );
+ }
+
+ test(
+ 'another tab changing accounts reloads and rejects old account work',
+ () async {
+ await session.saveLogin(
+ token: 'fixture-token',
+ refreshToken: 'fixture-refresh',
+ );
+ var reloads = 0;
+ final previous = client(reload: () => reloads++);
+ final other = client();
+ await other.signIn(const IssuedTokens(token: 'new-account'));
+ // Real storage events fire in other documents; dispatch one for this fixture.
+ web.window.dispatchEvent(
+ web.StorageEvent(
+ 'storage',
+ web.StorageEventInit(
+ key: '${prefix}auth_generation',
+ storageArea: web.window.localStorage,
+ ),
+ ),
+ );
+ expect(reloads, 1);
+ await expectLater(
+ previous.accessToken(),
+ throwsA(isA<DirectAuthException>()),
+ );
+ await expectLater(
+ previous.signOut(),
+ throwsA(isA<DirectAuthException>()),
+ );
+ expect(await session.accessToken(), 'new-account');
+ },
+ );
+
+ test(
+ 'simultaneous machine linking preserves one identity and both peers',
+ () async {
+ final first = ViewerKeyStore(storage: store);
+ final second = ViewerKeyStore(storage: HarnessFileStore());
+ final identities = await Future.wait([
+ first.identity(),
+ second.identity(),
+ ]);
+ expect(identities[0].seed, identities[1].seed);
+ await Future.wait([
+ first.pin('one', List.filled(32, 1)),
+ second.pin('two', List.filled(32, 2)),
+ ]);
+ expect(
+ (await first.peers()).map((peer) => peer.machineId),
+ unorderedEquals(['one', 'two']),
+ );
+ },
+ );
+}
diff --git a/desktop/test/web/browser_workspace_test.dart b/desktop/test/web/browser_workspace_test.dart
new file mode 100644
index 000000000..f238ff22c
--- /dev/null
+++ b/desktop/test/web/browser_workspace_test.dart
@@ -0,0 +1,262 @@
+@TestOn('browser')
+library;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.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/desktop_window.dart';
+import 'package:harness/core/harness_file_store.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:harness/core/viewer_mode.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/screens/login_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/grid_pictures.dart';
+import 'package:harness/terminal/terminal_font_store.dart';
+import 'package:harness/widgets/web_download_button.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:web/web.dart' as web;
+
+void main() {
+ test(
+ 'a late model response cannot cross an account change in JavaScript',
+ () {
+ final pictures = GridPictures();
+ addTearDown(pictures.dispose);
+ final response = GridModels.fromReply({'models': []});
+ pictures.adopt('machine', response);
+ final oldEpoch = pictures.epochOf('machine');
+ pictures.clear();
+ expect(pictures.adopt('machine', response, ifEpoch: oldEpoch), isFalse);
+ expect(pictures['machine'], isNull);
+ },
+ );
+
+ test(
+ 'browser persists preferences and credentials across tab storage loss',
+ () async {
+ final store = HarnessFileStore.shared;
+ const pref = 'test_browser_preference',
+ credential = 'auth_test_browser_token';
+ addTearDown(() async {
+ await store.delete(pref);
+ await store.delete(credential);
+ });
+ await store.write(pref, 'large');
+ await store.write(credential, 'synthetic');
+ expect(await store.readMany([pref, credential]), {
+ pref: 'large',
+ credential: 'synthetic',
+ });
+ expect(web.window.localStorage.getItem('harness.web.v1.$pref'), 'large');
+ expect(
+ web.window.localStorage.getItem('harness.web.v1.$credential'),
+ 'synthetic',
+ );
+ expect(
+ web.window.sessionStorage.getItem('harness.web.v1.$credential'),
+ isNull,
+ );
+ expect(await HarnessFileStore().read(credential), 'synthetic');
+ await store.delete(credential);
+ expect(await store.read(credential), isNull);
+ },
+ );
+
+ testWidgets('the desktop workspace and command picker mount in the browser', (
+ tester,
+ ) async {
+ expect(
+ kUnderTest,
+ isTrue,
+ reason: 'Run with --dart-define=HARNESS_TEST=true',
+ );
+ expect(kViewerMode, isTrue);
+ expect(hasManagedWindow, isFalse);
+ expect(
+ TerminalFontChoice.defaultForPlatform,
+ TerminalFontChoice.robotoMono,
+ );
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession())
+ ..newSwarm(newTabPage: true);
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(notifier: app),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(find.text('Harness like a boss.'), findsOneWidget);
+ expect(find.byType(WebDownloadButton), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ final tabs = app.swarms.length;
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyT);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(app.swarms.length, tabs + 1);
+ const modifier = LogicalKeyboardKey.altLeft;
+ await tester.sendKeyDownEvent(modifier);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyP);
+ await tester.sendKeyUpEvent(modifier);
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(find.byKey(const ValueKey('swarm-search-input')), findsOneWidget);
+ expect(find.textContaining('No harnesses yet.'), findsOneWidget);
+ expect(find.textContaining('This tab is full'), findsNothing);
+ expect(tester.takeException(), isNull);
+ tester.view.physicalSize = const Size(390, 844);
+ await tester.pump(const Duration(milliseconds: 100));
+ final download = tester.getRect(find.byType(WebDownloadButton));
+ expect(download.right, lessThanOrEqualTo(390));
+ expect(download.top, greaterThanOrEqualTo(0));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ app.dispose();
+ });
+
+ testWidgets(
+ 'machine commands and link requests use the same browser picker',
+ (tester) async {
+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession())
+ ..currentUser = const CurrentUserProfile(email: '[email protected]')
+ ..newSwarm(newTabPage: true);
+ const machine = Machine(
+ machineId: 'browser-fixture',
+ name: 'Studio machine',
+ authMode: MachineAuthMode.remote,
+ );
+ app.machines = [machine];
+ app.machineStates[machine.machineId] = MachineState(machine)
+ ..nodeOnline = true
+ ..needsLink = true
+ ..agentLoadStatus = AgentLoadStatus.needsLink;
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(notifier: app),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ Future<void> machinesShortcut() async {
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyM);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
+ await tester.pump(const Duration(milliseconds: 200));
+ }
+
+ void expectMachines() {
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ expect(search.scopePrefix, '@');
+ expect(search.rows.map((row) => row.title), contains('Studio machine'));
+ expect(search.rows.last.title, 'Add machine');
+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ expect(find.text('Starting Harness…'), findsNothing);
+ }
+
+ for (final command in [
+ 'Machine connection settings',
+ 'Connect another machine',
+ ]) {
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyP);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.enterText(input, '> $command');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 200));
+ expectMachines();
+ await machinesShortcut();
+ expect(input, findsNothing);
+ await machinesShortcut();
+ expectMachines();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ }
+
+ // A selected unlinked machine must use that picker too, and closing it
+ // must stay dismissed until the user deliberately revisits the machine.
+ app.showMachinePane(machine.machineId);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pump();
+ expectMachines();
+ expect(
+ tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search
+ .selected
+ ?.machineId,
+ machine.machineId,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ app.notifyListeners();
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(input, findsNothing);
+ expect(app.isLinkPromptDismissed(machine.machineId), isTrue);
+ app.showMachinePane(machine.machineId);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pump();
+ expectMachines();
+ await tester.tap(
+ find.byKey(const ValueKey('resource-action:picker.resource_connect')),
+ );
+ await tester.pump();
+ expect(
+ find.byKey(const ValueKey('remote-password-connect-field')),
+ findsOneWidget,
+ );
+ expect(input, findsOneWidget);
+ expect(find.byType(Dialog), findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ app.dispose();
+ },
+ );
+
+ testWidgets(
+ 'web landing keeps a large sign-in action and download visible on a phone',
+ (tester) async {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ );
+ tester.view.physicalSize = const Size(390, 640);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: LoginScreen(notifier: app),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ final download = tester.getRect(find.byType(WebDownloadButton));
+ final signIn = tester.getRect(
+ find.widgetWithText(FilledButton, 'Sign in'),
+ );
+ expect(download.bottom, lessThan(signIn.top));
+ expect(download.right, lessThanOrEqualTo(390));
+ expect(signIn.height, greaterThanOrEqualTo(56));
+ expect(find.text('Sign in').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ app.dispose();
+ },
+ );
+}
diff --git a/desktop/test/wire_counter_test.dart b/desktop/test/wire_counter_test.dart
new file mode 100644
index 000000000..cb9d71c83
--- /dev/null
+++ b/desktop/test/wire_counter_test.dart
@@ -0,0 +1,94 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:archive/archive.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/wire_counter.dart';
+import 'package:harness/e2ee/primitives.dart';
+import 'package:harness/e2ee/terminal_cipher.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/terminal/terminal_session.dart';
+
+void main() {
+ const stream = '00112233-4455-6677-8899-aabbccddeeff';
+
+ test('wire counters retain exact bytes across 32-bit boundaries', () {
+ const vectors = {
+ 0: [0, 0, 0, 0, 0, 0, 0, 0],
+ 4294967295: [0, 0, 0, 0, 255, 255, 255, 255],
+ 4294967296: [0, 0, 0, 1, 0, 0, 0, 0],
+ 4294967297: [0, 0, 0, 1, 0, 0, 0, 1],
+ maxSafeInteger: [0, 31, 255, 255, 255, 255, 255, 255],
+ };
+ for (final entry in vectors.entries) {
+ final data = ByteData(8);
+ writeWireCounter(data, 0, entry.key);
+ expect(data.buffer.asUint8List(), entry.value);
+ expect(readWireCounter(data, 0), entry.key);
+ expect(counterNonce(entry.key), [...entry.value, 0, 0, 0, 0]);
+ }
+ final unsafe = ByteData(8)..setUint32(0, 0x200000);
+ expect(readWireCounter(unsafe, 0), isNull);
+ expect(() => counterNonce(maxSafeInteger + 1), throwsRangeError);
+ expect(() => counterNonce(-1), throwsRangeError);
+ });
+
+ test('encrypted terminal bytes preserve large sequence and nonce values', () {
+ final key = List<int>.generate(32, (i) => i);
+ final frame = TerminalBinaryFrame(
+ kind: TerminalBinaryKind.output,
+ streamId: stream,
+ seq: 4294967297,
+ bytes: Uint8List.fromList(utf8.encode('shared terminal')),
+ compressed: false,
+ );
+ final wire = sealTerminalBinary(key, maxSafeInteger, frame)!;
+ final opened = openTerminalBinary(key, wire)!;
+ expect(opened.counter, maxSafeInteger);
+ expect(opened.frame.seq, frame.seq);
+ expect(opened.frame.bytes, frame.bytes);
+ wire[wire.length - 1] ^= 1;
+ expect(openTerminalBinary(key, wire), isNull);
+ });
+
+ test('compressed keyframes reach the shared terminal renderer', () async {
+ final sent = <Map<String, dynamic>>[];
+ final session = TerminalSession(
+ machineId: 'fixture',
+ agentId: 'agent',
+ engineId: 'codex',
+ agentName: 'Fixture',
+ send: (type, payload) async {
+ sent.add({'type': type, ...payload});
+ return true;
+ },
+ sendBinary: (_) async => true,
+ );
+ addTearDown(session.dispose);
+ await session.open();
+ await session.handleFrame('terminal_ready', {
+ 'requestId': sent.first['requestId'],
+ 'protocolVersion': 3,
+ 'streamId': stream,
+ 'agentId': 'agent',
+ });
+ await session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: stream,
+ seq: 0,
+ bytes: Uint8List.fromList(
+ const ZLibEncoder().encode(utf8.encode('Browser terminal ready')),
+ ),
+ compressed: true,
+ cols: 100,
+ rows: 24,
+ ),
+ );
+ expect(
+ session.terminal.buffer.getText(),
+ contains('Browser terminal ready'),
+ );
+ expect(session.acceptsInput, isTrue);
+ });
+}
diff --git a/desktop/web/_headers b/desktop/web/_headers
new file mode 100644
index 000000000..8e1e9a28b
--- /dev/null
+++ b/desktop/web/_headers
@@ -0,0 +1,7 @@
+/*
+ Cache-Control: no-cache
+ Referrer-Policy: no-referrer
+ X-Content-Type-Options: nosniff
+
+/auth/callback
+ Cache-Control: no-store
diff --git a/desktop/web/_redirects b/desktop/web/_redirects
new file mode 100644
index 000000000..eb3532fbf
--- /dev/null
+++ b/desktop/web/_redirects
@@ -0,0 +1,2 @@
+# Static hosts such as Cloudflare Pages and Netlify serve existing files first.
+/* /index.html 200
diff --git a/desktop/web/index.html b/desktop/web/index.html
new file mode 100644
index 000000000..9e0c16850
--- /dev/null
+++ b/desktop/web/index.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <base href="$FLUTTER_BASE_HREF">
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta name="description" content="Your Harness workspace. Connect to your machines and work with your agents from the browser.">
+ <meta name="theme-color" content="#141414">
+ <meta name="referrer" content="no-referrer">
+ <link rel="manifest" href="manifest.json">
+ <title>Harness</title>
+ <style>
+ html, body { margin: 0; height: 100%; background: #141414; color: #dedede; }
+ </style>
+</head>
+<body>
+ <noscript>Enable JavaScript to open your Harness workspace.</noscript>
+ <!-- Inline Flutter's generated loader so startup needs no extra script round trip. -->
+ <script>{{flutter_bootstrap_js}}</script>
+</body>
+</html>
diff --git a/desktop/web/manifest.json b/desktop/web/manifest.json
new file mode 100644
index 000000000..52a1d3dc4
--- /dev/null
+++ b/desktop/web/manifest.json
@@ -0,0 +1,9 @@
+{
+ "name": "Harness",
+ "short_name": "Harness",
+ "start_url": ".",
+ "display": "standalone",
+ "background_color": "#141414",
+ "theme_color": "#141414",
+ "description": "Your machines, agents, and workspace in the browser."
+}
diff --git a/docs/architecture.md b/docs/architecture.md
index 789c53b5d..83c2e8227 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -1,22 +1,124 @@
# How it works
+One execution system, with several interfaces. Work belongs to the machine running it;
+opening or closing a view does not determine whether that work runs.
+
+## System overview
+
+Conceptual architecture, recorded September 27, 2026. The founder identifies the TUI as part
+of current development; this diagram describes its intended client role. The web app is now
+a browser target of the existing desktop Flutter package, available as a public preview at
+[harness.autonomous.ai](https://harness.autonomous.ai).
+[Public shared-session pages](product-direction.md#web-shared-sessions-as-an-acquisition-loop)
+remain the next acquisition experiment beyond authenticated workspace access and private invitations.
+The [product direction and roadmap](product-direction.md)
+describe the larger bet and its proposed sequence.
+
+```text
+ HUMAN
+ |
+ +-------------------+-------------------+
+ | | |
+ DEEP WORK QUICK CONTROL AUTOMATION
+ | | |
+ +------+------+ +------+------+ +-----+
+ | Desktop | | Mobile | | CLI |
+ | TUI (dev) | | Web | +--+--+
+ +------+------+ +------+------+ |
+ | | |
+ +-------------------+-------------------+
+ |
+ SHARED COMMAND + EVENT CONTRACT
+ start / resume / stop / answer
+ status / questions / results
+ |
+ +----------------+----------------+
+ | |
+ Local socket Encrypted remote access
+ | P2P for terminal traffic
+ | Relay path / fallback
+ | |
+ v v
+ +-----------------------+ +-----------------------+
+ | DAEMON: laptop | | DAEMON: workstation |
+ | | | |
+ | Work + sessions | | Work + sessions |
+ | Status + questions | | Status + questions |
+ | Engine adapters | | Engine adapters |
+ | Tool/viewer lifecycle | | Tool/viewer lifecycle |
+ +-----------+-----------+ +-----------+-----------+
+ ^ | |
+ | v v
+ | +--------------------+ +--------------------+
+ | | Agent processes | | Agent processes |
+ | | Domain tools | | Domain tools |
+ | | Project files | | Project files |
+ | | Artifacts + checks | | Artifacts + checks |
+ | +--------------------+ +--------------------+
+ |
+ USB
+ |
+ +-----------------------+
+ | HARNESS DEVICE |
+ | Glance at progress |
+ | Answer questions |
+ | Speak instructions |
+ +-----------------------+
+
+
+ SUPPORTING SERVICES
+ +----------------------------------------------------+
+ | Backend: accounts, machine discovery, shared tabs |
+ | Relay: connection signaling + encrypted forwarding |
+ | Store: domain packages, tools, skills, viewers |
+ +----------------------------------------------------+
```
- ( ◉ ) Harness device (USB)
- │
- ┌─────────── this computer ───────────┐
- │ Harness app ── loopback ──▶ harness daemon ──▶ tmux ──▶ claude · codex · … │
- └──────────────────────────────┬──────┘
- │ WebSocket (E2EE)
- ╔═════════╧═════════╗
- ║ Harness Relay ║ store and forward, no keys
- ╚═════════╤═════════╝
- ┌───────────────────────┼───────────────────────┐
- your server your platform harness.autonomous.ai
- harness daemon your HTTP API the web client
- tmux · hermes · muse (provider) (paired browser)
- ▲
- └── terminal traffic goes direct over WebRTC when ICE succeeds
-```
+
+The contract in the diagram is an API boundary, not an extra server. The daemon already
+exposes commands and events through its [local socket](cli.md#automation). A common contract
+does not require every client to expose every operation.
+
+The diagram groups interfaces by their main job; the CLI is also useful for interactive
+administration, and desktop work includes quick decisions. Actual connection paths differ:
+
+- **Desktop and local CLI commands** reach the local daemon. Desktop access to another
+ machine goes through that local daemon's encrypted link.
+- **Mobile** is a standalone client that authenticates and terminates encryption itself.
+ It hosts no agents. See [the mobile architecture](../mobile/README.md).
+- **Web** shares desktop's Flutter screens, state, and terminal renderer in `desktop/`.
+ It authenticates and terminates encryption in the browser, reaching machines through
+ the relay. Browser sign-in, storage, and native capability adapters are separate;
+ there is no browser daemon. This first target does not negotiate WebRTC.
+- **Remote terminal traffic** can use direct WebRTC or TURN; the encrypted relay path
+ remains available. Other command/event traffic uses the supported daemon/relay paths.
+- **The device** communicates over USB with its host daemon. It does not connect to the
+ backend or execute agents.
+
+## Ownership boundaries
+
+| Component | Responsibility |
+| --- | --- |
+| Daemon | Authoritative machine execution state, agent lifecycle, question state, engine integration, and tool/viewer processes. |
+| CLI | Scriptable operations and machine administration over the execution system. |
+| Desktop | Rich interaction, terminal presentation, artifact inspection, and local window layout. |
+| Mobile | Remote access, focused interaction, and decisions while away from the desktop. |
+| Device | Desk status, questions, and voice input through the host. |
+| TUI, in development | Interactive access inside a terminal, using the same operations. |
+| Web, public preview | The shared desktop workspace in a browser, including private read-only invitations; public session pages for discovery and acquisition follow separately. |
+| Backend and relay | Identity, discovery, selected shared metadata, signaling, and encrypted forwarding. |
+| Domain packages | Instructions, skills, toolchain setup, project templates, checks, and viewers. |
+
+Window layouts belong to clients; account-level tab membership is shared through the backend.
+Runtime truth belongs to the daemon owning the work. A question answered through one interface
+must resolve for the others. Closing an interface leaves execution running on an available host;
+it does not make a sleeping or disconnected host capable of continuing work elsewhere.
+
+The current [orchestrator](../cli/src/orchestrator/service.ts) already persists local project
+runs, task dependencies, and artifact handoffs. Cross-machine orchestration, project migration,
+and universal engine-session portability are separate capabilities; access to a remote terminal
+does not provide them automatically.
+
+## Daemon, sessions, and transport
**The daemon** runs detached under your account. Every five seconds it reconciles the `harness-*`
tmux sessions with its registry; a pane has to be missing on two scans before its agent is marked
@@ -43,19 +145,22 @@ to it. Encryption is on for every path and has no switch:
- A **per-process group key** so one event encrypts once for many readers.
- **ChaCha20-Poly1305** on every frame, with the associated data binding frame type and session.
-The crypto core lives in [`cli/src/lib/e2ee/`](cli/src/lib/e2ee/) and is a byte-identical twin of the
+The crypto core lives in [`cli/src/lib/e2ee/`](../cli/src/lib/e2ee/) and is a byte-identical twin of the
browser's copy, with a drift-guard test and committed self-vectors.
## Providers, relay, web
-- **`provider/`** — the spec ([`spec/README.md`](provider/spec/README.md)), the deterministic
- [`reference-provider`](provider/reference-provider/) with the conformance runner on port 4319, and
- [`example-provider`](provider/example-provider/), a real one backed by the local `claude` CLI on
+- **`provider/`** — the spec ([`spec/README.md`](../provider/spec/README.md)), the deterministic
+ [`reference-provider`](../provider/reference-provider/) with the conformance runner on port 4319, and
+ [`example-provider`](../provider/example-provider/), a real one backed by the local `claude` CLI on
port 4502 (read its README before running it; it skips permissions). `provider/e2e` runs both.
-- **`backend/`** — the relay: Node, MongoDB via Prisma, Redis. It terminates four WebSocket paths
- (`/api/adapter-ws` for daemons, `/api/web-ws`, `/api/device-ws`, `/api/manager-ws`), signals WebRTC
+- **`desktop/`** — one Flutter package for native desktop and web, with shared product UI
+ and platform adapters. See [web development](../desktop/README.md#web-development).
+- **`backend/`** — the relay: Node, MongoDB via Prisma, Redis. Its WebSocket paths include
+ `/api/adapter-ws` for daemons, `/api/web-ws`, `/api/observer-ws` for private sharing,
+ `/api/device-ws`, and `/api/manager-ws`. It signals WebRTC
and hands out STUN/TURN, and persists machines, agent names and counters. `npm install && npm run
- dev` on `:8085`; [`backend/README.md`](backend/README.md) and `.env.example` for the rest.
+ dev` on `:8085`; [`backend/README.md`](../backend/README.md) and `.env.example` for the rest.
`harness-api.autonomous.ai` is the hosted instance.
- **[harness.autonomous.ai](https://harness.autonomous.ai)** is the download page: it hosts the CLI
installer and the desktop downloads. It is not in this repository.
@@ -77,5 +182,5 @@ and Boss mode routes it. A voice turn can carry a mode — `/goal` runs an instr
Firmware updates travel over the same cable in 16 KB credit windows, offered from the published
metadata and never for a dev build. `harness flash` re-flashes a device from a USB port. The firmware
-is ESP-IDF ≥ 5.5 under [`devices/harness-device/firmware/`](devices/harness-device/firmware/) (`idf.py set-target esp32s3 &&
+is ESP-IDF ≥ 5.5 under [`devices/harness-device/firmware/`](../devices/harness-device/firmware/) (`idf.py set-target esp32s3 &&
idf.py build`); `make device-test` runs the host-side tests with no board attached.
diff --git a/docs/product-direction.md b/docs/product-direction.md
new file mode 100644
index 000000000..1cd421fdc
--- /dev/null
+++ b/docs/product-direction.md
@@ -0,0 +1,366 @@
+# Harness: product thesis and roadmap
+
+Working product thesis, September 27, 2026. This records the framing developed with the
+founder and the product bet it suggests. Roadmap stages remain proposals for the order of
+learning and investment. See the [system diagram and ownership boundaries](architecture.md).
+
+The starting point is the founder's existing daily use: building Harness's desktop, TUI,
+mobile app, and device while doing market research, product planning, and X-post writing in
+agent sessions. That ongoing body of work is the first reference experience for this roadmap.
+
+## The thesis
+
+**Harness is becoming the environment through which a person directs an entire endeavor.**
+
+The founder is already using Harness to build Harness. Software engineering, hardware,
+experience design, research, and communication happen in different sessions under one
+person's direction. These are connected parts of building and bringing one product to users.
+
+The person supplies direction, taste, priorities, and acceptance standards. Agents supply
+execution across disciplines. Desktop, terminal, phone, and device are places where the person
+enters that work: to direct it, inspect it, answer a question, or make something themselves.
+
+The ambitious product promise is: **one person can direct work at the scope of an organization,
+while staying close to what is being made.**
+
+For the founder, that endeavor is Harness. The larger bet is making this way of working
+accessible to people building their own products, studios, research efforts, or businesses.
+The founder's use demonstrates the behavior; the scale of the opportunity remains a bet.
+
+The initial audience remains the [curious technical builder](ideal-users.md): someone already
+using agents, responsible for an outcome, and willing to work across disciplines. Start with
+one person, one project, and one machine. Additional agents, machines, and interfaces should
+become useful as their work grows.
+
+## The coordination opportunity
+
+The breadth of agent capability is already showing up in the founder's day. The opportunity
+is to make that breadth coherent and sustainable as the work grows.
+
+Today, the person carries important connections between sessions:
+
+- Which firmware results are ready to talk about publicly.
+- Which product decisions should apply across desktop, TUI, and mobile.
+- Which work is finished, blocked, superseded, or worth revisiting.
+- Where the relevant conversation lives.
+- What each agent needs to know about what happened elsewhere.
+
+Harness can make these relationships explicit and useful. A firmware result becomes input to
+communication. A product decision has consequences for several interfaces. A release depends
+on work spread across sessions. Each connection should lead back to the relevant work,
+decision, or evidence so the person can inspect and correct it.
+
+The core design principle is: **preserve the attention that creates value; reduce the attention
+spent reconstructing or transporting context.**
+
+Direction, taste, priorities, and quality judgment deserve the person's attention. Repeatedly
+finding a conversation, explaining an accepted decision, checking whether a draft uses current
+facts, and reconciling conflicting versions are opportunities for the environment to help.
+Which responsibilities to delegate remains a choice the person can make and revise.
+
+That gives the roadmap a concrete starting point: observe the coordination the founder performs
+every day, preserve their direct access to the work, and make the repeated connections dependable.
+
+## What the user is buying
+
+The core value is **more useful work completed per hour of human attention**. Three benefits
+make that concrete:
+
+| Benefit | What the person experiences |
+| --- | --- |
+| Capacity | Work advances while they focus elsewhere; several activities can progress within a defined budget. |
+| Capability | Domain tools and review surfaces let them complete work they previously could not confidently do. |
+| Continuity | Their brief, materials, decisions, and results remain coherent across sessions, devices, and revisions. |
+
+The important experience is a loop: describe, build, inspect, decide, revise, use. Terminals,
+models, and remote connections support that loop. A finished artifact must survive outside
+Harness in a usable form, along with the editable source where the domain supports it.
+
+The [earlier product reset](../work/SUPERPOWERS.md) sets a useful bar: real briefs, meaningful
+revisions that preserve approved choices, and exports checked by independent readers.
+Interface polish and a convincing demonstration are insufficient evidence of that value.
+
+## The reference experience is already happening
+
+A read-only inspection of local session metadata and selected user turns on September 27
+found the following examples. This is a sample of the founder's work; session titles identify
+topics and do not by themselves establish that a task succeeded.
+
+| Workstream | Observed session examples |
+| --- | --- |
+| Desktop product and interaction | "Add Harness activity manager"; "Command palette search results" |
+| Mobile | "Mobile app build and deploy" |
+| Physical device | "Deploy latest firmware" |
+| Positioning and communication | "Review repo and plan marketing"; "Draft X post about harness" |
+| Keeping work accessible | "Find harness marketing session"; "Restore lost panes and tabs" |
+
+The founder also identifies TUI development and market research as current workstreams.
+Selected turns show concrete links between these activities: the X-post session develops
+messaging about firmware responsiveness, while the firmware session concerns the physical
+device's interaction with the app. The desktop manager work concerns returning to ongoing
+sessions. A separate session asks why the marketing conversation cannot be found in search.
+
+These observations suggest a bottleneck worth investigating: the person carries context,
+priorities, quality judgment, and connections between workstreams. We should measure which of
+those responsibilities benefit from assistance and which they prefer to perform directly.
+
+An immediate reference journey can use this existing work:
+
+1. Find the firmware work, its measured results, and the related communication session from
+ the intention to announce the device improvement.
+2. Surface the current implementation, checks, and release state, with links to the evidence.
+3. Carry the approved facts into the post draft. An unpublished result remains distinguishable
+ from a released feature.
+4. If a result or release decision changes, identify the affected draft and bring back the
+ relevant decision. Preserve earlier versions and the person's approved wording.
+5. Let the founder review the device, software, and message through the appropriate interfaces,
+ then proceed under the authority they have granted.
+
+Steps involving shared context, impact tracking, and coordinated updates are proposed product
+capabilities. Their value can be evaluated against the founder's actual current process.
+
+Mobile, the device, desktop, and terminal access are parts of this ongoing practice. The product
+should let the person enter at the right level: a quick decision, a specific session, a project,
+or the broader set of work they are directing.
+
+## What is already here
+
+The repository contains more than a terminal manager. It also contains the beginnings of the
+project-level system this proposal needs.
+
+| Foundation | Evidence and boundary |
+| --- | --- |
+| Persistent machine execution and remote access | [Architecture](architecture.md) and [CLI contract](cli.md). Availability still depends on the execution host. |
+| Desktop, mobile, and USB device interfaces | [Desktop](../desktop/README.md), [mobile](../mobile/README.md), and [device firmware](../devices/harness-device/firmware/README.md). Their supported capabilities differ. |
+| Domain packages and interactive viewers | [Package contract](../store/spec/README.md). A package's presence does not establish output quality for arbitrary tasks. |
+| Durable project/task orchestration | [Model](../cli/src/orchestrator/model.ts) and [service](../cli/src/orchestrator/service.ts): dependencies, attempts, delivery state, recovery, and versioned artifact handoffs. |
+| Some real end-to-end project evidence | [Orchestrator verification](plans/2026-09-18-orchestrator-pr-verification.md) and [combinations](orchestrator-combinations.md). Evidence is bounded to the recorded workflows and environment. |
+| Local-first onboarding requirement | [Development notes](development.md#account-free-local-use). Account-free local startup remains outstanding. |
+
+The next step is to integrate and strengthen these pieces around the founder's daily experience.
+The current orchestrator's local runs are a foundation for that work. Reliable cross-machine
+project execution and continuing project memory require additional design and validation.
+
+## The architectural center: work across sessions
+
+A continuing endeavor can contain several projects, and each project can contain many sessions.
+Preserve that relationship alongside the existing ability to work directly in a session. A
+project should retain the intention and evidence while individual agent runs come and go.
+The proposed product model is:
+
+```text
+ENDEAVOR: for example, building and bringing Harness to users
+ |
+ +-- Related projects: desktop, mobile, device, research, communication
+ +-- Shared decisions and references, with explicit scope and provenance
+ +-- Dependencies, current priorities, and decisions needing the person
+
+PROJECT
+ |
+ +-- Brief: desired outcome, constraints, acceptance criteria
+ +-- Materials: source files, references, installed capabilities
+ +-- Decisions: approved choices, pending questions, rationale
+ +-- Plan: tasks and dependencies, revised as work develops
+ +-- Runs: engine, machine, attempt, status, cost, delivery receipt
+ +-- Artifacts: versions, provenance, dependencies, editable source
+ +-- Evidence: checks, findings, user review, acceptance
+ +-- Authority: permitted actions, budgets, stopping conditions
+```
+
+This extends existing task and artifact records. It does not require a new distributed service
+for the first version. Keep one authoritative owner for a project and clear references to the
+machines executing its tasks. Introduce distributed coordination when a real workflow needs it.
+
+Several boundaries matter as the product grows:
+
+- **Execution outlives views.** Clients can reconnect, rebuild their view from authoritative
+ state, and resolve uncertain requests without silently duplicating work.
+- **Decisions outlive conversations.** Approved choices and their provenance remain available
+ outside a model's current context. People can inspect, correct, and remove this memory.
+- **Results carry evidence.** Process exit, a quiet terminal, and an agent's success message
+ are observations. Completion depends on the project's actual acceptance criteria.
+- **Revisions preserve lineage.** A changed upstream artifact identifies downstream results
+ that need review or rebuilding. Accepted outputs retain their original versions.
+- **Capabilities can be replaced.** Work records and artifact contracts should survive a
+ change of engine. Vendor sessions retain their own resume limits; fresh runs can receive
+ explicit handoffs without pretending their internal contexts are interchangeable.
+- **Autonomy has a scope.** Budgets, permitted actions, and escalation conditions belong to
+ the work. Repeated low-impact operations can proceed under previously granted authority.
+
+Shared context should carry relevant, attributable facts and decisions between related work.
+Its scope must be inspectable and editable; unrelated sessions should retain their boundaries.
+The work model can connect existing sessions without forcing every activity through a director
+agent or converting all ongoing work into a predetermined pipeline.
+
+The daemon remains the execution foundation. The desktop remains the main workbench. CLI and
+TUI expose operations to terminal users and automation. Mobile and the device reduce delays
+at decision points. Web now reuses the desktop Flutter workspace through browser-specific
+transport, sign-in, and storage adapters. Publicly viewable shared work remains its growth
+hypothesis: people discover Harness through a real session and start using it themselves.
+The backend carries identity, reachability, and agreed shared metadata; private project content
+requires an explicit storage and encryption design before adding cloud synchronization.
+
+## Web: shared sessions as an acquisition loop
+
+**Implementation decision, September 27, 2026:** build web and desktop from the same
+Flutter package in `desktop/`, sharing the screens, state, and terminal renderer.
+The browser target is live as a public preview at
+[harness.autonomous.ai](https://harness.autonomous.ai), with authenticated machine access and existing
+private invitations. Public publishing is a separate next
+step requiring the review, snapshot storage, and acquisition flow described below.
+
+The founder identified a concrete growth hypothesis: someone shares a Harness session on X,
+other people open the link to see the work, and some download Harness to do work of their own.
+Each shared session can become a demonstration created through actual product use.
+
+```text
+Do useful work in Harness
+ |
+ v
+Share a session link on X or elsewhere
+ |
+ v
+Someone opens it and sees the work and result
+ |
+ v
+They download Harness and complete their first useful project
+ |
+ v
+Some share their own work, beginning the loop again
+```
+
+This gives web a distinct purpose alongside desktop and mobile: discovery through someone
+else's work. The shared page should help a new visitor understand what the person wanted,
+what the agent did, what was produced, and how they could try something similar.
+
+Extend the existing Share action so its recipient can open the work in a browser.
+The original recipient flow opens another Harness app. The acquisition path becomes:
+
+```text
+Existing: Share -> recipient opens Harness app -> views the session
+Proposed: Share -> recipient opens browser -> views the work -> downloads Harness
+```
+
+The first experiment adds a browser destination and a public-link option to that existing flow:
+
+- Open without an account or app installation; work well in a phone browser reached from X.
+- Lead with the result and a short brief. Let the visitor inspect selected conversation turns,
+ relevant actions, and available output in more detail.
+- Provide a useful title and image for the link preview and a clear Download Harness action.
+- Preserve the originating example through installation where feasible, so the person has a
+ concrete starting point. A later "Make something like this" action could prepare a new project
+ from an explicitly published brief or template using the new user's own files and accounts.
+- Keep the page useful after the creator closes the app or their machine goes offline.
+
+The smallest version can publish a reviewed snapshot of selected session content and artifacts.
+Recorded playback and live viewing can extend it. The author chooses and previews what becomes
+public and can unpublish the page; subsequent private session activity is not added automatically.
+Published snapshots need storage and delivery independent of the execution machine.
+
+The [existing sharing implementation](plans/2026-09-17-002-share-harness-plan.md) already provides
+account-bound invitations and live, view-only observation in the recipient's app. A browser
+viewer can reuse the supported private sharing protocol. The acquisition experience additionally
+needs a public-link mode for people arriving from X; rendering the current invitations in a
+browser alone would still require recipient access. Public snapshots and installation handoff
+are further additions to this foundation. A public snapshot page exposes the selected published
+work, with no terminal input or access to the creator's machine.
+
+Measure the funnel separately: unique human visitors, download clicks, confirmed first launches,
+first useful projects, return use, and subsequent sharing. Link-preview crawlers should not count
+as interested visitors. Where a visitor can voluntarily carry the shared example into the app,
+use its share identifier to connect discovery with activation. Conversion rates are unknown;
+the experiment should establish them and the cost of serving each successful acquisition.
+
+This bounded acquisition experiment can run alongside improvements to the founder's daily work.
+Start with a few author-approved sessions worth sharing, and expand the web product based on
+whether visitors become users who do useful work and return.
+
+## Where a lasting advantage could accumulate
+
+Persistent agents and orchestration already attract investment elsewhere. Anthropic describes
+a hosted runtime separating durable sessions, agent execution, and environments in its
+[Managed Agents architecture](https://www.anthropic.com/engineering/managed-agents), published
+April 8, 2026. Its March 24, 2026
+[application-development research](https://www.anthropic.com/engineering/harness-design-long-running-apps)
+also examines planners, generators, evaluators, and structured handoffs. These are primary
+accounts of that vendor's systems, not an exhaustive market comparison.
+
+Our strategic inference: execution infrastructure needs to be excellent, and differentiation
+must also come from the experience and capabilities built around it. The assets worth growing
+are:
+
+- A project history that preserves the user's materials, judgment, and working conventions.
+- Domain packages that reliably produce useful, editable artifacts and explain their checks.
+- Review interactions that make a new discipline understandable to a technical builder.
+- Repeatable ways to compose capabilities, revise their outputs, and preserve consistency.
+- An author community whose packages work on other people's machines and improve through use.
+
+As engines improve, re-evaluate orchestration complexity against a direct single-agent baseline.
+The product should benefit from better models and retain only the machinery that earns its cost.
+Project ownership, real tools, review, and continuity should remain useful through those changes.
+
+## Roadmap: earn each increase in scope
+
+These stages describe user capabilities. Some foundations already exist; each stage includes
+integration and proof as well as missing implementation. Later stages depend on earlier evidence.
+
+| Stage | Promise to the user | Main work | Evidence required to expand |
+| --- | --- | --- | --- |
+| 1. Make returning to work dependable | "I can return to any piece of work and see what needs me." | Search across real sessions, reliable restore/resume/reconnect, clear execution and delivery state, consistent decisions across clients, and account-free local use. | The founder can recover the actual engineering and marketing sessions they seek; restart and uncertain-request exercises preserve work without duplication. |
+| 2. Carry decisions across related work | "Related work knows the facts and decisions it needs." | Connect existing sessions to projects, preserve approved decisions and references, show their provenance, and make shared context inspectable and editable. | A real product decision reaches the relevant mobile, desktop, device, or communication work with less repeated explanation and no loss of user control. |
+| 3. Understand consequences across sessions | "A change tells me what else needs attention." | Versioned handoffs, release-aware communication, downstream staleness, a decision inbox, and selective updates across a few real workstreams. | The firmware-to-post journey or another observed dependency stays consistent through a revision, with less manual coordination than the baseline. |
+| 4. Delegate longer spans of responsibility | "This work advances and recurs within my instructions." | Build on the existing orchestrator with acceptance evidence, budget visibility, failure recovery, recurring work, and scoped authority. | The founder entrusts bounded outcomes and recurring work for weeks; corrections, exceptions, cost, and unwanted activity remain manageable. |
+| 5. Make this way of working repeatable for others | "I can bring my own endeavor and add the capabilities I need." | Onboarding for adjacent users, reusable project practices, domain packages, authoring assistance, reproducible environments, and richer collaboration where demanded. | Other people obtain similar value on their own projects, and outside authors deliver capabilities that work beyond their machines. |
+
+Hardware can improve the attention loop throughout these stages. Develop its status, decision,
+and voice experience alongside frequent users. Broader hardware ambitions should follow evidence
+that a dedicated physical interface changes their daily work. The present USB device remains a
+companion to a host that runs the daemon.
+
+## The next 30 days, proposed
+
+Use the founder's ongoing work as the first reference environment. Observe real sessions and
+decisions with their permission; keep personal transcripts and credentials out of published
+examples. Establish a baseline for finding work, repeating context, coordinating changes, and
+reviewing results. Further customer research should test how this practice generalizes.
+
+| Period | Concrete output |
+| --- | --- |
+| Week 1 | Map the founder's real workstreams and recurring coordination. Reproduce failures to find or restore sessions. Select one observed dependency, such as firmware results feeding an X-post draft. |
+| Week 2 | Fix the most consequential continuity gaps and add an inspectable way to associate the relevant sessions, decisions, and evidence. |
+| Week 3 | Carry one real change through those sessions, including review and revision. Measure repeated explanation, navigation, stale facts, and human effort against the baseline. |
+| Week 4 | Observe whether the founder keeps using that connection. Test the same experience with a few adjacent users on their own projects, and separate founder-specific preferences from general needs. |
+
+Run this as one effort to improve actual daily work. Ongoing desktop, TUI, mobile, and device
+development can exercise the same model and contract. Prioritize each surface by the coordination
+or interaction it improves. Test the bounded web-sharing acquisition loop with work this effort
+produces. Broader web functionality and domain expansion should follow observed demand and a
+clear role in the experience.
+
+## Measures and decisions
+
+The main outcome measure is useful, accepted work advanced or completed per person per week.
+Read it alongside time spent finding work, repeating context, coordinating changes, and reviewing
+results, plus cost, revision effort, recovery incidents, and retained use. Compare similar job
+types and quality criteria; splitting a project into small outputs must not inflate success.
+
+Track requests that fail or are abandoned as part of the denominator. Record why a result was
+rejected. A deliverable being used outside Harness is stronger evidence than its viewer being
+opened. Agent counts, token volume, and catalog size describe activity and capacity.
+
+Three questions should remain open until real use answers them:
+
+1. Which recurring coordination is the founder doing personally, and which parts should Harness
+ assist with? Distinguish valuable human judgment from avoidable repetition.
+2. Do shared decisions and explicit dependencies reduce stale work and revision effort across
+ the actual sessions, without making direct work harder?
+3. Which benefits transfer to other people directing their own endeavors, and which interface
+ helps them realize those benefits?
+
+A business hypothesis to test after repeat use: open local software and an open package format
+can support paid hosted execution, collaboration, and device sales. Validate willingness to pay
+for each convenience separately. Sustainable economics require useful outcomes after accounting
+for model, compute, support, and hardware costs.
+
+The decision for this proposal is to organize Harness around the continuing work a person is
+already directing: its intentions, relationships, progress, decisions, and usable results.