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.

fix(mobile): end sign-in when the SSO page is closed

tonyec485d86e02e
diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift
index f93a2c51a..2cfa7df10 100644
--- a/mobile/ios/Runner/AppDelegate.swift
+++ b/mobile/ios/Runner/AppDelegate.swift
@@ -1,4 +1,5 @@
import Flutter
+import SafariServices
import UIKit
import UserNotifications
@@ -18,6 +19,7 @@ import UserNotifications
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
DeviceNameChannel.register(with: engineBridge.pluginRegistry)
ClipboardImageChannel.register(with: engineBridge.pluginRegistry)
+ SignInPageChannel.register(with: engineBridge.pluginRegistry)
}
}
@@ -93,3 +95,123 @@ enum DeviceNameChannel {
}
}
}
+
+/// `harness/sign_in_page` — the SSO page, in an SFSafariViewController over the app (Dart:
+/// `lib/viewer/sign_in_browser.dart`). url_launcher's in-app page tells Dart nothing once its first
+/// load is over, so a page closed with Done left its sign-in waiting out five minutes behind
+/// "Waiting for Google…" and a Cancel. Here Done — or a swipe down — is said back: `closed`, with the
+/// id Dart opened the page with.
+///
+/// `open` answers once the page is on its way up; `close` takes it down and says nothing, since Dart
+/// asked.
+final class SignInPageChannel: NSObject, SFSafariViewControllerDelegate,
+ UIAdaptivePresentationControllerDelegate
+{
+ private static var shared: SignInPageChannel?
+
+ private let registrar: FlutterPluginRegistrar
+ private let channel: FlutterMethodChannel
+ /// The page up now, and the id Dart opened it with; nil once it is closed or taken down.
+ private var page: (controller: SFSafariViewController, id: Int)?
+
+ static func register(with registry: FlutterPluginRegistry) {
+ guard let registrar = registry.registrar(forPlugin: "HarnessSignInPage") else { return }
+ shared = SignInPageChannel(registrar: registrar)
+ }
+
+ private init(registrar: FlutterPluginRegistrar) {
+ self.registrar = registrar
+ channel = FlutterMethodChannel(
+ name: "harness/sign_in_page", binaryMessenger: registrar.messenger())
+ super.init()
+ channel.setMethodCallHandler { [weak self] call, result in
+ self?.handle(call, result: result)
+ }
+ }
+
+ private func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
+ switch call.method {
+ case "open":
+ let arguments = call.arguments as? [String: Any]
+ guard let id = arguments?["id"] as? Int,
+ let url = (arguments?["url"] as? String).flatMap(URL.init(string:)),
+ let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http"
+ else {
+ result(FlutterError(code: "bad-args", message: "Not a page to open", details: nil))
+ return
+ }
+ open(url, id: id, result: result)
+ case "close":
+ if let controller = take() { Self.takeDown(controller, animated: true) }
+ result(nil)
+ default:
+ result(FlutterMethodNotImplemented)
+ }
+ }
+
+ private func open(_ url: URL, id: Int, result: @escaping FlutterResult) {
+ // One page at a time: one an earlier sign-in left up goes first, without a word to Dart.
+ guard let old = take(), old.presentingViewController != nil else {
+ present(url, id: id, result: result)
+ return
+ }
+ Self.takeDown(old, animated: false) { self.present(url, id: id, result: result) }
+ }
+
+ private func present(_ url: URL, id: Int, result: @escaping FlutterResult) {
+ var presenter = registrar.viewController
+ while let presented = presenter?.presentedViewController, !presented.isBeingDismissed {
+ presenter = presented
+ }
+ guard let presenter else {
+ result(FlutterError(code: "no-ui", message: "Nothing on screen to open it over", details: nil))
+ return
+ }
+ let controller = SFSafariViewController(url: url)
+ controller.delegate = self
+ // Shown as a sheet, it can also be swiped away, which its own delegate does not hear.
+ controller.presentationController?.delegate = self
+ page = (controller, id)
+ presenter.present(controller, animated: true)
+ result(nil)
+ }
+
+ /// The page, no longer this channel's to watch.
+ private func take() -> SFSafariViewController? {
+ let controller = page?.controller
+ page = nil
+ return controller
+ }
+
+ /// Dismisses [controller] — once it is up, when it is still animating in: UIKit drops a dismiss
+ /// made during a presentation, and the page would stay up over a sign-in that had ended.
+ private static func takeDown(
+ _ controller: UIViewController, animated: Bool, then: (() -> Void)? = nil
+ ) {
+ if controller.isBeingPresented, let coordinator = controller.transitionCoordinator,
+ coordinator.animate(
+ alongsideTransition: nil,
+ completion: { _ in controller.dismiss(animated: animated, completion: then) })
+ {
+ return
+ }
+ controller.dismiss(animated: animated, completion: then)
+ }
+
+ /// The person closed [controller] — if it is still the page up, Dart is told.
+ private func closedByPerson(_ controller: UIViewController) {
+ guard let page, page.controller === controller else { return }
+ self.page = nil
+ channel.invokeMethod("closed", arguments: page.id)
+ }
+
+ // Done. The dismiss is url_launcher's own: harmless when the page has already gone by itself.
+ func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
+ closedByPerson(controller)
+ controller.dismiss(animated: true)
+ }
+
+ func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
+ closedByPerson(presentationController.presentedViewController)
+ }
+}
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index f1e61e4e1..b4480b9a5 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -1762,22 +1762,28 @@ class AppNotifier extends ChangeNotifier {
}
/// The page [signInWithProvider] waits on, shown. One that cannot be shown ends that sign-in
- /// with the reason — it would otherwise wait out its timeout on a page nobody can see — but
- /// only while it is still the sign-in in flight: a later one is not this failure's to end.
+ /// with the reason — it would otherwise wait out its timeout on a page nobody can see — and one
+ /// the person closes ends it as a cancel ([DirectLogin.pageClosed]): the welcome screen is back
+ /// as it was, with nothing to say. Either only while it is still the sign-in in flight: a later
+ /// one is not this page's to end.
Future<void> _openSignInPage(Uri url, DirectLogin login, int revision) async {
- DirectAuthException reason;
+ bool inFlight() => _authWorkCurrent(revision) && signInProvider != null;
try {
- if (await openSignInPage(url)) return;
- // iOS answers false for a page closed before it had loaded: the person's own cancel.
- reason = const SignInCancelled();
+ await openSignInPage(
+ url,
+ onClosed: () {
+ if (inFlight()) login.pageClosed();
+ },
+ );
} catch (error) {
debugPrint('signInWithProvider: could not open the sign-in page: $error');
- reason = const DirectAuthException(
- 'Could not open the sign-in page. Check your connection and try again.',
- );
- }
- if (_authWorkCurrent(revision) && signInProvider != null) {
- login.cancel(reason);
+ if (inFlight()) {
+ login.cancel(
+ const DirectAuthException(
+ 'Could not open the sign-in page. Check your connection and try again.',
+ ),
+ );
+ }
}
}
diff --git a/mobile/lib/viewer/direct_login.dart b/mobile/lib/viewer/direct_login.dart
index af9778fb5..295209538 100644
--- a/mobile/lib/viewer/direct_login.dart
+++ b/mobile/lib/viewer/direct_login.dart
@@ -157,6 +157,15 @@ class DirectLogin implements SignInClient {
callback?.cancel(error);
}
+ /// The person closed the sign-in page themselves (`sign_in_browser.dart`). Before the redirect
+ /// came back that is a [cancel]; after it, the sign-in is already on its way in — the page then
+ /// says "Close this page to go back to Harness" — and carries on.
+ void pageClosed() {
+ final callback = _pending;
+ if (callback == null || callback.answered) return;
+ cancel();
+ }
+
void _requireCurrent(int revision) {
if (revision != _loginRevision) throw const SignInCancelled();
}
@@ -185,6 +194,9 @@ class _LoopbackCallback {
Future<({String code, String state})?> get result => _completer.future;
+ /// The redirect came back — or the sign-in was stopped — so there is nothing left to wait on.
+ bool get answered => _completer.isCompleted;
+
/// Completes when [cancel] stops this sign-in — also after its redirect has landed, for an
/// exchange that is waiting to try again ([DirectLogin._exchange]).
Future<void> get stopped => _stopped.future;
diff --git a/mobile/lib/viewer/sign_in_browser.dart b/mobile/lib/viewer/sign_in_browser.dart
index 7e50635db..6933c8bdc 100644
--- a/mobile/lib/viewer/sign_in_browser.dart
+++ b/mobile/lib/viewer/sign_in_browser.dart
@@ -1,4 +1,8 @@
+import 'dart:async';
+import 'dart:io';
+
import 'package:flutter/services.dart';
+import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
/// Where the SSO page opens: in the app — SFSafariViewController on iOS, a Custom Tab on Android —
@@ -13,22 +17,36 @@ import 'package:url_launcher/url_launcher.dart';
/// ([closeSignInPage]): on Android the page's last screen goes back to the app through
/// [signInReturnUrl] instead.
///
-/// True once the page is up; false when iOS's sheet was closed before its first page loaded.
-Future<bool> openSignInPage(Uri url) async {
+/// [onClosed]: the person closed the page themselves — iOS's Done, Android's ✕ — before
+/// [closeSignInPage] took it down. url_launcher says nothing of it, and the sign-in the page was
+/// for waited out its five minutes behind "Waiting for Google…" and a Cancel nobody had pressed.
+/// Not told once the page has been taken down, nor once another page has been opened.
+///
+/// Completes once the page is on its way up; throws when it cannot be shown.
+Future<void> openSignInPage(Uri url, {required VoidCallback onClosed}) async {
+ _stopWatching();
+ final id = _pageId;
+ _onClosed = onClosed;
try {
- return await launchUrl(url, mode: LaunchMode.inAppBrowserView);
- } on PlatformException catch (error) {
- // ⚠️ **The sheet is up — this is the sign-in page working, not failing.** Named a provider,
- // auth-service's page replaces itself with Google's or Apple's (`location.replace`) before
- // its own load finishes, so SFSafariViewController reports the first load as failed, and
- // url_launcher_ios throws exactly this (`_failedSafariViewControllerLoadException`) while
- // leaving the sheet where it is. Taking it as "could not open" cancelled every iOS sign-in
- // and pulled the sheet out from under Google's account picker. A page that truly failed to
- // load is still on screen, saying so, for the person to close.
- if (error.code == 'Error' &&
- (error.message ?? '').startsWith('Error while launching')) {
- return true;
+ if (Platform.isIOS) {
+ _iosPage.setMethodCallHandler(_fromIosPage);
+ await _iosPage.invokeMethod<void>('open', {'id': id, 'url': '$url'});
+ return;
+ }
+ // A Custom Tab says nothing when it is closed: the app coming back to the front is that close.
+ // Not at once — a redirect that came in while the app was frozen is only taken in once it
+ // runs again, and that sign-in is under way rather than closed ([DirectLogin.pageClosed]).
+ _resumeWatch = AppLifecycleListener(
+ onResume: () {
+ _closedGrace?.cancel();
+ _closedGrace = Timer(const Duration(seconds: 1), () => _closed(id));
+ },
+ );
+ if (!await launchUrl(url, mode: LaunchMode.inAppBrowserView)) {
+ throw StateError('No browser to open $url in');
}
+ } catch (_) {
+ if (id == _pageId) _stopWatching();
rethrow;
}
}
@@ -40,9 +58,45 @@ const signInReturnUrl = 'ai.autonomous.harness.signin://signed-in';
/// Takes down what [openSignInPage] put up, where the platform can. Best effort.
Future<void> closeSignInPage() async {
+ _stopWatching();
try {
- if (await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView)) {
+ if (Platform.isIOS) {
+ await _iosPage.invokeMethod<void>('close');
+ } else if (await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView)) {
await closeInAppWebView();
}
} catch (_) {}
}
+
+/// iOS's page (`SignInPageChannel`, `ios/Runner/AppDelegate.swift`): url_launcher's
+/// SFSafariViewController cannot say when Done was pressed.
+const _iosPage = MethodChannel('harness/sign_in_page');
+
+/// The page [openSignInPage] last opened; bumped when it is let go, so what its platform says
+/// later is not taken for the next one's.
+int _pageId = 0;
+VoidCallback? _onClosed;
+AppLifecycleListener? _resumeWatch;
+Timer? _closedGrace;
+
+void _stopWatching() {
+ _pageId++;
+ _onClosed = null;
+ _resumeWatch?.dispose();
+ _resumeWatch = null;
+ _closedGrace?.cancel();
+ _closedGrace = null;
+}
+
+Future<void> _fromIosPage(MethodCall call) async {
+ if (call.method == 'closed' && call.arguments is int) {
+ _closed(call.arguments as int);
+ }
+}
+
+void _closed(int id) {
+ final onClosed = _onClosed;
+ if (id != _pageId || onClosed == null) return;
+ _stopWatching();
+ onClosed();
+}