The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
refactor(mobile): drop the CLI sign-in, the browser sign-in and the CLI runner
deea1b06c3a19ab
diff --git a/mobile/lib/app_shell.dart b/mobile/lib/app_shell.dartindex 8920f1712..82753003b 100644--- a/mobile/lib/app_shell.dart+++ b/mobile/lib/app_shell.dart@@ -220,14 +220,8 @@ class RootShell extends ConsumerWidget {// signed-out screen, which carries the wait as a state of its own// button; swapping the window for a separate screen there was a// hard cut in the middle of a flow, and it is why that button's- // spinner was almost never seen.- //- // ⚠️ Keyed on `signingIn`, NOT on `pendingAuthorizeUrl`. The URL- // only exists for the middle stretch of the flow — the CLI has to- // start before it can print one, and it is cleared again while- // the post-login restore is still running — so keying on it blew- // the user's own screen away twice per sign-in: once on the click- // and again on success.+ // spinner was almost never seen. Keyed on `signingIn`, which spans+ // the whole of it — see [AppNotifier.signingIn].AppStatus.bootstrapping =>app.signingIn ? signedOutScreen(app) : bootScreen(app),AppStatus.unauthenticated => signedOutScreen(app),diff --git a/mobile/lib/auth/cli_link.dart b/mobile/lib/auth/cli_link.dartindex bdf6c40e4..54e876213 100644--- a/mobile/lib/auth/cli_link.dart+++ b/mobile/lib/auth/cli_link.dart@@ -1,40 +1,3 @@-import 'dart:convert';-import 'dart:io';--import '../core/harness_cli_runner.dart';-import 'peer_link_client.dart';--/// Result of `harness remote-password set --stdin --json` — sets (or replaces) this machine's-/// persistent remote password, the shared secret another machine's `harness link connect` PAKE-/// handshake authenticates against. The app never sees the password's cryptographic use, only-/// pipes it to the CLI on stdin, the same as typing it at a terminal prompt would.-class RemotePasswordSetResult {- /// Null on success.- final String? error;-- /// This machine's fingerprint after the password is set — shown so the user can verify it- /// matches on the connecting side.- final String? fingerprint;-- const RemotePasswordSetResult({this.error, this.fingerprint});-}--/// Result of `harness remote-password status --json`.-class RemotePasswordStatus {- /// Null on success. A query failure, not "no password set" — that's [hasPassword] false.- final String? error;- final bool hasPassword;- final String? fingerprint;- final DateTime? setAt;-- const RemotePasswordStatus({- this.error,- this.hasPassword = false,- this.fingerprint,- this.setAt,- });-}-/// Result of `harness link connect <machineId> --stdin --json` — the password-authenticated/// replacement for the old token-based `import`.class CliLinkConnectResult {@@ -77,299 +40,3 @@ class CliLinkListResult {const CliLinkListResult({this.error, this.machines = const []});}--class CliLink implements PeerLinkClient {- final HarnessCliRunner _runner;-- CliLink({HarnessCliRunner? runner}) : _runner = runner ?? HarnessCliRunner();- static final _listRowPattern = RegExp(- r'^\s*\d+\.\s+(\S+)\s+(\S+)\s+\(linked\s+([\d-]+\s[\d:]+)\)',- multiLine: true,- );-- /// Sets (or replaces) this machine's persistent remote password. Stays valid until changed —- /// there is no expiry, unlike the old 7-day link tokens.- Future<RemotePasswordSetResult> setRemotePassword(String password) async {- final invocation = await _runStdinNdjson(- ['remote-password', 'set', '--stdin', '--json'],- password,- label: 'harness remote-password set',- );- if (invocation.error != null) {- return RemotePasswordSetResult(error: invocation.error);- }- final json = invocation.result!;- if (json['ok'] == true) {- return RemotePasswordSetResult(- fingerprint: json['fingerprint'] as String?,- );- }- return RemotePasswordSetResult(- error: json['error'] as String? ?? 'harness remote-password set failed',- );- }-- /// Whether this machine currently has a remote password set, and its fingerprint/set time.- Future<RemotePasswordStatus> remotePasswordStatus() async {- final invocation = await _runJson([- 'remote-password',- 'status',- '--json',- ], label: 'harness remote-password status');- if (invocation.error != null) {- return RemotePasswordStatus(error: invocation.error);- }- final json = invocation.result!;- final setAtMs = json['setAt'];- return RemotePasswordStatus(- hasPassword: json['hasPassword'] == true,- fingerprint: json['fingerprint'] as String?,- setAt: setAtMs is num- ? DateTime.fromMillisecondsSinceEpoch(setAtMs.toInt())- : null,- );- }-- /// Clears this machine's remote password, revoking remote access for anyone who knew it. Null- /// on success.- Future<String?> clearRemotePassword() async {- final invocation = await _runJson([- 'remote-password',- 'clear',- '--json',- ], label: 'harness remote-password clear');- if (invocation.error != null) return invocation.error;- final json = invocation.result!;- if (json['ok'] == true) return null;- return json['error'] as String? ?? 'harness remote-password clear failed';- }-- /// Connects to [machineId] using the password set with `setRemotePassword` on THAT machine —- /// the password-authenticated replacement for the old token `import`. [onProgress], if given,- /// is called with each stage name the CLI reports (`connecting`, `deriving_key`, `exchanging`,- /// `verifying`) as the handshake proceeds; best-effort UI feedback only, never required for- /// correctness. [displayName], when given, is how the CLI's error messages name the machine —- /// otherwise they show the raw [machineId], which is all a terminal user would have.- /// The desktop is the side that SHOWS the code; it never scans one.- @override- Future<CliLinkConnectResult> connectWithCode(- String machineId,- String code, {- required String label,- String? displayName,- }) async => const CliLinkConnectResult(- error: 'Pairing by code is done from the phone.',- );-- @override- Future<CliLinkConnectResult> connect(- String machineId,- String password, {- void Function(String stage)? onProgress,- String? displayName,- String? label,- }) async {- final invocation = await _runStdinNdjson(- [- 'link',- 'connect',- machineId,- '--stdin',- '--json',- if (displayName != null && displayName.isNotEmpty)- '--name=$displayName',- ],- password,- label: 'harness link connect',- onLine: (json) {- final stage = json['stage'];- if (stage is String) onProgress?.call(stage);- },- );- if (invocation.error != null) {- return CliLinkConnectResult(error: invocation.error);- }- final json = invocation.result!;- if (json['ok'] == true) {- return CliLinkConnectResult(- linkedMachineId: json['machineId'] as String? ?? machineId,- fingerprint: json['fingerprint'] as String?,- );- }- // `message` is the CLI's human sentence for the code (what it prints without --json); `error`- // is the bare code and only a fallback for a CLI too old to send one.- return CliLinkConnectResult(- error:- json['message'] as String? ??- json['error'] as String? ??- 'harness link connect failed',- );- }-- /// Machines this one currently trusts (CLI-to-CLI, not the browser-pairing list).- @override- Future<CliLinkListResult> list() async {- final response = await _run(['link', 'list']);- if (response.error != null) {- return CliLinkListResult(error: response.error);- }- final result = response.result!;- final stdoutText = (result.stdout as String).trim();- if (result.exitCode != 0) {- return CliLinkListResult(- error: _errorMessage(result, stdoutText, 'harness link list'),- );- }- return CliLinkListResult(- machines: [- for (final m in _listRowPattern.allMatches(stdoutText))- LinkedMachine(- machineId: m.group(1)!,- fingerprint: m.group(2)!,- linkedAt: m.group(3)!,- ),- ],- );- }-- /// Removes a linked machine's trust pin. Null on success.- @override- Future<String?> unlink(String machineId) async {- final response = await _run(['link', 'unlink', machineId]);- if (response.error != null) return response.error;- final result = response.result!;- if (result.exitCode == 0) return null;- return _errorMessage(- result,- (result.stdout as String).trim(),- 'harness link unlink',- );- }-- String _errorMessage(- ProcessResult result,- String stdoutText,- String command,- ) {- final stderrText = (result.stderr as String).trim();- final message = stderrText.isNotEmpty ? stderrText : stdoutText;- return message.isEmpty- ? '$command failed (exit ${result.exitCode})'- : message;- }-- Future<_CliInvocation> _run(List<String> arguments) async {- try {- return _CliInvocation(result: await _runner.run(arguments));- } on ProcessException catch (error) {- return _CliInvocation(- error: 'Could not run the Harness CLI: ${error.message}',- );- }- }-- /// One-shot NDJSON invocation (no stdin) — spawns [arguments], runs to completion, and returns- /// the last valid JSON line decoded (a one-shot `--json` command prints exactly one such line —- /// `{"ok":true,...}` / `{"ok":false,"error":...}`, or a bare status object with no `ok` key for- /// commands like `remote-password status` that always succeed if they ran at all), or an error- /// if the CLI could not be run or never produced a JSON line.- Future<_ResultInvocation> _runJson(- List<String> arguments, {- required String label,- }) async {- final response = await _run(arguments);- if (response.error != null) return _ResultInvocation(error: response.error);- final result = response.result!;- final stdoutText = result.stdout as String;- Map<String, dynamic>? resultJson;- for (final raw in stdoutText.split('\n')) {- final line = raw.trim();- if (line.isEmpty) continue;- Map<String, dynamic> json;- try {- json = jsonDecode(line) as Map<String, dynamic>;- } catch (_) {- continue;- }- resultJson = json;- }- if (resultJson == null) {- return _ResultInvocation(- error: _errorMessage(result, stdoutText.trim(), label),- );- }- return _ResultInvocation(result: resultJson);- }-- /// Streaming NDJSON invocation with piped stdin — spawns [arguments], writes [stdinLine]- /// followed by a newline, closes stdin, then streams NDJSON off stdout: a line carrying a- /// `stage` key is a progress event and goes to [onLine]; every other valid JSON line is a- /// candidate final result (the last one wins — `link connect`/`remote-password set` print- /// exactly one such line, `{"ok":true,...}` or `{"ok":false,"error":...}`). Mirrors- /// `CliLogin.login()`'s NDJSON-over-stdout parsing style, plus the stdin write this app's other- /// CLI invocations don't need.- Future<_ResultInvocation> _runStdinNdjson(- List<String> arguments,- String stdinLine, {- required String label,- void Function(Map<String, dynamic> json)? onLine,- }) async {- final Process process;- try {- process = await _runner.start(arguments);- } on ProcessException catch (error) {- return _ResultInvocation(- error: 'Could not run the Harness CLI: ${error.message}',- );- }- // Drained unconditionally: an unread stderr pipe can fill its OS buffer and block the child- // process from writing more output at all, which would otherwise look exactly like a hang.- process.stderr.drain<void>();- process.stdin.writeln(stdinLine);- await process.stdin.close();- Map<String, dynamic>? resultJson;- final lines = process.stdout- .transform(utf8.decoder)- .transform(const LineSplitter());- await for (final raw in lines) {- final line = raw.trim();- if (line.isEmpty) continue;- Map<String, dynamic> json;- try {- json = jsonDecode(line) as Map<String, dynamic>;- } catch (_) {- continue;- }- if (json.containsKey('stage')) {- onLine?.call(json);- } else {- resultJson = json;- }- }- final exitCode = await process.exitCode;- if (resultJson == null) {- return _ResultInvocation(- error: exitCode != 0- ? '$label failed (exit $exitCode)'- : '$label produced no result',- );- }- return _ResultInvocation(result: resultJson);- }-}--class _CliInvocation {- final ProcessResult? result;- final String? error;-- const _CliInvocation({this.result, this.error})- : assert((result == null) != (error == null));-}--class _ResultInvocation {- final Map<String, dynamic>? result;- final String? error;-- const _ResultInvocation({this.result, this.error})- : assert((result == null) != (error == null));-}diff --git a/mobile/lib/auth/cli_login.dart b/mobile/lib/auth/cli_login.dartindex 7f6fdbc82..4ab0dfadb 100644--- a/mobile/lib/auth/cli_login.dart+++ b/mobile/lib/auth/cli_login.dart@@ -1,168 +1,7 @@-import 'dart:async';-import 'dart:convert';-import 'dart:io';--import '../core/harness_cli_runner.dart';-import 'sign_in_client.dart';-+/// Whether the app is signed in, as [SignInClient.checkStatus] answers it — the shape the harness+/// CLI's `auth status --json` gives a desktop build, kept by the phone for its own session.class CliAuthStatus {final bool loggedIn;- final String? computerId;- final String? machineId;- final String? autonomousEnv;-- const CliAuthStatus({- required this.loggedIn,- this.computerId,- this.machineId,- this.autonomousEnv,- });-- factory CliAuthStatus.fromJson(Map<String, dynamic> json) => CliAuthStatus(- loggedIn: json['loggedIn'] == true,- computerId: json['computerId'] as String?,- machineId: json['machineId'] as String?,- autonomousEnv: json['autonomousEnv'] as String?,- );-}--/// Thrown when the `harness` CLI itself could not be run at all (the managed-/// runtime, installed launcher, and PATH are all unavailable) — distinct from-/// the CLI running fine and reporting "not signed in".-class CliNotAvailableException implements Exception {- final String message;- CliNotAvailableException(this.message);- @override- String toString() => message;-}--/// Talks to the local `harness` CLI for everything auth-related: whether this computer already has a-/// signed-in session, and driving `harness login --json`'s NDJSON event stream when it does not. The-/// CLI owns the SSO session end to end (`~/.harness/auth/session.json`) — this app never sees, stores,-/// or refreshes an access token itself.-class CliLogin implements SignInClient {- final HarnessCliRunner _runner;- Process? _activeProcess;- int _loginRevision = 0;-- CliLogin({HarnessCliRunner? runner}) : _runner = runner ?? HarnessCliRunner();-- @override- Future<CliAuthStatus> checkStatus() async {- final result = await _run(['auth', 'status', '--json']);- final line = _lastNonEmptyLine(result.stdout as String);- if (line == null) {- throw CliNotAvailableException(- 'Could not run the harness CLI (${(result.stderr as String).trim().isEmpty ? 'exit ${result.exitCode}' : (result.stderr as String).trim()}). '- 'Make sure it is installed and try again.',- );- }- return CliAuthStatus.fromJson(jsonDecode(line) as Map<String, dynamic>);- }-- /// Runs `harness login --force --json`. This is only ever reached from the desktop's `LoginScreen`, i.e. the app- /// has already decided this computer is signed out — so a stale-but-present session file on disk- /// must not short-circuit into a silent refresh attempt (`loginCommand`'s `readAuthSession() &&- /// !force` branch), which just re-reports the same failure forever instead of opening a fresh SSO- /// flow. Calls [onAuthorizeUrl] as soon as the CLI reports the SSO page to show, then resolves once- /// the CLI's own loopback callback server completes the flow (or throws on failure/cancellation).- /// The process is killed if [cancel] is called while this is in flight.- @override- Future<void> login({- required void Function(String url) onAuthorizeUrl,- }) async {- // A cancelled spawn can finish after a replacement login has started.- // Each process owns only its attempt, including its eventual cleanup.- final revision = ++_loginRevision;- final Process process;- try {- process = await _runner.start(['login', '--force', '--json']);- } catch (error) {- throw CliNotAvailableException('Could not run the harness CLI: $error');- }- if (revision != _loginRevision) {- unawaited(process.stdout.drain<void>());- unawaited(process.stderr.drain<void>());- process.kill();- throw StateError('Sign-in was cancelled.');- }- _activeProcess = process;- // Drained unconditionally: an unread stderr pipe can fill its OS buffer and block the child- // process from writing more output at all, which would otherwise look exactly like a hang here.- process.stderr.drain<void>();- try {- final lines = process.stdout- .transform(utf8.decoder)- .transform(const LineSplitter());- var gotResult = false;- var success = false;- String? message;- await for (final raw in lines) {- if (revision != _loginRevision) continue;- final line = raw.trim();- if (line.isEmpty) continue;- Map<String, dynamic> json;- try {- json = jsonDecode(line) as Map<String, dynamic>;- } catch (_) {- continue;- }- switch (json['type']) {- case 'authorize_url':- final url = json['url'];- if (url is String) onAuthorizeUrl(url);- case 'result':- gotResult = true;- success = json['status'] == 'success';- message = json['message'] as String?;- }- }- final exitCode = await process.exitCode;- if (revision != _loginRevision) {- throw StateError('Sign-in was cancelled.');- }- if (!gotResult || !success) {- throw StateError(- message ??- (exitCode != 0- ? 'Sign-in was cancelled.'- : 'Sign-in did not complete.'),- );- }- } finally {- if (identical(_activeProcess, process)) _activeProcess = null;- }- }-- /// Aborts this attempt even if its process has not finished starting yet —- /// reached from the embedded sign-in webview's close button.- @override- void cancel() {- ++_loginRevision;- final process = _activeProcess;- _activeProcess = null;- process?.kill();- }-- @override- Future<void> logout() async {- try {- await _run(['logout']);- } catch (_) {- // Best-effort: local app state is cleared regardless by the caller.- }- }-- Future<ProcessResult> _run(List<String> arguments) async {- try {- return await _runner.run(arguments);- } catch (error) {- throw CliNotAvailableException('Could not run the harness CLI: $error');- }- }- String? _lastNonEmptyLine(String stdout) {- final lines = stdout.trim().split('\n').where((l) => l.trim().isNotEmpty);- return lines.isEmpty ? null : lines.last.trim();- }+ const CliAuthStatus({required this.loggedIn});}diff --git a/mobile/lib/auth/peer_link_client.dart b/mobile/lib/auth/peer_link_client.dartindex b45c08be1..734107804 100644--- a/mobile/lib/auth/peer_link_client.dart+++ b/mobile/lib/auth/peer_link_client.dart@@ -1,8 +1,7 @@import 'cli_link.dart';-/// Linking to another machine by its remote password: `harness link connect/list/unlink` through-/// [CliLink], or the same exchange run by the app itself in a viewer build-/// (`viewer/direct_link.dart`).+/// Linking to another machine by its remote password: the exchange `harness link+/// connect/list/unlink` runs on a desktop, run by the app itself (`viewer/direct_link.dart`).abstract interface class PeerLinkClient {/// [onProgress] gets the CLI's stage names (`connecting`, `deriving_key`, `exchanging`,/// `verifying`) — best-effort feedback, never needed for correctness. [displayName] is how andiff --git a/mobile/lib/auth/sign_in_client.dart b/mobile/lib/auth/sign_in_client.dartindex 70c80835c..030cca8be 100644--- a/mobile/lib/auth/sign_in_client.dart+++ b/mobile/lib/auth/sign_in_client.dart@@ -1,16 +1,13 @@import 'cli_login.dart';-/// Whether the app is signed in, and how it signs in — the seam between the two kinds of build.+/// Whether the app is signed in, and signing it out — the seam the notifier reads the session+/// through.///-/// [CliLogin] asks the local harness CLI, which holds the session. A viewer build has no CLI and-/// holds its own (`viewer/direct_login.dart`).+/// The phone holds its own session (`viewer/direct_login.dart`); a desktop build asks the local+/// harness CLI instead, which holds it there. How a phone signs IN is not here: an emailed code or+/// a scanned one (`viewer/email_code_login.dart`), which no CLI build has.abstract interface class SignInClient {Future<CliAuthStatus> checkStatus();- /// Resolves once signed in; throws on failure or [cancel]. [onAuthorizeUrl] gets the SSO page.- Future<void> login({required void Function(String url) onAuthorizeUrl});-- void cancel();-Future<void> logout();}diff --git a/mobile/lib/core/harness_cli_runner.dart b/mobile/lib/core/harness_cli_runner.dartdeleted file mode 100644index 0cbc18d69..000000000--- a/mobile/lib/core/harness_cli_runner.dart+++ /dev/null@@ -1,214 +0,0 @@-import 'host_platform.dart';-import 'dart:io';--import '../logging/cli_transcript.dart';--/// Runs the Harness CLI owned by this desktop app without depending on a-/// terminal shell, its rc files, or Finder's inherited PATH.-///-/// The normal path is the managed tier: `~/.harness/runtime/current-node` — a-/// private, checksum-verified Node that the `harness` installer provisions and-/// records — paired with the `~/.harness/cli/cli.js` bundle,-/// invoked as `<node> <cli.js> …` with no shell in between. Because both are-/// absolute paths beneath [harnessHome], launching Harness from Finder and from-/// Terminal have identical runtime behavior; PATH never enters into it.-///-/// Behind that come the installed `~/.local/bin/harness` launcher and finally-/// bare `harness` on PATH, which cover a developer-managed install and the-/// window before the first provisioning run has finished.-class HarnessCliRunner {- final Directory harnessHome;- final Map<String, String> environment;- final Future<ProcessResult> Function(- String executable,- List<String> arguments, {- Map<String, String>? environment,- })- _runProcess;- final Future<Process> Function(- String executable,- List<String> arguments, {- Map<String, String>? environment,- })- _startProcess;-- HarnessCliRunner({- Directory? harnessHome,- Map<String, String>? environment,- Future<ProcessResult> Function(- String executable,- List<String> arguments, {- Map<String, String>? environment,- })?- runProcess,- Future<Process> Function(- String executable,- List<String> arguments, {- Map<String, String>? environment,- })?- startProcess,- }) : environment = environment ?? Platform.environment,- harnessHome = harnessHome ?? Directory(_defaultHarnessHome()),- _runProcess = runProcess ?? Process.run,- _startProcess = startProcess ?? Process.start;-- static String _defaultHarnessHome() {- // HOME, then USERPROFILE: Windows sets only the latter, so a launch from Explorer threw here- // before any UI existed to report it.- final home = Platform.environment['HOME'];- final profile = Platform.environment['USERPROFILE'];- final resolved = home != null && home.isNotEmpty- ? home- : (profile != null && profile.isNotEmpty ? profile : containerHome);- if (resolved == null || resolved.isEmpty) {- throw StateError('Could not resolve the current user home directory');- }- return '$resolved${Platform.pathSeparator}.harness';- }-- Directory get _runtimeDirectory =>- Directory('${harnessHome.path}${Platform.pathSeparator}runtime');-- File get _currentNodeFile =>- File('${_runtimeDirectory.path}${Platform.pathSeparator}current-node');-- File get _cliFile => File(- '${harnessHome.path}${Platform.pathSeparator}cli${Platform.pathSeparator}cli.js',- );-- /// Builds the direct invocation used by [run] and [start]. Public for- /// focused tests and diagnostics; callers should generally call [run].- Future<HarnessCliInvocation> resolve(List<String> arguments) async {- final node = await _managedNode();- if (node != null && await _cliFile.exists()) {- return HarnessCliInvocation(- executable: node.path,- arguments: [_cliFile.path, ...arguments],- environment: _commandEnvironment(),- source: HarnessCliSource.managed,- );- }-- final home = _home();- if (home != null && home.isNotEmpty) {- final launcher = File(- '$home${Platform.pathSeparator}.local${Platform.pathSeparator}bin${Platform.pathSeparator}harness',- );- if (await launcher.exists()) {- return HarnessCliInvocation(- executable: launcher.path,- arguments: arguments,- environment: _commandEnvironment(),- source: HarnessCliSource.launcher,- );- }- }-- return HarnessCliInvocation(- executable: 'harness',- arguments: arguments,- environment: _commandEnvironment(),- source: HarnessCliSource.path,- );- }-- Future<ProcessResult> run(List<String> arguments) async {- final invocation = await resolve(arguments);- return logProcessRun(- _displayLine(arguments),- () => _runProcess(- invocation.executable,- invocation.arguments,- environment: invocation.environment,- ),- );- }-- Future<Process> start(List<String> arguments) async {- final invocation = await resolve(arguments);- return logProcessStart(- _displayLine(arguments),- () => _startProcess(- invocation.executable,- invocation.arguments,- environment: invocation.environment,- ),- );- }-- /// The invocation as a person reads it — `harness auth status --json`.- ///- /// The [arguments] this was asked for, never [HarnessCliInvocation.arguments]:- /// on the managed tier the real argv is `<node> <cli.js> …`, two absolute- /// paths of noise in front of the only part that says what ran.- static String _displayLine(List<String> arguments) =>- 'harness ${arguments.join(' ')}';-- Future<File?> _managedNode() async {- try {- final raw = (await _currentNodeFile.readAsString()).trim();- if (raw.isEmpty) return null;- final runtimeRoot =- '${_runtimeDirectory.absolute.path}${Platform.pathSeparator}';- if (!raw.startsWith(runtimeRoot)) return null;- final node = File(raw);- return await node.exists() ? node : null;- } on FileSystemException {- return null;- }- }-- String? _home() {- final home = environment['HOME'];- if (home != null && home.isNotEmpty) return home;- final profile = environment['USERPROFILE'];- return profile != null && profile.isNotEmpty ? profile : null;- }-- Map<String, String> _commandEnvironment() {- final home = _home();- final launcherDirectory = home == null || home.isEmpty- ? null- : '$home${Platform.pathSeparator}.local${Platform.pathSeparator}bin';- final path = environment['PATH'] ?? '';- // PATH is ';'-separated on Windows. Joining with ':' there does not just fail to prepend the- // launcher directory — it welds it onto the first real entry and destroys that one too.- final pathSeparator = Platform.isWindows ? ';' : ':';- final commandEnvironment = <String, String>{- ...environment,- if (launcherDirectory != null)- 'PATH': path.isEmpty- ? launcherDirectory- : '$launcherDirectory$pathSeparator$path',- };- final configuredLocale =- commandEnvironment['LC_ALL'] ??- commandEnvironment['LC_CTYPE'] ??- commandEnvironment['LANG'];- if ((Platform.isMacOS || Platform.isLinux) &&- (configuredLocale == null ||- !RegExp(- r'utf-?8',- caseSensitive: false,- ).hasMatch(configuredLocale))) {- commandEnvironment['LC_ALL'] = 'C.UTF-8';- }- return commandEnvironment;- }-}--enum HarnessCliSource { managed, launcher, path }--class HarnessCliInvocation {- final String executable;- final List<String> arguments;- final Map<String, String> environment;- final HarnessCliSource source;-- const HarnessCliInvocation({- required this.executable,- required this.arguments,- required this.environment,- required this.source,- });-}diff --git a/mobile/lib/logging/cli_transcript.dart b/mobile/lib/logging/cli_transcript.dartdeleted file mode 100644index 82b8b2a1f..000000000--- a/mobile/lib/logging/cli_transcript.dart+++ /dev/null@@ -1,129 +0,0 @@-/// Records a child process into [cliLog] — the transcript both the daily file-/// and Settings ▸ Debug are built from.-///-/// One place, used by [HarnessCliRunner]: "the CLI did something unexpected"-/// is the most common shape of a fault here, since the app itself holds almost-/// no logic.-///-/// **A command line and its output are logged; its environment is not.** A-/// secret handed to a child belongs in its environment precisely so it stays-/// out of argv, and writing the environment here would undo that. What the-/// child *prints* can still carry one — `harness auth status --json` prints a-/// session — so every line goes through [redactSecretsInText] first.-library;--import 'dart:async';-import 'dart:convert';-import 'dart:io';--import 'cli_log.dart';-import 'redact.dart';--/// Output lines kept per invocation. Enough to see what a command answered,-/// short of pasting a whole `--json` catalogue into the day's log.-const int _maxOutputLines = 40;--/// Longest single line kept. A base64 blob buries the lines either side of it.-const int _maxLineChars = 500;--/// Runs [call] as one logged invocation of [command].-///-/// [command] is the display line — `harness auth status --json` — not the real-/// argv, which for the managed tier is `<node> <cli.js> …` and reads as noise.-Future<ProcessResult> logProcessRun(- String command,- Future<ProcessResult> Function() call,-) async {- final entry = cliLog.begin(redactSecretsInText(command));- final started = DateTime.now();- try {- final result = await call();- _writeOutput(entry, result);- entry.end(- exitCode: result.exitCode,- duration: DateTime.now().difference(started),- );- return result;- } on Object catch (error) {- // A missing binary is a ProcessException, and it is the single most useful- // line this log can hold — so it is recorded before it is rethrown.- entry.end(error: '$error', duration: DateTime.now().difference(started));- rethrow;- }-}--/// Opens a section for a long-running child and closes it when the child exits.-///-/// Its output is not captured: the caller owns those streams (that is why it-/// asked for a [Process]), and a second listener would steal the bytes it is-/// reading. So a streamed command records that it started, and how it ended.-Future<Process> logProcessStart(- String command,- Future<Process> Function() call,-) async {- final entry = cliLog.begin(redactSecretsInText(command));- final started = DateTime.now();- final Process process;- try {- process = await call();- } on Object catch (error) {- entry.end(error: '$error', duration: DateTime.now().difference(started));- rethrow;- }- unawaited(- process.exitCode- .then(- (code) => entry.end(- exitCode: code,- duration: DateTime.now().difference(started),- ),- )- // The child's fate is the caller's business; this listener only reports- // it, so its own failure must not become an unhandled error.- .catchError(- (Object error) => entry.end(- error: '$error',- duration: DateTime.now().difference(started),- ),- ),- );- return process;-}--/// Writes a finished command's stdout and stderr into its section, redacted,-/// clipped, and stderr tagged.-void _writeOutput(CliLogEntry entry, ProcessResult result) {- var budget = _maxOutputLines;- budget = _writeStream(entry, result.stdout, budget, isError: false);- budget = _writeStream(entry, result.stderr, budget, isError: true);-}--int _writeStream(- CliLogEntry entry,- Object? stream,- int budget, {- required bool isError,-}) {- if (budget <= 0) return budget;- final text = stream is String ? stream : '${stream ?? ''}';- final lines = const LineSplitter()- .convert(redactSecretsInText(text))- .where((line) => line.trim().isNotEmpty)- .toList();- for (final line in lines.take(budget)) {- entry.output(- line.length > _maxLineChars- ? '${line.substring(0, _maxLineChars)}…'- : line,- isError: isError,- );- }- final kept = lines.length < budget ? lines.length : budget;- if (lines.length > kept) {- entry.output(- '… ${lines.length - kept} more lines not kept',- isError: isError,- );- }- return budget - kept;-}diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 720654f54..6d3894fcf 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -9,13 +9,11 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';import '../analytics/analytics.dart';import '../api/api_client.dart';import '../viewer/direct_auth_api.dart';-import '../viewer/sign_in_browser.dart';import '../viewer/viewer_services.dart';import '../auth/auth_session.dart';import '../auth/peer_link_client.dart';import '../auth/sign_in_client.dart';import '../auth/cli_link.dart';-import '../auth/cli_login.dart';import '../core/config.dart';import '../core/agent_preference.dart';import '../core/engine_availability.dart';@@ -277,15 +275,12 @@ class AppNotifier extends ChangeNotifier {AppConfig config;late ApiClient api;- /// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,- /// [ViewerServices.login] in a viewer build — which has no CLI — under one name, so every call- /// site reads the same in both.+ /// Says whether this device is signed in, and signs it out: [ViewerServices.login], the app's own+ /// session. The name is the desktop's, where the harness CLI holds the session instead.late final SignInClient cliLogin;- final CliLink cliLink;/// Links to other machines by remote password — the app itself, through [ViewerServices.links].- /// THIS machine's own remote password stays on [cliLink] — a viewer is not a machine, and has no- /// password for anyone to link to.+ /// A viewer is not a machine, so it has no password of its own for anyone to link to.late final PeerLinkClient peerLinks;/// This app's stand-ins for the harness CLI (`lib/viewer/`). It is always a viewer: no CLI runs@@ -390,8 +385,6 @@ class AppNotifier extends ChangeNotifier {!_disposed && revision == _authRevision;int _invalidateAuthWork() {- _resetLoginBrowser();- _loginAuthorized = false;_profileInFlight = null;_retryInFlight = null;machinesLoading = false;@@ -944,28 +937,13 @@ class AppNotifier extends ChangeNotifier {int _nextPaneId = 1;static const maxPanes = 64;- // Set only while `harness login --force --json` is waiting for the user to finish SSO in their system- // browser. It arrives PART WAY THROUGH the flow — the CLI has to start before it can hand one- // over. It identifies the current sign-in link; [signingIn] tracks the whole- // attempt, including CLI startup and workspace restoration.- String? pendingAuthorizeUrl;- bool openingLoginBrowser = false;- String? loginBrowserError;- int _loginBrowserRevision = 0;- bool _loginAuthorized = false;- bool get canCancelLogin => signingIn && !_loginAuthorized;-- /// True from the moment the user presses Sign in until the flow settles, one way or the other.- ///- /// **Not the same question as `pendingAuthorizeUrl != null`, and the difference was a bug.**- /// `login()` flips [status] to `bootstrapping` immediately, but the authorize URL only lands- /// once the CLI has spawned Node and got as far as printing one — seconds later — and it is- /// cleared again in `finally` while `_finishBootstrapSignedIn()` is still restoring panes and- /// fetching machines. `RootShell` keyed the sign-in screen off the URL, so both of those windows- /// dropped the user onto a bare full-screen spinner: the card they were looking at vanished on- /// the click, came back, then vanished again on success.++ /// True from the moment a code is handed in — emailed or scanned — until the flow settles, one+ /// way or the other.///- /// This flag spans the whole flow, so the screen the user pressed a button on stays put.+ /// It spans the whole flow, restoring the tiles and fetching the machines included, so the+ /// screen the user pressed a button on stays put: `RootShell` keeps the signed-out screen up+ /// while it is set, rather than dropping them onto a bare full-screen spinner.bool signingIn = false;AppNotifier({@@ -974,7 +952,6 @@ class AppNotifier extends ChangeNotifier {ConfigStore? configStore,this.connectionForTest,SignInClient? cliLogin,- CliLink? cliLink,PeerLinkClient? peerLinks,ViewerServices? viewer,PaneLayoutStore? paneLayoutStore,@@ -1007,7 +984,6 @@ class AppNotifier extends ChangeNotifier {machineCache ?? (paneLayoutStore == null ? null : MachineCache()),session = authSession,_store = configStore,- cliLink = cliLink ?? CliLink(),config = configStore?.config ?? config,viewer =viewer ??@@ -1300,9 +1276,7 @@ class AppNotifier extends ChangeNotifier {// The boot spinner holds while the sign-in is checked.status = AppStatus.bootstrapping;notifyListeners();- // Auth now lives entirely with the local `harness` CLI — it owns the SSO session on disk and- // refreshes it itself. This app never reads, stores, or refreshes a token of its own; it just- // asks the CLI whether this computer is currently signed in.+ // The session is the app's own (`viewer/direct_auth.dart`): this asks whether one is kept.try {final authStatus = await StartupTrace.time('boot.checkSignIn',@@ -1463,7 +1437,6 @@ class AppNotifier extends ChangeNotifier {_invalidateAuthWork();currentUser = null;signingIn = false;- pendingAuthorizeUrl = null;// The code was scanned into the session that just ended — see [logout].pendingPairing = null;_awaitingFirstMessage = null;@@ -1477,65 +1450,6 @@ class AppNotifier extends ChangeNotifier {notifyListeners();}- Future<void> login() async {- if (_disposed || signingIn) return;- final revision = _invalidateAuthWork();- _closedHistory.clear();- _lastError = null;- status = AppStatus.bootstrapping;- signingIn = true;- pendingAuthorizeUrl = null;- notifyListeners();- try {- await cliLogin.login(- onAuthorizeUrl: (url) {- if (!_authWorkCurrent(revision)) return;- if (pendingAuthorizeUrl == url) return;- _resetLoginBrowser();- pendingAuthorizeUrl = url;- notifyListeners();- // Through [openLoginBrowser] rather than straight to the launcher, so- // the first handoff is the same one the login screen's retry button- // takes and reports its outcome the same way. WHICH browser it opens- // is decided in `viewer/sign_in_browser.dart`.- unawaited(openLoginBrowser());- },- );- if (!_authWorkCurrent(revision)) return;- _loginAuthorized = true;- pendingAuthorizeUrl = null;- _resetLoginBrowser();- notifyListeners();- await _enterSignedIn(revision);- } catch (error) {- if (!_authWorkCurrent(revision)) return;- status = AppStatus.unauthenticated;- _lastError = error.toString();- _lastErrorRetryable = true;- // A short code, never `error.toString()` — a CLI failure carries paths- // and host names, and this stream is not the place for them. Only the- // two the TYPE can tell apart: a cancelled sign-in and a refused one both- // arrive as a `StateError` differing in message text, and matching on- // English sentences is how a stream starts lying after a copy edit.- analytics.signInFailed(- error is CliNotAvailableException ? 'cli_missing' : 'failed',- );- } finally {- // Takes the in-app browser view down once the redirect has landed; a no-op- // where the page opened in a browser of its own.- unawaited(closeSignInPage());- // Cleared last, and only here: everything above may still be running when the URL goes, and- // dropping the flag any earlier is what put a bare spinner over the user's own screen.- if (_authWorkCurrent(revision)) {- _resetLoginBrowser();- _loginAuthorized = false;- pendingAuthorizeUrl = null;- signingIn = false;- }- }- if (_authWorkCurrent(revision)) notifyListeners();- }-/// A session was just saved: load everything behind the login screen, and/// count the sign-in. The one road in for every way of signing in.Future<void> _enterSignedIn(int revision) async {@@ -1625,75 +1539,9 @@ class AppNotifier extends ChangeNotifier {}}- void _resetLoginBrowser() {- ++_loginBrowserRevision;- openingLoginBrowser = false;- loginBrowserError = null;- }-- /// Reopens the current authorization URL without creating another login.- Future<void> openLoginBrowser() async {- final url = pendingAuthorizeUrl;- if (_disposed || !signingIn || url == null || openingLoginBrowser) return;- final authRevision = _authRevision;- final browserRevision = ++_loginBrowserRevision;- openingLoginBrowser = true;- loginBrowserError = null;- notifyListeners();- var opened = false;- try {- final uri = Uri.tryParse(url);- if (uri != null &&- uri.hasAuthority &&- (uri.scheme == 'https' || uri.scheme == 'http')) {- // Not `launchUrl(..., externalApplication)` directly: on a desktop- // [openSignInPage] IS that call, and on a phone it must not be. Handing- // a phone to Safari suspends this app, and with it the loopback listener- // the page redirects back to — the sign-in could then never land.- // ⚠️ The reason the desktop insists on a real browser survives here: this- // SSO page's Google button uses Google's popup-based Identity Services- // flow, where a popup window posts the result back to its opener. Whether- // an in-app browser view can satisfy that is open, and flagged in- // `sign_in_browser.dart`; it is why the phone case is confined to phones- // rather than made the rule.- opened = await openSignInPage(uri);- }- } catch (_) {- // Browser handoff failure is recoverable within the same sign-in. Never- // put a credential-bearing URL or a raw platform exception in the UI.- }- if (!_authWorkCurrent(authRevision) ||- browserRevision != _loginBrowserRevision ||- pendingAuthorizeUrl != url) {- return;- }- openingLoginBrowser = false;- if (!opened) {- loginBrowserError =- 'Couldn’t open your browser. Open it again or copy the sign-in link.';- }- notifyListeners();- }-- /// Return immediately; late URLs, results and browser replies belong to the- /// cancelled attempt and cannot change a subsequent sign-in.- void cancelLogin() {- if (_disposed || !canCancelLogin) return;- _invalidateAuthWork();- signingIn = false;- pendingAuthorizeUrl = null;- status = AppStatus.unauthenticated;- _lastError = null;- _lastErrorRetryable = false;- cliLogin.cancel();- notifyListeners();- }-Future<void> logout() async {final revision = _invalidateAuthWork();- cliLogin.cancel();signingIn = false;- pendingAuthorizeUrl = null;// A scanned code belongs to the session it was scanned into. Held past this,// the next sign-in — perhaps another account's — would spend it on the first// locked machine of that id and show a pairing error where its password form@@ -1701,9 +1549,9 @@ class AppNotifier extends ChangeNotifier {// code is set before that sign-in on purpose (`phone_welcome.dart`).pendingPairing = null;_closedHistory.clear();- // Best-effort and fire-and-forget: local state is cleared below regardless of whether the CLI- // process could be reached, but a real `harness logout` clears its saved session so the NEXT- // launch doesn't silently sign back in without ever showing the login screen.+ // Best-effort and fire-and-forget: local state is cleared below regardless, but the saved+ // session goes too, so the NEXT launch doesn't silently sign back in without ever showing the+ // login screen.unawaited(cliLogin.logout());_stopAllOfflineRetries();_stopAllAgentSyncTimers();@@ -2213,20 +2061,6 @@ class AppNotifier extends ChangeNotifier {bool linkedMachinesLoading = false;String? linkedMachinesError;- /// Sets (or replaces) THIS machine's persistent remote password (`harness remote-password- /// set --stdin --json`) — another machine later connects with `connectWithPassword` using the- /// same password, no token copy/paste involved.- Future<RemotePasswordSetResult> setRemotePassword(String password) =>- cliLink.setRemotePassword(password);-- /// Queries THIS machine's remote-password state (`harness remote-password status --json`).- Future<RemotePasswordStatus> remotePasswordStatus() =>- cliLink.remotePasswordStatus();-- /// Clears THIS machine's remote password (`harness remote-password clear --json`). Returns null- /// on success.- Future<String?> clearRemotePassword() => cliLink.clearRemotePassword();-/// Refreshes the "machines this one trusts" list (`harness link list`).Future<void> refreshLinkedMachines() async {linkedMachinesLoading = true;@@ -5958,7 +5792,6 @@ class AppNotifier extends ChangeNotifier {@overridevoid dispose() {_disposed = true;- if (signingIn) cliLogin.cancel();_closedHistory.clear();_stopAllOfflineRetries();_stopAllAgentSyncTimers();diff --git a/mobile/lib/viewer/direct_auth_api.dart b/mobile/lib/viewer/direct_auth_api.dartindex de35ef19c..bbc60e051 100644--- a/mobile/lib/viewer/direct_auth_api.dart+++ b/mobile/lib/viewer/direct_auth_api.dart@@ -1,6 +1,5 @@import 'package:dio/dio.dart';-import '../api/api_client.dart';import '../core/config.dart';import '../logging/http_log.dart';@@ -17,7 +16,7 @@ class DirectAuthException implements Exception {String toString() => message;}-/// What `/api/auth/exchange` and `/api/auth/refresh` hand back.+/// What `/api/auth/refresh` and `/api/auth/handoff/redeem` hand back.class IssuedTokens {const IssuedTokens({required this.token,@@ -72,43 +71,6 @@ class DirectAuthApi {'Could not renew your sign-in. That is usually the sign-in service having a moment — ''if it keeps happening, sign out and sign in again.';- Future<({String authorizeUrl, String tx})> authorizeNative(- String redirectUri,- ) async {- final data = unwrapApiResponse(- await _dio.post(- '/api/auth/authorize-native',- data: {- 'redirectUri': redirectUri,- 'autonomousEnv': config.autonomousEnv,- },- ),- );- final url = data is Map ? data['authorizeUrl'] : null;- final tx = data is Map ? data['tx'] : null;- if (url is! String || url.isEmpty || tx is! String || tx.isEmpty) {- throw const DirectAuthException(- 'The server did not return a sign-in page.',- );- }- return (authorizeUrl: url, tx: tx);- }-- Future<IssuedTokens> exchange({- required String code,- required String state,- required String tx,- }) async {- final data = unwrapApiResponse(- await _dio.post(- '/api/auth/exchange',- data: {'code': code, 'state': state, 'tx': tx},- ),- );- return IssuedTokens.fromData(data) ??- (throw const DirectAuthException('Sign-in returned no access token.'));- }-/// Trade the one-time code in a signed-in computer's Add Phone QR for a/// session of this phone's own — scan to sign in, no emailed code. [label]/// is what the phone calls itself, for the account's list of devices.diff --git a/mobile/lib/viewer/direct_login.dart b/mobile/lib/viewer/direct_login.dartindex 43a592f1f..8bdebddd9 100644--- a/mobile/lib/viewer/direct_login.dart+++ b/mobile/lib/viewer/direct_login.dart@@ -1,113 +1,22 @@-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.+/// Whether this app is signed in, and signing it out, with no harness CLI to ask — the session is+/// the app's own ([DirectAuth]).///-/// It deliberately skips the CLI's closing `resolve-computer`, which registers the computer as a-/// Harness machine. A viewer is not one.+/// There is no browser sign-in here. The desktop's is cli.ts `loginCommand` — a loopback listener+/// for the SSO redirect — and a phone that hands the person to Safari is suspended along with that+/// listener. A phone signs in with a code instead (`email_code_login.dart`).class DirectLogin implements SignInClient {DirectLogin({required this.auth});final DirectAuth auth;- _LoopbackCallback? _pending;-- static const _callbackTimeout = Duration(minutes: 5);@overrideFuture<CliAuthStatus> checkStatus() async =>CliAuthStatus(loggedIn: await auth.hasSession());- @override- Future<void> login({- required void Function(String url) onAuthorizeUrl,- }) async {- final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);- final callback = _pending = _LoopbackCallback(server);- try {- final start = await auth.api.authorizeNative(- 'http://127.0.0.1:${server.port}/callback',- );- onAuthorizeUrl(start.authorizeUrl);- final redirect = await callback.result.timeout(- _callbackTimeout,- onTimeout: () => throw const DirectAuthException('Sign-in timed out.'),- );- await auth.signIn(- await auth.api.exchange(- code: redirect.code,- state: redirect.state,- tx: start.tx,- ),- );- } finally {- _pending = null;- await server.close(force: true);- }- }-- @override- void cancel() => _pending?.cancel();-@overrideFuture<void> logout() => auth.signOut();}--/// The loopback end of the redirect: the first `/callback` carrying `code` and `state` completes-/// it and an `error` fails it; anything else the browser asks for (a favicon) is turned away.-class _LoopbackCallback {- _LoopbackCallback(HttpServer server) {- server.listen(_onRequest);- }-- final _completer = Completer<({String code, String state})>();-- Future<({String code, String state})> get result => _completer.future;-- Future<void> _onRequest(HttpRequest request) async {- final response = request.response;- if (request.uri.path != '/callback') {- response.statusCode = HttpStatus.notFound;- await response.close();- return;- }- final query = request.uri.queryParameters;- final code = query['code'], state = query['state'], error = query['error'];- final signedIn = error == null && code != null && state != null;- response- ..statusCode = signedIn ? HttpStatus.ok : HttpStatus.badRequest- ..headers.contentType = ContentType.html- ..write(- _page(- signedIn ? 'Signed in to Harness' : 'Harness sign-in failed',- ),- );- await response.close();- if (_completer.isCompleted) return;- if (signedIn) {- _completer.complete((code: code, state: state));- } else {- _completer.completeError(- DirectAuthException('Sign-in failed: ${error ?? 'no code returned'}'),- );- }- }-- void cancel() {- if (_completer.isCompleted) return;- _completer.completeError(- const DirectAuthException('Sign-in was cancelled.'),- );- }-}--String _page(String title) =>- '<!doctype html><meta charset="utf-8"><title>$title</title>'- '<body style="font:16px system-ui,sans-serif;text-align:center;padding:4em 1em">'- '<h1 style="font-weight:600">$title</h1>'- '<p>You can close this window and go back to Harness.</p></body>';diff --git a/mobile/lib/viewer/email_code_api.dart b/mobile/lib/viewer/email_code_api.dartindex 626705f2c..d4049d78d 100644--- a/mobile/lib/viewer/email_code_api.dart+++ b/mobile/lib/viewer/email_code_api.dart@@ -9,8 +9,8 @@ import 'direct_auth_api.dart';/// the app.////// Why a phone signs in this way and not through the browser: the SSO flow redirects back to a-/// loopback listener inside the app (`direct_login.dart`), and a phone is not obliged to keep that-/// listener alive while a browser is in front of it. Google Play's review saw exactly that —+/// loopback listener inside the app (the desktop CLI's `loginCommand`), and a phone is not obliged+/// to keep that listener alive while a browser is in front of it. Google Play's review saw exactly that —/// "127.0.0.1 took too long to respond" — and rejected the build for a sign-in that could not/// finish. A code typed into the app never leaves it.///diff --git a/mobile/lib/viewer/sign_in_browser.dart b/mobile/lib/viewer/sign_in_browser.dartdeleted file mode 100644index 8b760ace7..000000000--- a/mobile/lib/viewer/sign_in_browser.dart+++ /dev/null@@ -1,24 +0,0 @@-import 'dart:io';--import 'package:url_launcher/url_launcher.dart';--/// Where the SSO page opens: the system browser, as it always has — except on a phone.-///-/// There, handing the person to Safari or Chrome suspends this app and with it the loopback-/// listener the page redirects back to, so the page opens in-app (SFSafariViewController on iOS,-/// a Custom Tab on Android), where the app keeps running, and [closeSignInPage] takes it down-/// once the redirect lands.-///-/// ⚠️ Unverified on a device: the SSO page's Google button opens a popup, and whether an in-app-/// browser view lets that popup post back to its opener is exactly what the first run on a phone-/// has to answer.-Future<bool> openSignInPage(Uri url) => launchUrl(- url,- mode: Platform.isIOS || Platform.isAndroid- ? LaunchMode.inAppBrowserView- : LaunchMode.externalApplication,-);--Future<void> closeSignInPage() async {- if (Platform.isIOS || Platform.isAndroid) await closeInAppWebView();-}diff --git a/mobile/test/app_state_phone_paths_test.dart b/mobile/test/app_state_phone_paths_test.dartindex 3fccbc84e..99911365f 100644--- a/mobile/test/app_state_phone_paths_test.dart+++ b/mobile/test/app_state_phone_paths_test.dart@@ -590,15 +590,17 @@ void main() {test('closing the app mid sign-in lets go of the sign-in', () async {final rig = viewerApp(signedIn: false);- rig.viewer.emailLogin.gate = Completer<void>();+ final gate = rig.viewer.emailLogin.gate = Completer<void>();- unawaited(- rig.app.signInWithCode(email: '[email protected]', code: '1').catchError((_) {}),- );+ final signingIn = rig.app.signInWithCode(email: '[email protected]', code: '1');await settle();rig.app.dispose();+ gate.complete();+ await signingIn;- expect(rig.signIn.cancels, 1);+ // The code's answer lands on an app that is gone: nothing is fetched for+ // it, and nothing tells a disposed notifier's listeners (which throws).+ expect(rig.api.machineFetches, 0);});}diff --git a/mobile/test/viewer/viewer_services_test.dart b/mobile/test/viewer/viewer_services_test.dartindex 584b86d56..8b07c9046 100644--- a/mobile/test/viewer/viewer_services_test.dart+++ b/mobile/test/viewer/viewer_services_test.dart@@ -88,9 +88,6 @@ void main() {await login.auth.signIn(const IssuedTokens(token: 't'));expect((await login.checkStatus()).loggedIn, isTrue);- // Cancelling with nothing in progress is nothing.- login.cancel();-await login.logout();expect((await login.checkStatus()).loggedIn, isFalse);expect(await session.accessToken(), isNull);diff --git a/mobile/test/viewer_app_fixture.dart b/mobile/test/viewer_app_fixture.dartindex 5a7e61a54..70bd3e094 100644--- a/mobile/test/viewer_app_fixture.dart+++ b/mobile/test/viewer_app_fixture.dart@@ -209,7 +209,6 @@ class FakeSignIn implements SignInClient {/// Held open until the test completes it.Completer<void>? statusGate;- int cancels = 0;int logouts = 0;@override@@ -219,14 +218,6 @@ class FakeSignIn implements SignInClient {return CliAuthStatus(loggedIn: signedIn);}- @override- Future<void> login({- required void Function(String url) onAuthorizeUrl,- }) async {}-- @override- void cancel() => cancels++;-@overrideFuture<void> logout() async => logouts++;}@@ -452,7 +443,6 @@ ViewerRig viewerApp({authSession: session,configStore: null,cliLogin: signIn,- cliLink: CliLink(),peerLinks: links,viewer: viewer,paneLayoutStore: storage == null ? null : PaneLayoutStore(storage: storage),