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(desktop): recover browser sign-in and cancel stale attempts

deeb7b60753737b
diff --git a/desktop/lib/auth/cli_login.dart b/desktop/lib/auth/cli_login.dart
index caf396218..2a19b5667 100644
--- a/desktop/lib/auth/cli_login.dart
+++ b/desktop/lib/auth/cli_login.dart
@@ -42,6 +42,7 @@ class CliNotAvailableException implements Exception {
class CliLogin {
final HarnessCliRunner _runner;
Process? _activeProcess;
+ int _loginRevision = 0;
CliLogin({HarnessCliRunner? runner}) : _runner = runner ?? HarnessCliRunner();
@@ -67,12 +68,21 @@ class CliLogin {
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.
@@ -85,6 +95,7 @@ class CliLogin {
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;
@@ -104,6 +115,9 @@ class CliLogin {
}
}
final exitCode = await process.exitCode;
+ if (revision != _loginRevision) {
+ throw StateError('Sign-in was cancelled.');
+ }
if (!gotResult || !success) {
throw StateError(
message ??
@@ -113,13 +127,16 @@ class CliLogin {
);
}
} finally {
- _activeProcess = null;
+ if (identical(_activeProcess, process)) _activeProcess = null;
}
}
- /// Aborts an in-flight [login] — used by the embedded sign-in webview's close button.
+ /// Aborts this attempt even if its process has not finished starting yet.
void cancel() {
- _activeProcess?.kill();
+ ++_loginRevision;
+ final process = _activeProcess;
+ _activeProcess = null;
+ process?.kill();
}
Future<void> logout() async {
diff --git a/desktop/lib/screens/login_screen.dart b/desktop/lib/screens/login_screen.dart
index 214374b1d..7a0f74987 100644
--- a/desktop/lib/screens/login_screen.dart
+++ b/desktop/lib/screens/login_screen.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
@@ -7,7 +8,7 @@ import '../widgets/welcome_workspace_preview.dart';
/// The sign-in screen.
///
-/// Lead with the work: real coding agents together in one workspace. A static
+/// Lead with the work: real agents together in one workspace. A static
/// example explains a swarm before sign-in; the privacy guarantee stays in the
/// quiet footer. The preview never creates agents or sends them a task.
///
@@ -44,6 +45,8 @@ class LoginScreen extends StatelessWidget {
// The same flag `RootShell` routes on, so the button's state and the reason
// this screen is on screen at all can never disagree.
final waiting = notifier.signingIn;
+ final compact = MediaQuery.sizeOf(context).height < 640;
+ final gap = compact ? 16.0 : 24.0;
return Scaffold(
// The PANEL tone, not the window's. In light both `windowBg` and the
@@ -58,7 +61,7 @@ class LoginScreen extends StatelessWidget {
const Positioned.fill(child: LoginAurora()),
Center(
child: SingleChildScrollView(
- padding: const EdgeInsets.all(24),
+ padding: EdgeInsets.all(compact ? 16 : 24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: _cardWidth),
child: Container(
@@ -68,12 +71,12 @@ class LoginScreen extends StatelessWidget {
borderRadius: BorderRadius.circular(14),
boxShadow: grid.AppCard.shadow,
),
- padding: const EdgeInsets.all(24),
+ padding: EdgeInsets.all(compact ? 20 : 24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const _AppMark(),
- const SizedBox(height: 24),
+ SizedBox(height: gap),
Text(
'All your agents, on one screen',
textAlign: TextAlign.center,
@@ -86,9 +89,9 @@ class LoginScreen extends StatelessWidget {
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall,
),
- const SizedBox(height: 24),
+ SizedBox(height: gap),
const WelcomeWorkspacePreview(),
- const SizedBox(height: 24),
+ SizedBox(height: gap),
_Action(notifier: notifier, waiting: waiting),
if (notifier.lastError != null) ...[
const SizedBox(height: 16),
@@ -97,7 +100,7 @@ class LoginScreen extends StatelessWidget {
onRetry: notifier.login,
),
],
- const SizedBox(height: 24),
+ SizedBox(height: gap),
const _Seal(),
],
),
@@ -117,27 +120,79 @@ class LoginScreen extends StatelessWidget {
/// changes, a spinner replaces the glyph, and Cancel appears beside it. Nothing
/// moves position, so the wait reads as *this button is working* rather than as
/// a new screen.
-class _Action extends StatelessWidget {
+class _Action extends StatefulWidget {
const _Action({required this.notifier, required this.waiting});
final AppNotifier notifier;
final bool waiting;
+ @override
+ State<_Action> createState() => _ActionState();
+}
+
+class _ActionState extends State<_Action> {
+ AppNotifier get notifier => widget.notifier;
+ final _signInFocus = FocusNode(debugLabel: 'Sign in');
+ String? _copiedUrl;
+ String? _copyFailureUrl;
+ bool _copying = false;
+
+ @override
+ void didUpdateWidget(covariant _Action oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.waiting && !widget.waiting) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _signInFocus.requestFocus();
+ }
+ });
+ }
+ }
+
+ @override
+ void dispose() {
+ _signInFocus.dispose();
+ super.dispose();
+ }
+
+ Future<void> _copyLink() async {
+ final url = notifier.pendingAuthorizeUrl;
+ if (url == null || !notifier.signingIn || _copying) return;
+ setState(() => _copying = true);
+ var copied = false;
+ try {
+ await Clipboard.setData(ClipboardData(text: url));
+ copied = true;
+ } catch (_) {
+ // Keep recovery in the same sign-in if the OS clipboard is unavailable.
+ }
+ if (!mounted) return;
+ setState(() {
+ _copying = false;
+ if (notifier.signingIn && notifier.pendingAuthorizeUrl == url) {
+ _copiedUrl = copied ? url : null;
+ _copyFailureUrl = copied ? null : url;
+ }
+ });
+ }
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- if (!waiting) {
+ if (!widget.waiting) {
return Column(
children: [
FilledButton.icon(
+ focusNode: _signInFocus,
+ autofocus: true,
onPressed: notifier.login,
icon: const Icon(Icons.login, size: grid.AppControl.iconSize),
label: const Text('Sign in'),
),
const SizedBox(height: 12),
Text(
- 'Sign in through your browser. We’ll bring you back here.',
+ 'Sign in through your browser to continue.',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall,
),
@@ -145,6 +200,12 @@ class _Action extends StatelessWidget {
);
}
+ final url = notifier.pendingAuthorizeUrl;
+ final message =
+ notifier.loginBrowserError ??
+ (url != null && _copyFailureUrl == url
+ ? 'Couldn’t copy the link. Try opening your browser again.'
+ : null);
return Column(
children: [
FilledButton.icon(
@@ -156,23 +217,65 @@ class _Action extends StatelessWidget {
height: grid.AppControl.iconSize,
child: CircularProgressIndicator(strokeWidth: 2),
),
- label: const Text('Waiting for your browser'),
+ label: Text(url == null ? 'Signing in…' : 'Waiting for your browser'),
),
const SizedBox(height: 12),
- Text(
- // Says the thing the idle line could not: what to do if the browser
- // did not come forward. That is the actual failure people hit here —
- // the tab opens behind the app and the window looks stuck.
- 'Finish in your browser. If it didn\'t open, check behind this '
- 'window.',
- textAlign: TextAlign.center,
- style: Theme.of(context).textTheme.bodySmall,
- ),
- const SizedBox(height: 8),
- TextButton(
- onPressed: notifier.cancelLogin,
- child: const Text('Cancel'),
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ message ??
+ (url == null
+ ? 'Your workspace will open when sign-in is complete.'
+ : 'Finish signing in in your browser, then return here.'),
+ textAlign: TextAlign.center,
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
),
+ if (url != null || notifier.canCancelLogin) ...[
+ const SizedBox(height: 12),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ alignment: WrapAlignment.center,
+ children: [
+ if (url != null) ...[
+ OutlinedButton.icon(
+ onPressed: notifier.openingLoginBrowser
+ ? null
+ : notifier.openLoginBrowser,
+ icon: const Icon(Icons.open_in_new, size: 16),
+ label: Text(
+ notifier.openingLoginBrowser
+ ? 'Opening browser…'
+ : 'Open browser',
+ ),
+ ),
+ TextButton.icon(
+ onPressed: _copying ? null : _copyLink,
+ icon: Icon(
+ _copiedUrl == url ? Icons.check : Icons.content_copy,
+ size: 16,
+ ),
+ label: Semantics(
+ liveRegion: true,
+ child: Text(
+ _copiedUrl == url ? 'Link copied' : 'Copy link',
+ ),
+ ),
+ ),
+ ],
+ if (notifier.canCancelLogin)
+ TextButton(
+ autofocus: true,
+ onPressed: notifier.cancelLogin,
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textSecondary,
+ ),
+ child: const Text('Cancel'),
+ ),
+ ],
+ ),
+ ],
],
);
}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index b7e2ec2a1..e2d2346ef 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -341,6 +341,8 @@ class AppNotifier extends ChangeNotifier {
!_disposed && revision == _authRevision;
int _invalidateAuthWork() {
+ _resetLoginBrowser();
+ _loginAuthorized = false;
_profileInFlight = null;
_retryInFlight = null;
machinesLoading = false;
@@ -890,9 +892,14 @@ class AppNotifier extends ChangeNotifier {
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 — so it says "the browser is open", not "a sign-in is running". Use [signingIn] for the
- // second question; see the note there.
+ // 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.
///
@@ -2152,17 +2159,21 @@ class AppNotifier extends ChangeNotifier {
await cliLogin.login(
onAuthorizeUrl: (url) {
if (!_authWorkCurrent(revision)) return;
+ if (pendingAuthorizeUrl == url) return;
+ _resetLoginBrowser();
pendingAuthorizeUrl = url;
notifyListeners();
// Must be the system browser, not an embedded webview: this SSO page's Google button uses
// Google's popup-based Identity Services flow (a real popup window posts the result back to
// its opener), which only a real browser can satisfy.
- unawaited(
- launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication),
- );
+ unawaited(openLoginBrowser());
},
);
if (!_authWorkCurrent(revision)) return;
+ _loginAuthorized = true;
+ pendingAuthorizeUrl = null;
+ _resetLoginBrowser();
+ notifyListeners();
await _finishBootstrapSignedIn();
if (!_authWorkCurrent(revision) || status != AppStatus.authenticated)
return;
@@ -2188,6 +2199,8 @@ class AppNotifier extends ChangeNotifier {
// 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;
}
@@ -2195,11 +2208,63 @@ class AppNotifier extends ChangeNotifier {
if (_authWorkCurrent(revision)) notifyListeners();
}
- /// Aborts an in-flight [login] — the embedded sign-in webview's close button calls this.
- void cancelLogin() => cliLogin.cancel();
+ 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')) {
+ opened = await launchUrl(uri, mode: LaunchMode.externalApplication);
+ }
+ } catch (_) {
+ // Browser handoff failure is recoverable within the same sign-in. Never
+ // put a credential-bearing URL or a raw platform exception in the UI.
+ }
+ if (!_authWorkCurrent(authRevision) ||
+ browserRevision != _loginBrowserRevision ||
+ pendingAuthorizeUrl != url) {
+ return;
+ }
+ openingLoginBrowser = false;
+ if (!opened) {
+ loginBrowserError =
+ 'Couldn’t open your browser. Open it again or copy the sign-in link.';
+ }
+ notifyListeners();
+ }
+
+ /// Return immediately; late URLs, results and browser replies belong to the
+ /// cancelled attempt and cannot change a subsequent sign-in.
+ void cancelLogin() {
+ if (_disposed || !canCancelLogin) return;
+ _invalidateAuthWork();
+ signingIn = false;
+ pendingAuthorizeUrl = null;
+ status = AppStatus.unauthenticated;
+ _lastError = null;
+ _lastErrorRetryable = false;
+ cliLogin.cancel();
+ notifyListeners();
+ }
Future<void> logout() async {
final revision = _invalidateAuthWork();
+ cliLogin.cancel();
signingIn = false;
pendingAuthorizeUrl = null;
_closedHistory.clear();
@@ -5313,6 +5378,7 @@ class AppNotifier extends ChangeNotifier {
void dispose() {
_localGitProjects.dispose();
_disposed = true;
+ if (signingIn) cliLogin.cancel();
_closedHistory.clear();
_daemonSupervisionTimer?.cancel();
_updateCheckTimer?.cancel();
diff --git a/desktop/lib/widgets/environment_setup_screen.dart b/desktop/lib/widgets/environment_setup_screen.dart
index 56124004f..5dad543f6 100644
--- a/desktop/lib/widgets/environment_setup_screen.dart
+++ b/desktop/lib/widgets/environment_setup_screen.dart
@@ -124,7 +124,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
'Get this computer ready',
count == 0
? 'Nothing is left to install. Harness will run one final verification.'
- : 'Harness brings your coding agents together in one workspace. '
+ : 'Harness brings your agents together in one workspace. '
'Set up the $countLabel below, then sign in to get started.',
),
Row(
diff --git a/desktop/test/cli_login_test.dart b/desktop/test/cli_login_test.dart
index d9f533805..638440f84 100644
--- a/desktop/test/cli_login_test.dart
+++ b/desktop/test/cli_login_test.dart
@@ -1,10 +1,130 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/auth/cli_login.dart';
+import 'package:harness/core/harness_cli_runner.dart';
+
+class _Runner extends HarnessCliRunner {
+ final starts = <Completer<Process>>[];
+ @override
+ Future<Process> start(List<String> arguments) {
+ expect(arguments, ['login', '--force', '--json']);
+ final start = Completer<Process>();
+ starts.add(start);
+ return start.future;
+ }
+}
+
+class _Process implements Process {
+ final output = StreamController<List<int>>();
+ final errors = StreamController<List<int>>();
+ final ended = Completer<int>();
+ var kills = 0;
+ void emit(Map<String, dynamic> event) =>
+ output.add(utf8.encode('${jsonEncode(event)}\n'));
+ void finish() {
+ unawaited(output.close());
+ unawaited(errors.close());
+ if (!ended.isCompleted) ended.complete(0);
+ }
+
+ @override
+ Stream<List<int>> get stdout => output.stream;
+ @override
+ Stream<List<int>> get stderr => errors.stream;
+ @override
+ Future<int> get exitCode => ended.future;
+ @override
+ bool kill([ProcessSignal signal = ProcessSignal.sigterm]) {
+ kills++;
+ // A signalled process need not exit synchronously. Tests explicitly finish
+ // it later, including after a replacement sign-in has already started.
+ return true;
+ }
+
+ @override
+ int get pid => 1;
+ @override
+ IOSink get stdin => throw UnimplementedError();
+}
-// The subprocess-spawning parts of CliLogin (checkStatus/login/logout all shell out to a real
-// `harness` binary) have no safe local seam to unit-test — same accepted limitation noted elsewhere
-// this session for live-transport paths. Only the pure JSON-parsing contract is covered here.
void main() {
+ test(
+ 'cancel while the CLI starts ignores its late URL and stops that process',
+ () async {
+ final runner = _Runner();
+ final cli = CliLogin(runner: runner);
+ final urls = <String>[];
+ final login = cli.login(onAuthorizeUrl: urls.add);
+ final result = expectLater(login, throwsStateError);
+ cli.cancel();
+ final process = _Process();
+ process.emit({
+ 'type': 'authorize_url',
+ 'url': 'https://auth.example/old',
+ });
+ process.emit({'type': 'result', 'status': 'success'});
+ runner.starts.single.complete(process);
+ process.finish();
+ await result;
+ expect(process.kills, 1);
+ expect(urls, isEmpty);
+ },
+ );
+
+ test(
+ 'a cancelled process cannot clear or complete its replacement',
+ () async {
+ final runner = _Runner();
+ final cli = CliLogin(runner: runner);
+ final urls = <String>[];
+ final first = cli.login(onAuthorizeUrl: urls.add);
+ final firstResult = expectLater(first, throwsStateError);
+ final old = _Process();
+ runner.starts.first.complete(old);
+ await Future<void>.delayed(Duration.zero);
+ cli.cancel();
+ final second = cli.login(onAuthorizeUrl: urls.add);
+ final secondResult = expectLater(second, throwsStateError);
+ final current = _Process();
+ runner.starts.last.complete(current);
+ await Future<void>.delayed(Duration.zero);
+ old.emit({'type': 'authorize_url', 'url': 'https://auth.example/old'});
+ old.emit({'type': 'result', 'status': 'success'});
+ old.finish();
+ await firstResult;
+ expect(urls, isEmpty);
+ cli.cancel();
+ expect(current.kills, 1);
+ current.finish();
+ await secondResult;
+ },
+ );
+
+ test(
+ 'successful CLI sign-in still publishes its URL and completes',
+ () async {
+ final runner = _Runner();
+ final cli = CliLogin(runner: runner);
+ final urls = <String>[];
+ final login = cli.login(onAuthorizeUrl: urls.add);
+ final process = _Process();
+ runner.starts.single.complete(process);
+ process.emit({
+ 'type': 'authorize_url',
+ 'url': 'https://auth.example/current',
+ });
+ process.emit({'type': 'result', 'status': 'success'});
+ process.finish();
+ await login;
+ cli.cancel();
+ expect(urls, ['https://auth.example/current']);
+ expect(process.kills, 0);
+ },
+ );
+
group('CliAuthStatus.fromJson', () {
test('parses a full logged-in payload', () {
final status = CliAuthStatus.fromJson({
diff --git a/desktop/test/login_screen_test.dart b/desktop/test/login_screen_test.dart
index 9c198f5ab..e0f51000b 100644
--- a/desktop/test/login_screen_test.dart
+++ b/desktop/test/login_screen_test.dart
@@ -25,7 +25,12 @@ Widget _host(
size: const Size(880, 560),
disableAnimations: reduceMotion,
),
- child: grid.BrightnessScope(child: LoginScreen(notifier: app)),
+ child: grid.BrightnessScope(
+ child: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => LoginScreen(notifier: app),
+ ),
+ ),
),
);
}
@@ -100,7 +105,9 @@ void main() {
tester,
) async {
// `signingIn` is what `main.dart` routes on — see the note there.
- final app = _notifier(AppStatus.bootstrapping)..signingIn = true;
+ final app = _notifier(AppStatus.bootstrapping)
+ ..signingIn = true
+ ..pendingAuthorizeUrl = 'https://auth.example/authorize';
await tester.pumpWidget(_host(app));
await tester.pump(const Duration(milliseconds: 100));
@@ -233,7 +240,7 @@ void main() {
// Just pressed: in flight, no URL yet.
expect(app.pendingAuthorizeUrl, isNull);
- expect(find.text('Waiting for your browser'), findsOneWidget);
+ expect(find.text('Signing in…'), findsOneWidget);
expect(find.byType(WelcomeWorkspacePreview), findsOneWidget);
// The CLI hands one over; nothing about the screen should change.
@@ -248,6 +255,8 @@ void main() {
app.pendingAuthorizeUrl = null;
app.notifyListeners();
await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text('Signing in…'), findsOneWidget);
+ expect(find.text('Copy link'), findsNothing);
expect(find.byType(WelcomeWorkspacePreview), findsOneWidget);
});
diff --git a/desktop/test/signin_recovery_test.dart b/desktop/test/signin_recovery_test.dart
new file mode 100644
index 000000000..da25fc1e0
--- /dev/null
+++ b/desktop/test/signin_recovery_test.dart
@@ -0,0 +1,274 @@
+import 'dart:async';
+
+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/auth/cli_login.dart';
+import 'package:harness/core/config.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';
+
+class _Attempt {
+ _Attempt(this.authorize);
+ final void Function(String) authorize;
+ final done = Completer<void>();
+}
+
+class _Cli extends CliLogin {
+ final attempts = <_Attempt>[];
+ var cancellations = 0;
+ var statusChecks = 0;
+ @override
+ Future<void> login({required void Function(String) onAuthorizeUrl}) {
+ final attempt = _Attempt(onAuthorizeUrl);
+ attempts.add(attempt);
+ return attempt.done.future;
+ }
+
+ @override
+ Future<CliAuthStatus> checkStatus() async {
+ statusChecks++;
+ throw StateError('A stale fixture login must not bootstrap');
+ }
+
+ @override
+ void cancel() => cancellations++;
+}
+
+class _App extends AppNotifier {
+ _App(_Cli cli)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLogin: cli,
+ ) {
+ status = AppStatus.unauthenticated;
+ }
+ var daemonChecks = 0;
+ Completer<void>? daemon;
+ @override
+ Future<void> ensureCliDaemonReady() async {
+ daemonChecks++;
+ if (daemon == null) throw StateError('Unexpected fixture bootstrap');
+ await daemon!.future;
+ }
+}
+
+_App _app(_Cli cli) => _App(cli);
+
+const _browser = MethodChannel('plugins.flutter.io/url_launcher');
+const _platform = SystemChannels.platform;
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ testWidgets(
+ 'keyboard sign-in can reopen and copy its link without restarting login',
+ (tester) async {
+ final cli = _Cli();
+ final app = _app(cli);
+ final launches = <String>[];
+ String? clipboard;
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(_browser, (
+ call,
+ ) async {
+ expect(call.method, 'launch');
+ final args = call.arguments as Map;
+ expect(args['useWebView'], isFalse);
+ expect(args['useSafariVC'], isFalse);
+ launches.add(args['url'] as String);
+ return launches.length > 1;
+ });
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ _platform,
+ (call) async {
+ if (call.method == 'Clipboard.setData') {
+ clipboard = (call.arguments as Map)['text'] as String;
+ }
+ return null;
+ },
+ );
+ addTearDown(() {
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ _browser,
+ null,
+ );
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ _platform,
+ null,
+ );
+ });
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(880, 800);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => LoginScreen(notifier: app),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(cli.attempts, hasLength(1));
+ expect(find.text('Signing in…'), findsOneWidget);
+ expect(find.text('Copy link'), findsNothing);
+ const url = 'https://auth.example/authorize?state=fixture';
+ cli.attempts.single.authorize(url);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.textContaining('Couldn’t open your browser'), findsOneWidget);
+ expect(app.signingIn, isTrue);
+ await tester.tap(find.text('Open browser'));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(launches, [url, url]);
+ expect(cli.attempts, hasLength(1));
+ expect(app.loginBrowserError, isNull);
+ await tester.tap(find.text('Copy link'));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(clipboard, url);
+ expect(find.text('Link copied'), findsOneWidget);
+ await tester.tap(find.text('Cancel'));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(app.signingIn, isFalse);
+ expect(app.status, AppStatus.unauthenticated);
+ expect(app.lastError, isNull);
+ expect(find.text('Sign in'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(cli.attempts, hasLength(2));
+ // An old result cannot finish the replacement or open a stale browser tab.
+ cli.attempts.first.authorize('https://auth.example/stale');
+ cli.attempts.first.done.complete();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(app.signingIn, isTrue);
+ expect(cli.statusChecks, 0);
+ expect(app.daemonChecks, 0);
+ expect(launches, [url, url]);
+ app.cancelLogin();
+ cli.attempts.last.done.complete();
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ test('Cancel before a URL is immediate and ignores a late success', () async {
+ final cli = _Cli();
+ final app = _app(cli);
+ addTearDown(app.dispose);
+ final login = app.login();
+ app.cancelLogin();
+ expect(app.signingIn, isFalse);
+ expect(app.status, AppStatus.unauthenticated);
+ expect(cli.cancellations, 1);
+ cli.attempts.single.authorize('https://auth.example/stale');
+ cli.attempts.single.done.complete();
+ await login;
+ expect(app.pendingAuthorizeUrl, isNull);
+ expect(app.lastError, isNull);
+ expect(cli.statusChecks, 0);
+ expect(app.daemonChecks, 0);
+ });
+
+ test(
+ 'completed browser sign-in clears recovery before restoring the workspace',
+ () async {
+ final cli = _Cli();
+ final app = _app(cli)..daemon = Completer<void>();
+ addTearDown(app.dispose);
+ final login = app.login();
+ cli.attempts.single.done.complete();
+ await Future<void>.delayed(Duration.zero);
+ expect(app.signingIn, isTrue);
+ expect(app.canCancelLogin, isFalse);
+ expect(app.pendingAuthorizeUrl, isNull);
+ app.cancelLogin();
+ expect(app.status, AppStatus.bootstrapping);
+ expect(cli.cancellations, 0);
+ app.daemon!.completeError(StateError('Fixture service unavailable'));
+ await login;
+ expect(app.signingIn, isFalse);
+ },
+ );
+
+ for (final replace in [false, true]) {
+ test(
+ 'late browser failure belongs to its original ${replace ? 'login' : 'URL'}',
+ () async {
+ final cli = _Cli();
+ final app = _app(cli);
+ addTearDown(app.dispose);
+ final replies = <Completer<bool>>[];
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(_browser, (_) {
+ final reply = Completer<bool>();
+ replies.add(reply);
+ return reply.future;
+ });
+ addTearDown(
+ () => TestDefaultBinaryMessengerBinding
+ .instance
+ .defaultBinaryMessenger
+ .setMockMethodCallHandler(_browser, null),
+ );
+ final first = app.login();
+ cli.attempts.first.authorize('https://auth.example/first');
+ await Future<void>.delayed(Duration.zero);
+ await app
+ .openLoginBrowser(); // A held/repeated action shares this handoff.
+ expect(replies, hasLength(1));
+ Future<void>? second;
+ if (replace) {
+ app.cancelLogin();
+ second = app.login();
+ }
+ cli.attempts.last.authorize('https://auth.example/current');
+ await Future<void>.delayed(Duration.zero);
+ expect(replies, hasLength(2));
+ replies.last.complete(true);
+ await Future<void>.delayed(Duration.zero);
+ replies.first.complete(false);
+ await Future<void>.delayed(Duration.zero);
+ expect(app.loginBrowserError, isNull);
+ expect(app.openingLoginBrowser, isFalse);
+ expect(app.pendingAuthorizeUrl, 'https://auth.example/current');
+ app.cancelLogin();
+ for (final attempt in cli.attempts) {
+ attempt.done.complete();
+ }
+ await first;
+ await second;
+ },
+ );
+ }
+
+ test('browser exceptions stay recoverable and disposal cancels the pending login', () async {
+ final cli = _Cli();
+ final app = _app(cli);
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(_browser, (_) async {
+ throw PlatformException(code: 'browser_unavailable');
+ });
+ addTearDown(
+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(_browser, null),
+ );
+ final login = app.login();
+ cli.attempts.single.authorize('https://auth.example/current');
+ await Future<void>.delayed(Duration.zero);
+ expect(app.signingIn, isTrue);
+ expect(app.loginBrowserError, contains('Couldn’t open your browser'));
+ expect(app.lastError, isNull);
+ app.dispose();
+ expect(cli.cancellations, 1);
+ cli.attempts.single.done.complete();
+ await login;
+ expect(cli.statusChecks, 0);
+ });
+}
diff --git a/docs/harness-v2-appearance-onboarding.md b/docs/harness-v2-appearance-onboarding.md
index 1135aa2ff..fccb655ef 100644
--- a/docs/harness-v2-appearance-onboarding.md
+++ b/docs/harness-v2-appearance-onboarding.md
@@ -95,6 +95,30 @@ were inspected at 1280×800 and at 880×560 with 2× text. These are synthetic U
checks; first-install/provider-sign-in observation and measured time to a useful
real agent remain release qualification work.
+## Browser sign-in recovery
+
+Sign-in keeps its workspace example and action in the same card through CLI
+startup, browser authorization and workspace restoration. It now offers
+**Open browser** and **Copy link** when an authorization URL is available.
+Reopening reuses that URL; it does not launch a second CLI sign-in. Browser
+launch failure stays recoverable in place, with no raw URL or platform error
+rendered in the message.
+
+**Cancel** returns immediately, including while the CLI process is still
+starting. An obsolete process cannot publish a link, finish a replacement login
+or clear its process handle. Browser responses likewise belong to their original
+attempt and URL. After authorization succeeds, browser recovery and Cancel
+disappear while the workspace restores. The initial Sign in button takes keyboard
+focus; cancellation returns focus there so Enter can try again.
+
+The minimum-height layout keeps the normal-size controls visible at 880×560.
+Large text wraps the actions within the existing scrollable card. Sixty-four
+affected workflow tests and one real-font render check pass, with minimum-size,
+2× text and synthetic light/dark review. The shipping app remains dark-only.
+Analysis has no errors/warnings and 14 existing infos; the normal arm64 Release
+build succeeds. These checks use fake subprocess, browser and clipboard replies.
+Real first-install, provider sign-in and time to a useful agent remain unverified.
+
## Earlier onboarding evidence and direction (historical)
| Primary source | Observed behavior | Harness adaptation |
diff --git a/docs/harness-v2-handoff.md b/docs/harness-v2-handoff.md
index 1307bb787..1d74eb172 100644
--- a/docs/harness-v2-handoff.md
+++ b/docs/harness-v2-handoff.md
@@ -40,6 +40,14 @@ query back to Add and retains its original swarm/split. A closed swarm or change
split gets an explanation instead of redirecting the addition. A background
empty tab cannot take focus from the open creation dialog.
+Browser sign-in now offers **Open browser**, **Copy link** and immediate **Cancel**
+while waiting for authorization. Reopening uses the current link without starting
+another CLI login. Cancel works even before the CLI finishes starting; late URLs,
+results and browser replies cannot affect a replacement attempt. After browser
+authorization succeeds, those controls disappear while the workspace restores.
+Enter starts sign-in and can start again after cancellation. Live first-install
+and provider sign-in still need direct observation.
+
## Goal
Build the best everyday workspace for people directing persistent AI agents:
@@ -64,6 +72,17 @@ Research must lead to justified improvements, not feature accumulation.
- Continue on **`main`**, tracking `origin/main`. The user's latest instruction
is to work, commit, and push directly on main from now on. This supersedes
the earlier preference for creating a fresh feature branch after each merge.
+- The browser-sign-in recovery continuation passes 64 affected workflow checks
+ plus one real-font render check (65 total), including late process startup,
+ cancelled/replaced sign-ins, browser launch failure, clipboard recovery,
+ keyboard retry and the authorization-to-workspace boundary. Analysis has zero
+ errors/warnings and 14 existing infos. Minimum-size and 2× text renders were
+ reviewed. Logs: `/private/tmp/harness-signin-final-{tests,analyze}.log`.
+ The normal arm64 Release build succeeds at
+ `/private/tmp/harness-signin-release/Build/Products/Release/Harness.app`;
+ log: `/private/tmp/harness-signin-release.log`. It was not launched. The team's
+ `b45c156` CLI recap change was fast-forwarded from main and does not overlap
+ this desktop work. No real sign-in, agent restart or benchmark ran.
- The creation-to-Add continuation passes 87 affected workflow tests, including
six new keyboard/destination regressions, plus a real-font render check at
880×560 with normal and 2× text. Analysis has zero errors/warnings and the same
@@ -501,6 +520,9 @@ that its isolated window can become active/key.
machine/project starters are implemented. Check fresh dependencies, provider sign-in, cloning,
first task and adding a second agent; improve what the observation exposes.
Preserve choices on failure and the distinction between Navigate and Add.
+ Browser reopen/copy/cancel recovery is implemented with isolated subprocess
+ and platform fixtures. Check the real browser handoff and provider return;
+ do not infer live sign-in success from fixture results.
Creation recovery is implemented and tested with isolated replies. Verify a
deliberately delayed remote create on a disposable agent, including an older
CLI and a changed original swarm. A status check must remain read-only. A
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index f0cf9f71f..d309aa502 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -6,6 +6,21 @@ Updated 2026-09-14 after integrating the continuation into main. This is a worki
## Continue directly on main
+- Added browser-sign-in recovery: **Open browser** reuses the current link,
+ **Copy link** offers a fallback, and **Cancel** immediately restores Sign in
+ with keyboard focus. Cancellation before CLI startup, late authorization URLs,
+ old results and delayed browser replies cannot disturb a replacement login.
+ Recovery controls disappear after authorization succeeds, while the workspace
+ restores. The compact layout keeps the normal-size actions visible at 880×560;
+ larger text wraps in the existing scrollable card. The affected workflow/render
+ suite passes 65 checks; analysis has zero errors/warnings and 14 existing infos.
+ Logs: `/private/tmp/harness-signin-final-{tests,analyze}.log`. The normal arm64
+ Release build succeeds at
+ `/private/tmp/harness-signin-release/Build/Products/Release/Harness.app`;
+ log: `/private/tmp/harness-signin-release.log`. It was not launched. The team's
+ `b45c156` main update changes CLI recap text and does not overlap this work.
+ Real first-install/provider sign-in and remote workflow checks remain open;
+ Archive/Resume remains a proposal and benchmarking remains deferred.
- Added **Find existing agent…** to uncertain New agent forms. It opens shared
Add with the search query, original swarm and split preserved; a closed swarm
or stale split gets an explanation. The dialog releases keyboard ownership