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
feat(mobile): open a harness's sign-in page on the phone, and send the sign-in back
bubu-dudu17018d8bf6bc
diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dartindex f87e168b5..e60bec88e 100644--- a/mobile/lib/e2ee/envelope.dart+++ b/mobile/lib/e2ee/envelope.dart@@ -61,6 +61,9 @@ const Set<String> encryptedDownTypes = {// redirect, with its code, rides `callback`. A `MACHINE_REQUESTS` type in the CLI: sent in the clear// the machine refused it ("E2EE required"), which read as no computer online.'connectors',+ // A sign-in this phone caught for a page a harness's program opened (`AppNotifier.browserCallback`): it+ // carries the code. A `MACHINE_REQUESTS` type in the CLI.+ 'browser_callback','codex_profiles_list','codex_profile_link',// Asks the machine to read its OWN agent accounts' usage (cli/src/lib/accountUsage.ts). Missingdiff --git a/mobile/lib/phone/browser_handoff.dart b/mobile/lib/phone/browser_handoff.dartnew file mode 100644index 000000000..4f4c700bd--- /dev/null+++ b/mobile/lib/phone/browser_handoff.dart@@ -0,0 +1,141 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:url_launcher/url_launcher.dart';++import 'package:harness_mobile/state/app_state.dart';++/// A page a program in a harness's pane opened while this phone was the one typing there — Claude Code's+/// `/login`, `gh auth login` — opened here instead of on the computer (cli core/terminals/browser.ts).+///+/// The address is also put on the clipboard: it can be sent to somebody else to sign in for the person.+///+/// A sign-in that returns to the program at `http://localhost:PORT/callback` would land on this phone's own+/// localhost. So the phone listens there itself, as Settings ▸ Connectors does, catches the redirect, closes+/// the browser and hands the redirect to the computer (`browser_callback`), which gives it to the program+/// still waiting on that port. The code is no use without the secret the program kept on the computer.+class BrowserHandoff {+ BrowserHandoff(this.notifier, {required this.say});++ final AppNotifier notifier;++ /// A line for the person, in a snack bar.+ final void Function(String text) say;++ final List<HttpServer> _servers = [];+ Timer? _giveUp;++ /// How long a sign-in may take before the phone stops listening for its redirect.+ static const listenFor = Duration(minutes: 10);++ Future<void> open(String machineId, String url) async {+ final page = Uri.tryParse(url);+ if (page == null || !(page.scheme == 'https' || page.scheme == 'http')) {+ return;+ }+ unawaited(Clipboard.setData(ClipboardData(text: url)).catchError((_) {}));+ final redirect = Uri.tryParse(page.queryParameters['redirect_uri'] ?? '');+ await _stop();+ if (redirect != null && _loopback(redirect)) {+ await _listen(machineId, redirect);+ }+ final opened = await launchUrl(+ page,+ mode: LaunchMode.inAppBrowserView,+ ).catchError((_) => false);+ if (!opened) {+ say(+ 'Could not open the browser. The address is copied: open it in a browser.',+ );+ await _stop();+ return;+ }+ say('Sign-in opened on this phone. The address is copied too.');+ }++ static bool _loopback(Uri uri) =>+ uri.scheme == 'http' &&+ (uri.host == 'localhost' || uri.host == '127.0.0.1') &&+ uri.hasPort;++ /// Both loopbacks: a browser may try `localhost` as ::1 before 127.0.0.1.+ Future<void> _listen(String machineId, Uri redirect) async {+ for (final address in [+ InternetAddress.loopbackIPv4,+ InternetAddress.loopbackIPv6,+ ]) {+ try {+ final server = await HttpServer.bind(address, redirect.port);+ _servers.add(server);+ server.listen(+ (request) => unawaited(_caught(machineId, redirect, request)),+ );+ debugPrint('browser: listening on ${address.address}:${redirect.port}');+ } on SocketException {+ // The port is taken on this phone (or there is no IPv6): the browser shows the redirect, and the+ // program still prints its own address to finish by hand.+ }+ }+ _giveUp = Timer(listenFor, () => unawaited(_stop()));+ }++ Future<void> _caught(+ String machineId,+ Uri redirect,+ HttpRequest request,+ ) async {+ if (request.uri.path != redirect.path) {+ request.response.statusCode = HttpStatus.notFound;+ await request.response.close();+ return;+ }+ request.response+ ..statusCode = HttpStatus.ok+ ..headers.contentType = ContentType.html+ ..headers.set('Cache-Control', 'no-store')+ ..write(+ '<!doctype html><meta charset=utf-8>'+ '<meta name=viewport content="width=device-width,initial-scale=1">'+ '<title>Harness</title>'+ "<body style='font:16px ui-monospace,monospace;background:#11140f;color:#e7e8de;padding:32px'>"+ '<h1>Signed in.</h1><p>Return to Harness to finish.</p>',+ );+ await request.response.close();+ await _stop();+ unawaited(closeInAppWebView().catchError((_) {}));+ final caught = redirect.replace(query: request.uri.query).toString();+ debugPrint('browser: caught the sign-in on port ${redirect.port}');+ // The line to the computer is often down while the browser covered the app: try until it is back.+ final deadline = DateTime.now().add(const Duration(minutes: 2));+ while (DateTime.now().isBefore(deadline)) {+ final reply = await notifier.browserCallback(machineId, caught);+ debugPrint(+ 'browser: the computer answered ${reply['ok'] == true ? 'ok' : reply['error'] ?? reply['status']}',+ );+ if (reply['error'] == 'UNAVAILABLE') {+ await Future<void>.delayed(const Duration(seconds: 2));+ continue;+ }+ say(+ reply['ok'] == true+ ? 'Signed in on the computer.'+ : 'The computer did not accept the sign-in. Try again.',+ );+ return;+ }+ say('The computer could not be reached. Try signing in again.');+ }++ Future<void> _stop() async {+ _giveUp?.cancel();+ _giveUp = null;+ for (final server in _servers) {+ await server.close(force: true);+ }+ _servers.clear();+ }++ Future<void> dispose() => _stop();+}diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dartindex 421059f71..b95dd36e7 100644--- a/mobile/lib/phone/phone_shell.dart+++ b/mobile/lib/phone/phone_shell.dart@@ -7,6 +7,7 @@ import 'package:harness_mobile/state/app_state.dart';import '../p2p/phone_terminal_p2p.dart';import 'agent_home.dart';import 'approve_sign_in.dart';+import 'browser_handoff.dart';import 'devices_page.dart';import 'exit_app.dart';import 'new_device_banner.dart';@@ -35,6 +36,7 @@ class PhoneShell extends StatefulWidget {}class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {+ late final BrowserHandoff _browser;final _navigator = GlobalKey<NavigatorState>();/// The nested navigator's own — see the note at the `HeroControllerScope` below.@@ -44,6 +46,15 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {void initState() {super.initState();WidgetsBinding.instance.addObserver(this);+ // A page a harness's program opened while this phone was typing there (Claude Code's `/login`).+ _browser = BrowserHandoff(+ widget.notifier,+ say: (text) =>+ ScaffoldMessenger.maybeOf(context)+ ?.showSnackBar(SnackBar(content: Text(text))),+ );+ widget.notifier.onBrowserOpen = (machineId, _, url) =>+ unawaited(_browser.open(machineId, url));final notices = widget.notifier.agentNotices.system;notices.opened.addListener(_openNoticedAgent);notices.openedDevice.addListener(_openNoticedDevice);@@ -71,6 +82,8 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {@overridevoid dispose() {WidgetsBinding.instance.removeObserver(this);+ widget.notifier.onBrowserOpen = null;+ unawaited(_browser.dispose());widget.notifier.agentNotices.system.opened.removeListener(_openNoticedAgent,);diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex f81d7a3ae..f7d013c2a 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -5570,6 +5570,25 @@ class AppNotifier extends ChangeNotifier {/// `connectors` on [machineId] (cli/src/services/connectors.ts): `list`, `connect`, `flow`,/// `callback`, `disconnect`. A machine that cannot answer reads as `{error: UNAVAILABLE}`.+ /// Set by the phone shell: opens a page a harness's program asked for (`browser_open`,+ /// phone/browser_handoff.dart).+ void Function(String machineId, String agentId, String url)? onBrowserOpen;++ /// Hands a sign-in this phone caught back to [machineId], to the program waiting for it there+ /// (`browser_callback`, cli core/terminals/browser.ts). `{'error': 'UNAVAILABLE'}` when the line is down.+ Future<Map<String, dynamic>> browserCallback(String machineId, String url) async {+ final machine = machineStates[machineId];+ if (machine == null || machine.needsLink) return {'error': 'UNAVAILABLE'};+ try {+ return await _conn(machineId).request(+ 'browser_callback',+ payload: {'url': url},+ );+ } catch (_) {+ return {'error': 'UNAVAILABLE'};+ }+ }+Future<Map<String, dynamic>> connectors(String machineId,Map<String, dynamic> payload, {@@ -8191,6 +8210,14 @@ class AppNotifier extends ChangeNotifier {}}break;+ // A program in a harness's pane opened a page (Claude Code's `/login`) while this phone was the one+ // typing there (cli core/terminals/browser.ts): it opens on this phone. Nothing here to redraw.+ case 'browser_open':+ final url = payload['url'];+ if (url is String && url.isNotEmpty) {+ onBrowserOpen?.call(machineId, payload['agentId'] as String? ?? '', url);+ }+ return;// ⚠️ Everything else changed nothing here, so it must not redraw. The machine streams every// agent's live chat — `text_delta`, `tool_start`, … — down this socket, several per second// per agent, and each one used to rebuild every screen listening to this notifier.