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.

Desktop first-run sign-in: phone scan, a code for another device, Email/GitHub/passkey button (#2438)

0xken15c20ef1b5f5ca
diff --git a/desktop/integration_test/sign_in_native_test.dart b/desktop/integration_test/sign_in_native_test.dart
index 955a280ed..959435a0f 100644
--- a/desktop/integration_test/sign_in_native_test.dart
+++ b/desktop/integration_test/sign_in_native_test.dart
@@ -434,18 +434,18 @@ void main() {
expect(find.text(benefit.line), findsOneWidget);
}
expect(find.text('Sign in to continue.'), findsOneWidget);
- // Email is centered under the standalone buttons, and no Skip remains.
+ // Email, GitHub or passkey is a button of their width under the two
+ // accounts; a phone's scan and a code follow. No Skip remains.
final google = tester.getRect(_google);
expect(tester.getRect(_apple).left, google.left);
expect(find.text('Skip'), findsNothing);
- expect(
- tester.getRect(find.text('Continue with email')).center.dx,
- moreOrLessEquals(google.center.dx, epsilon: 0.5),
- );
+ expect(tester.getRect(_email).width, google.width);
expect(
tester.getRect(_email).top,
greaterThan(tester.getRect(_apple).bottom),
);
+ expect(find.text('Scan with your phone'), findsOneWidget);
+ expect(find.text('Sign in on another device'), findsOneWidget);
expect(tester.takeException(), isNull);
await _shot(tester, '2-sign-in-page');
diff --git a/desktop/lib/auth/cli_login.dart b/desktop/lib/auth/cli_login.dart
index d2a5f9fc3..05d8c57d8 100644
--- a/desktop/lib/auth/cli_login.dart
+++ b/desktop/lib/auth/cli_login.dart
@@ -62,7 +62,7 @@ class CliSignOutUnderTestError extends Error {
/// 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, PhoneSignInClient {
+class CliLogin implements SignInClient, PhoneSignInClient, CodeSignInClient {
final HarnessCliRunner _runner;
Process? _activeProcess;
int _loginRevision = 0;
@@ -116,12 +116,23 @@ class CliLogin implements SignInClient, PhoneSignInClient {
required Future<bool> Function(String email) onConfirm,
}) => _login(const ['--qr'], onQr: onQr, onConfirm: onConfirm);
+ /// `harness login --code`: a short code another signed-in device types in, in place of the QR;
+ /// each `code` event is the code to show, the account question as for [loginWithPhone].
+ @override
+ Future<void> loginWithCode({
+ required void Function(String code, int expiresIn) onCode,
+ required Future<bool> Function(String email) onConfirm,
+ }) => _login(const ['--code'], onCode: onCode, onConfirm: onConfirm);
+
Future<void> _login(
List<String> extra, {
void Function(String url)? onAuthorizeUrl,
void Function(String link, int expiresIn)? onQr,
+ void Function(String code, int expiresIn)? onCode,
Future<bool> Function(String email)? onConfirm,
}) async {
+ // Approved from another device — a phone's scan, or a code typed there — rather than in a browser.
+ final approval = onQr != null || onCode != null;
// A cancelled spawn can finish after a replacement login has started.
// Each process owns only its attempt, including its eventual cleanup.
final revision = ++_loginRevision;
@@ -174,9 +185,10 @@ class CliLogin implements SignInClient, PhoneSignInClient {
final note = json['message'];
if (note is String && note.isNotEmpty) waitingNote.value = note;
case 'authorize_url':
- // Asked for a QR and given a browser page: a CLI from before `--qr`, which ignores the
- // flag and starts SSO. Nothing would ever be shown — stop it and say why.
- if (onQr != null) {
+ // Asked for a QR or a code and given a browser page: a CLI from before `--qr` or
+ // `--code`, which ignores the flag and starts SSO. Nothing would ever be shown — stop it
+ // and say why.
+ if (approval) {
tooOld = true;
process.kill();
break;
@@ -188,6 +200,11 @@ class CliLogin implements SignInClient, PhoneSignInClient {
if (url is String) {
onQr?.call(url, expiresIn is int ? expiresIn : 120);
}
+ case 'code':
+ final shown = json['code'], expiresIn = json['expiresIn'];
+ if (shown is String) {
+ onCode?.call(shown, expiresIn is int ? expiresIn : 120);
+ }
case 'confirm':
final email = json['email'];
final yes =
@@ -207,9 +224,9 @@ class CliLogin implements SignInClient, PhoneSignInClient {
throw StateError('Sign-in was cancelled.');
}
if (tooOld) {
- throw const PhoneSignInException(
+ throw PhoneSignInException(
'CLI_TOO_OLD',
- 'This computer\'s Harness CLI is too old to sign in with a phone. Continue with Google or Apple, or update Harness.',
+ 'This computer\'s Harness CLI is too old to sign in with ${onCode != null ? 'a code' : 'a phone'}. Continue with Google or Apple, or update Harness.',
);
}
if (!gotResult || !success) {
@@ -219,12 +236,12 @@ class CliLogin implements SignInClient, PhoneSignInClient {
? 'Sign-in was cancelled.'
: 'Sign-in did not complete.');
// A phone sign-in says why it ended, so the screen can offer the right next step.
- if (onQr != null && code != null) {
+ if (approval && code != null) {
throw PhoneSignInException(code, text);
}
// A browser one says so too, for the count of why sign-ins did not go through. A CLI that
// ended without a result line crashed or was killed: that is a reason of its own.
- if (onQr == null && (code != null || !gotResult)) {
+ if (!approval && (code != null || !gotResult)) {
throw SignInException(code ?? 'NO_RESULT', text);
}
throw StateError(text);
diff --git a/desktop/lib/auth/phone_sign_in.dart b/desktop/lib/auth/phone_sign_in.dart
index 5b0b67dd4..65bb9e45c 100644
--- a/desktop/lib/auth/phone_sign_in.dart
+++ b/desktop/lib/auth/phone_sign_in.dart
@@ -12,6 +12,22 @@ abstract interface class PhoneSignInClient {
});
}
+/// Signing in by a short code another signed-in device approves: a phone (Settings ▸ Sign in a
+/// computer ▸ Type a code instead) or a computer (Machines ▸ Approve a device). The same approval as
+/// the QR (backend `routes/qrSignIn.ts`), for a computer whose screen a phone cannot reach — a remote
+/// one — or a person with no phone at hand. The CLI's (`harness login --code`).
+abstract interface class CodeSignInClient {
+ /// Shows [onCode] the code to type (again, whenever its life is extended), waits for a device to
+ /// approve it, then asks [onConfirm] whose account it is, as [PhoneSignInClient.loginWithPhone].
+ Future<void> loginWithCode({
+ required void Function(String code, int expiresIn) onCode,
+ required Future<bool> Function(String email) onConfirm,
+ });
+}
+
+/// The two ways in another device approves: a phone scanning the QR, or a code typed elsewhere.
+enum ApprovalSignIn { phone, code }
+
/// Why a phone sign-in did not finish. [code]: `DENIED` (on the phone), `EXPIRED`, `CANCELLED`
/// (the person here said no, or went back), `BACKEND_ERROR`, `UNAVAILABLE` (a backend without it).
class PhoneSignInException implements Exception {
diff --git a/desktop/lib/screens/login_screen.dart b/desktop/lib/screens/login_screen.dart
index f9002997b..dcac9003a 100644
--- a/desktop/lib/screens/login_screen.dart
+++ b/desktop/lib/screens/login_screen.dart
@@ -6,9 +6,9 @@ import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart';
import '../auth/sign_in_provider.dart';
-import '../shared/widgets/qr_code_view.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
+import '../widgets/approval_sign_in_panel.dart';
import '../widgets/finger_target.dart' show kFingerTarget;
import '../widgets/login_fleet_map.dart';
import '../widgets/login_relay_diagram.dart';
@@ -367,84 +367,21 @@ class _ActionState extends State<_Action> {
);
}
- // A phone approved this sign-in: whose account is it? Someone else's phone may have scanned
- // the code, and nothing is signed in until the person here says yes.
- if (notifier.pendingConfirmEmail case final email?) {
- final previous = notifier.previousAccountEmail;
- final changed =
- previous != null && previous.toLowerCase() != email.toLowerCase();
- return Column(
- children: [
- Text(
- 'Sign in as $email?',
- key: const Key('login-phone-confirm'),
- textAlign: TextAlign.center,
- style: grid.AppType.heading(),
- ),
- const SizedBox(height: 8),
- Text(
- changed
- ? 'This computer was signed in as $previous. Continue only if $email is yours.'
- : 'Your phone approved this sign-in. Continue only if this is your account.',
- textAlign: TextAlign.center,
- style: Theme.of(context).textTheme.bodySmall
- ?.copyWith(color: changed ? grid.AppPalette.warn : null),
- ),
- const SizedBox(height: 14),
- Wrap(
- spacing: 8,
- alignment: WrapAlignment.center,
- children: [
- FilledButton(
- key: const Key('login-phone-continue'),
- autofocus: true,
- onPressed: () => notifier.confirmPhoneSignIn(true),
- child: const Text('Continue'),
- ),
- TextButton(
- key: const Key('login-phone-refuse'),
- onPressed: () => notifier.confirmPhoneSignIn(false),
- child: const Text('Cancel'),
- ),
- ],
- ),
- ],
- );
- }
-
- // Waiting for a phone to scan the QR.
- if (notifier.pendingQrLink case final link?) {
+ // A phone scanning the QR, then whose account approved it: someone else's phone may have
+ // scanned the code, and nothing is signed in until the person here says yes.
+ if (notifier.approvalSignIn case final method?) {
return _RevealOnShow(
- child: Column(
- children: [
- QrCodeView(
- key: const Key('login-phone-qr'),
- data: link,
- side: 200,
- semanticLabel: 'QR code to sign in with your phone',
- ),
- const SizedBox(height: 12),
- Text(
- 'On your phone: Harness ▸ Settings ▸ Sign in a computer',
- textAlign: TextAlign.center,
- style: Theme.of(context).textTheme.bodySmall,
- ),
- const SizedBox(height: 12),
- Wrap(
- spacing: 8,
- alignment: WrapAlignment.center,
- children: [
- // Back to the two buttons: that is where the browser's way in is chosen.
- TextButton(
- onPressed: notifier.cancelLogin,
- style: TextButton.styleFrom(
- foregroundColor: grid.AppPalette.textSecondary,
- ),
- child: const Text('Cancel'),
- ),
- ],
- ),
- ],
+ child: ApprovalSignInPanel(
+ method: method,
+ qrLink: notifier.pendingQrLink,
+ code: notifier.pendingSignInCode,
+ refreshAt: notifier.approvalRefreshAt,
+ confirmEmail: notifier.pendingConfirmEmail,
+ previousEmail: notifier.previousAccountEmail,
+ answered: notifier.approvalAnswered,
+ onConfirm: notifier.confirmPhoneSignIn,
+ // Back to the ways in: that is where the browser's way in is chosen.
+ onCancel: notifier.cancelLogin,
),
);
}
diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dart
index 7a03d51e4..4d898d94d 100644
--- a/desktop/lib/shared/theme/app_icons.dart
+++ b/desktop/lib/shared/theme/app_icons.dart
@@ -123,6 +123,7 @@ abstract final class AppIcons {
static const info = LucideIcons.info400;
static const keyboard = LucideIcons.keyboard400;
static const laptop = LucideIcons.laptop400;
+ static const mail = LucideIcons.mail400;
static const layers = LucideIcons.layers400;
static const layoutGrid = LucideIcons.layoutGrid400;
static const link2 = LucideIcons.link2400;
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index a4e0ac60d..f0149719e 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -17,6 +17,7 @@ import 'dart:io'
show Directory, FileSystemEntity, FileSystemEntityType, Platform, exit, pid;
import 'dart:math' show Random, min;
+import 'package:clock/clock.dart';
import 'package:dio/dio.dart';
import 'dart:ui'
@@ -1387,7 +1388,7 @@ class AppNotifier extends ChangeNotifier {
/// The sign-in step's buttons. Unlike the sign-in sheet, the page does not
/// change while the browser is open, so every way in stays live: pressing
/// one again opens the browser again, and another one switches to it.
- /// No [provider] is the sign-in page's own chooser — Continue with email.
+ /// No [provider] is the sign-in page's own chooser — Email, GitHub or passkey.
Future<void> signInFromStep([SignInProvider? provider]) async {
if (signingIn) {
// The same way in, pressed again: its page again, not a second sign-in
@@ -4823,6 +4824,9 @@ class AppNotifier extends ChangeNotifier {
/// Whether this build can sign in by a phone at all (the CLI's, and a viewer's, can).
bool get canSignInWithPhone => cliLogin is PhoneSignInClient;
+ /// Whether this build can sign in by a code another device types in (the CLI's can).
+ bool get canSignInWithCode => cliLogin is CodeSignInClient;
+
/// What a sign-in in progress is waiting on before it can start — another sign-in on this
/// computer, say — for the login screen to show; null when it is not waiting.
String? get loginWaitingNote => switch (cliLogin) {
@@ -8271,7 +8275,9 @@ class AppNotifier extends ChangeNotifier {
Object error,
int revision,
) {
- final reason = !_authWorkCurrent(revision)
+ final reason = revision == _refreshedAuthRevision
+ ? SignInEndReason.expired
+ : !_authWorkCurrent(revision)
? SignInEndReason.cancelled
: switch (error) {
SignInException(:final code) || PhoneSignInException(:final code) =>
@@ -8796,17 +8802,71 @@ class AppNotifier extends ChangeNotifier {
}
/// Sign in by a QR a signed-in phone approves, then a yes here to the account it names.
- Future<void> loginWithPhone() async {
+ Future<void> loginWithPhone() => _loginByApproval(ApprovalSignIn.phone);
+
+ /// Sign in by a short code another signed-in device types in — a phone's Settings ▸ Sign in a
+ /// computer ▸ Type a code instead, or a computer's Machines ▸ Approve a device — then a yes here.
+ Future<void> loginWithCode() => _loginByApproval(ApprovalSignIn.code);
+
+ /// The sign-in step's Scan with your phone and Sign in on another device. As [signInFromStep]:
+ /// another way in under way ends and this one begins; the same one again changes nothing.
+ Future<void> approveFromStep(ApprovalSignIn method) async {
+ if (signingIn) {
+ if (approvalSignIn == method) return;
+ if (!canCancelLogin) return;
+ cancelLogin();
+ }
+ await _loginByApproval(method);
+ }
+
+ /// A code's whole life at the backend, however often it is kept alive (`QR_SIGN_IN_MAX_LIFE_SEC`
+ /// in backend `lib/harnessSession.ts`). Scholes's code ran out twice before he could type it
+ /// (2026-10-31): the page swaps in a new one before then instead of showing a dead one.
+ static const approvalCodeLife = Duration(minutes: 10);
+
+ /// How long before a code's end the page swaps in the next: time for the swap itself, so the
+ /// code on screen is always one that still works.
+ static const approvalRefreshLead = Duration(seconds: 15);
+
+ /// How many new codes a page left open gets before it stops asking (about an hour of them).
+ /// Each is a sign-in record at the backend; a window nobody is looking at should not make them
+ /// all night.
+ static const maxApprovalRefreshes = 6;
+
+ /// The approval sign-in under way, if any: what the step shows in place of its ways in.
+ ApprovalSignIn? approvalSignIn;
+
+ /// The code to type on another device ([loginWithCode]) while it waits for one to approve it.
+ String? pendingSignInCode;
+
+ /// When the page swaps in a new QR or code, for its "New code in" line. Null before the first.
+ DateTime? approvalRefreshAt;
+
+ Timer? _approvalRefresh;
+ int _approvalRefreshes = 0;
+
+ /// The attempt a refresh replaced: counted as expired, not as the person cancelling.
+ int? _refreshedAuthRevision;
+
+ Future<void> _loginByApproval(
+ ApprovalSignIn method, {
+ bool refreshing = false,
+ }) async {
final client = cliLogin;
+ final supported = switch (method) {
+ ApprovalSignIn.phone => client is PhoneSignInClient,
+ ApprovalSignIn.code => client is CodeSignInClient,
+ };
if (_disposed ||
- signingIn ||
+ (signingIn && !refreshing) ||
signingOut ||
signOutError != null ||
- client is! PhoneSignInClient) {
+ !supported) {
return;
}
final finish = productMeasurement.begin(ProductFlow.signIn);
var signedInHere = false;
+ var refreshAfter = false;
final wasGuest = isGuest;
final revision = _invalidateAuthWork();
previousAccountEmail = currentUser?.email;
@@ -8818,26 +8878,70 @@ class AppNotifier extends ChangeNotifier {
signInProvider = null;
pendingAuthorizeUrl = null;
_clearPhoneSignIn();
+ approvalSignIn = method;
+ if (!refreshing) _approvalRefreshes = 0;
notifyListeners();
+ // When this attempt's code first showed, and how long a fresh one lives: the start of its
+ // backend life, and the measure of a "less than usual" time left near its end.
+ DateTime? shownAt;
+ int? fullLife;
+ void shown(int expiresIn) {
+ final now = clock.now();
+ shownAt ??= now;
+ fullLife ??= expiresIn;
+ var end = shownAt!.add(approvalCodeLife);
+ // Less than a fresh code's time left: the backend is near the end of its life, whatever this
+ // page assumes that life to be.
+ final reported = now.add(Duration(seconds: expiresIn));
+ if (expiresIn < fullLife! && reported.isBefore(end)) end = reported;
+ final refreshAt = end.subtract(approvalRefreshLead);
+ if (refreshAt == approvalRefreshAt) return;
+ approvalRefreshAt = refreshAt;
+ _approvalRefresh?.cancel();
+ final wait = refreshAt.difference(now);
+ _approvalRefresh = Timer(
+ wait.isNegative ? Duration.zero : wait,
+ () => _refreshApproval(revision),
+ );
+ }
+
try {
if (_workspaceCleanup case final cleanup?) {
await cleanup;
if (!_authWorkCurrent(revision)) return;
}
- await (client as PhoneSignInClient).loginWithPhone(
- onQr: (link, _) {
- if (!_authWorkCurrent(revision) || pendingQrLink == link) return;
- pendingQrLink = link;
- notifyListeners();
- },
- onConfirm: (email) {
- if (!_authWorkCurrent(revision)) return Future.value(false);
- final answer = _phoneConfirm = Completer<bool>();
- pendingConfirmEmail = email;
- notifyListeners();
- return answer.future;
- },
- );
+ Future<bool> confirm(String email) {
+ if (!_authWorkCurrent(revision)) return Future.value(false);
+ final answer = _phoneConfirm = Completer<bool>();
+ pendingConfirmEmail = email;
+ notifyListeners();
+ return answer.future;
+ }
+
+ switch (method) {
+ case ApprovalSignIn.phone:
+ await (client as PhoneSignInClient).loginWithPhone(
+ onQr: (link, expiresIn) {
+ if (!_authWorkCurrent(revision)) return;
+ shown(expiresIn);
+ if (pendingQrLink == link) return;
+ pendingQrLink = link;
+ notifyListeners();
+ },
+ onConfirm: confirm,
+ );
+ case ApprovalSignIn.code:
+ await (client as CodeSignInClient).loginWithCode(
+ onCode: (code, expiresIn) {
+ if (!_authWorkCurrent(revision)) return;
+ shown(expiresIn);
+ if (pendingSignInCode == code) return;
+ pendingSignInCode = code;
+ notifyListeners();
+ },
+ onConfirm: confirm,
+ );
+ }
if (!_authWorkCurrent(revision)) return;
finish(ProductOutcome.ok);
signedInHere = true;
@@ -8853,11 +8957,23 @@ class AppNotifier extends ChangeNotifier {
} catch (error) {
if (!signedInHere) _measureSignInEnd(finish, error, revision);
if (!_authWorkCurrent(revision)) return;
- status = wasGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
- _lastError = error.toString();
- _lastErrorRetryable = true;
- if (wasGuest && _guestDeskRestorePending && !signedIn) {
- unawaited(_becomeGuest(revision: revision));
+ // The code ran out before anyone used it (or while the person answered): a new one, on the
+ // same page, until the bound.
+ if (!signedInHere &&
+ error is PhoneSignInException &&
+ error.code == 'EXPIRED' &&
+ _approvalRefreshes < maxApprovalRefreshes) {
+ refreshAfter = true;
+ } else {
+ status = wasGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
+ _lastError =
+ error is PhoneSignInException && error.code == 'EXPIRED'
+ ? _approvalRanOut
+ : error.toString();
+ _lastErrorRetryable = true;
+ if (wasGuest && _guestDeskRestorePending && !signedIn) {
+ unawaited(_becomeGuest(revision: revision));
+ }
}
} finally {
finish(
@@ -8871,21 +8987,78 @@ class AppNotifier extends ChangeNotifier {
signingIn = false;
}
}
+ if (refreshAfter && _authWorkCurrent(revision)) {
+ _approvalRefreshes++;
+ // Synchronously up to its first wait, so no frame shows the ways in between the two codes.
+ unawaited(_loginByApproval(method, refreshing: true));
+ return;
+ }
if (_authWorkCurrent(revision)) notifyListeners();
}
+ static const _approvalRanOut =
+ 'The code ran out. Choose a way to sign in when you are ready.';
+
+ /// The QR or code on screen is about to end: replace it with a new one, unless the person is
+ /// answering whose account approved it — that answer belongs to this code.
+ void _refreshApproval(int revision) {
+ final method = approvalSignIn;
+ if (!_authWorkCurrent(revision) ||
+ !signingIn ||
+ method == null ||
+ pendingConfirmEmail != null ||
+ approvalAnswered) {
+ return;
+ }
+ _refreshedAuthRevision = revision;
+ if (_approvalRefreshes >= maxApprovalRefreshes) {
+ // Out of new codes: back to the ways in, saying why, with no dead code left on screen.
+ final next = _invalidateAuthWork();
+ signingIn = false;
+ _clearPhoneSignIn();
+ status = isGuest ? AppStatus.authenticated : AppStatus.unauthenticated;
+ _lastError = _approvalRanOut;
+ _lastErrorRetryable = true;
+ cliLogin.cancel();
+ notifyListeners();
+ if (isGuest && _guestDeskRestorePending) {
+ unawaited(_becomeGuest(revision: next));
+ }
+ return;
+ }
+ _approvalRefreshes++;
+ cliLogin.cancel();
+ unawaited(_loginByApproval(method, refreshing: true));
+ }
+
+ /// The person said yes to the account that approved: the QR or code has done its work, and no new
+ /// one replaces it while the session is claimed.
+ bool approvalAnswered = false;
+
/// The person's answer to "Sign in as [pendingConfirmEmail]?".
void confirmPhoneSignIn(bool yes) {
final answer = _phoneConfirm;
_phoneConfirm = null;
pendingConfirmEmail = null;
+ if (yes && answer != null && !answer.isCompleted) {
+ approvalAnswered = true;
+ approvalRefreshAt = null;
+ _approvalRefresh?.cancel();
+ _approvalRefresh = null;
+ }
if (answer != null && !answer.isCompleted) answer.complete(yes);
notifyListeners();
}
void _clearPhoneSignIn() {
pendingQrLink = null;
+ pendingSignInCode = null;
pendingConfirmEmail = null;
+ approvalSignIn = null;
+ approvalAnswered = false;
+ approvalRefreshAt = null;
+ _approvalRefresh?.cancel();
+ _approvalRefresh = null;
final answer = _phoneConfirm;
_phoneConfirm = null;
if (answer != null && !answer.isCompleted) answer.complete(false);
@@ -8993,6 +9166,7 @@ class AppNotifier extends ChangeNotifier {
final previousMachineId = localMachineState?.machine.machineId;
cliLogin.cancel();
signingIn = false;
+ _clearPhoneSignIn();
signingOut = true;
signOutError = null;
_lastError = null;
@@ -22230,6 +22404,7 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
_teamOfferRetry?.cancel();
+ _approvalRefresh?.cancel();
if (identical(CrashLog.healthError, _measurementError)) {
CrashLog.healthError = null;
}
diff --git a/desktop/lib/widgets/approval_sign_in_panel.dart b/desktop/lib/widgets/approval_sign_in_panel.dart
new file mode 100644
index 000000000..dff07bdfb
--- /dev/null
+++ b/desktop/lib/widgets/approval_sign_in_panel.dart
@@ -0,0 +1,343 @@
+import 'dart:async';
+
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../auth/phone_sign_in.dart';
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/qr_code_view.dart';
+
+/// A sign-in another device approves, while it waits: the QR a phone scans or the code typed on a
+/// phone or a computer, where to go there, when a new one comes ([refreshAt]), and then whose account
+/// approved it ([confirmEmail]) — nothing is signed in until the person here says yes.
+///
+/// One panel for every sign-in page that offers these ways in: the first-run page in place of its
+/// buttons (`sign_in_step.dart`), and the web page's (`login_screen.dart`).
+class ApprovalSignInPanel extends StatelessWidget {
+ const ApprovalSignInPanel({
+ super.key,
+ required this.method,
+ required this.onConfirm,
+ required this.onCancel,
+ this.qrLink,
+ this.code,
+ this.refreshAt,
+ this.confirmEmail,
+ this.previousEmail,
+ this.answered = false,
+ });
+
+ final ApprovalSignIn method;
+
+ /// What the phone scans ([ApprovalSignIn.phone]); null until the CLI has made it.
+ final String? qrLink;
+
+ /// What the other device types ([ApprovalSignIn.code]); null until the CLI has made it.
+ final String? code;
+
+ /// When a new QR or code takes this one's place; null when none is coming.
+ final DateTime? refreshAt;
+
+ /// The account that approved it, waiting on the person's answer.
+ final String? confirmEmail;
+
+ /// Who was signed in here before, so the question can say when the account changes.
+ final String? previousEmail;
+
+ /// The person said yes: the session is being claimed, and the QR or code is spent.
+ final bool answered;
+
+ final ValueChanged<bool> onConfirm;
+ final VoidCallback onCancel;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final small = Theme.of(context).textTheme.bodySmall;
+ if (confirmEmail case final email?) {
+ final changed =
+ previousEmail != null &&
+ previousEmail!.toLowerCase() != email.toLowerCase();
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ 'Sign in as $email?',
+ key: const Key('login-phone-confirm'),
+ textAlign: TextAlign.center,
+ style: grid.AppType.heading(),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ changed
+ ? 'This computer was signed in as $previousEmail. Continue only if $email is yours.'
+ : 'Continue only if this is your account.',
+ textAlign: TextAlign.center,
+ style: small?.copyWith(
+ color: changed ? grid.AppPalette.warn : null,
+ ),
+ ),
+ const SizedBox(height: 14),
+ Wrap(
+ spacing: 8,
+ alignment: WrapAlignment.center,
+ children: [
+ FilledButton(
+ key: const Key('login-phone-continue'),
+ autofocus: true,
+ onPressed: () => onConfirm(true),
+ child: const Text('Continue'),
+ ),
+ TextButton(
+ key: const Key('login-phone-refuse'),
+ onPressed: () => onConfirm(false),
+ child: const Text('Cancel'),
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+
+ final shown = answered
+ ? null
+ : switch (method) {
+ ApprovalSignIn.phone => qrLink,
+ ApprovalSignIn.code => code,
+ };
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (shown == null)
+ _Getting(
+ label: answered
+ ? 'Signing in…'
+ : method == ApprovalSignIn.phone
+ ? 'Getting a QR code…'
+ : 'Getting a code…',
+ )
+ else if (method == ApprovalSignIn.phone) ...[
+ QrCodeView(
+ key: const Key('login-phone-qr'),
+ data: shown,
+ side: 200,
+ semanticLabel: 'QR code to sign in with your phone',
+ ),
+ const SizedBox(height: 12),
+ Text(
+ 'On your phone: Harness ▸ Settings ▸ Sign in a computer',
+ textAlign: TextAlign.center,
+ style: small,
+ ),
+ ] else
+ _Code(code: shown),
+ if (shown != null && refreshAt != null) ...[
+ const SizedBox(height: 10),
+ _NewCodeIn(refreshAt: refreshAt!),
+ ],
+ const SizedBox(height: 12),
+ TextButton(
+ key: const Key('approval-sign-in-cancel'),
+ onPressed: onCancel,
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textSecondary,
+ ),
+ child: const Text('Cancel'),
+ ),
+ ],
+ );
+ }
+}
+
+class _Getting extends StatelessWidget {
+ const _Getting({required this.label});
+
+ final String label;
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ padding: const EdgeInsets.symmetric(vertical: 16),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const SizedBox.square(
+ dimension: 16,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ const SizedBox(width: 10),
+ Flexible(child: Text(label, style: grid.AppType.body())),
+ ],
+ ),
+ );
+}
+
+/// The code in two halves, as the CLI says it, with Copy beside it and where to type it under it.
+class _Code extends StatefulWidget {
+ const _Code({required this.code});
+
+ final String code;
+
+ @override
+ State<_Code> createState() => _CodeState();
+}
+
+class _CodeState extends State<_Code> {
+ /// The code the last Copy put on the clipboard: "Copied" speaks for that code only.
+ String? _copied;
+ bool _copying = false;
+
+ Future<void> _copy() async {
+ final code = widget.code;
+ if (_copying) return;
+ setState(() => _copying = true);
+ var copied = false;
+ try {
+ await Clipboard.setData(ClipboardData(text: code));
+ copied = true;
+ } catch (_) {
+ // The clipboard can be unavailable; the code is still on screen to type.
+ }
+ if (!mounted) return;
+ setState(() {
+ _copying = false;
+ _copied = copied ? code : null;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final code = widget.code;
+ final spoken = code.length == 8
+ ? '${code.substring(0, 4)} ${code.substring(4)}'
+ : code;
+ final small = Theme.of(context).textTheme.bodySmall;
+ final copied = _copied == code;
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Wrap(
+ alignment: WrapAlignment.center,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ spacing: 12,
+ runSpacing: 8,
+ children: [
+ SelectableText(
+ spoken,
+ key: const Key('sign-in-code'),
+ // The app's own face with even-width digits, not the terminal's: a code
+ // read across a room must not change shape with a font setting.
+ style: grid.AppType.display(color: grid.AppPalette.textPrimary)
+ .copyWith(
+ fontSize: 36,
+ fontWeight: FontWeight.w700,
+ letterSpacing: 3,
+ fontFeatures: const [FontFeature.tabularFigures()],
+ ),
+ ),
+ OutlinedButton.icon(
+ key: const Key('sign-in-code-copy'),
+ onPressed: _copying ? null : () => unawaited(_copy()),
+ icon: Icon(copied ? AppIcons.check : AppIcons.copy, size: 14),
+ label: Text(copied ? 'Copied' : 'Copy'),
+ ),
+ ],
+ ),
+ const SizedBox(height: 14),
+ Text(
+ 'Type this code on a device that is signed in:',
+ textAlign: TextAlign.center,
+ style: grid.AppType.body(color: grid.AppPalette.textPrimary),
+ ),
+ const SizedBox(height: 8),
+ _Path(
+ icon: AppIcons.smartphone,
+ where: 'Phone',
+ path: 'Harness ▸ Settings ▸ Sign in a computer ▸ Type a code instead',
+ style: small,
+ ),
+ const SizedBox(height: 6),
+ _Path(
+ icon: AppIcons.laptop,
+ where: 'Computer',
+ path: 'Machines ▸ Approve a device',
+ style: small,
+ ),
+ ],
+ );
+ }
+}
+
+class _Path extends StatelessWidget {
+ const _Path({
+ required this.icon,
+ required this.where,
+ required this.path,
+ required this.style,
+ });
+
+ final IconData icon;
+ final String where;
+ final String path;
+ final TextStyle? style;
+
+ @override
+ Widget build(BuildContext context) => Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(top: 1),
+ child: ExcludeSemantics(
+ child: Icon(icon, size: 14, color: grid.AppPalette.textSecondary),
+ ),
+ ),
+ const SizedBox(width: 8),
+ Text('$where: ', style: style?.copyWith(fontWeight: FontWeight.w600)),
+ Expanded(child: Text(path, style: style)),
+ ],
+ );
+}
+
+/// "New code in 0:45": quiet, ticking each second, so a person typing knows how long they have.
+class _NewCodeIn extends StatefulWidget {
+ const _NewCodeIn({required this.refreshAt});
+
+ final DateTime refreshAt;
+
+ @override
+ State<_NewCodeIn> createState() => _NewCodeInState();
+}
+
+class _NewCodeInState extends State<_NewCodeIn> {
+ Timer? _tick;
+
+ @override
+ void initState() {
+ super.initState();
+ _tick = Timer.periodic(const Duration(seconds: 1), (_) {
+ if (mounted) setState(() {});
+ });
+ }
+
+ @override
+ void dispose() {
+ _tick?.cancel();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final left = widget.refreshAt.difference(clock.now());
+ final seconds = (left.inMilliseconds / 1000).ceil();
+ final line = seconds <= 0
+ ? 'Getting a new code…'
+ : 'New code in ${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}';
+ return Text(
+ line,
+ key: const Key('approval-new-code-in'),
+ style: Theme.of(context).textTheme.bodySmall
+ ?.copyWith(color: grid.AppPalette.textFaint),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/sign_in_step.dart b/desktop/lib/widgets/sign_in_step.dart
index e7a6cc2c2..96467b736 100644
--- a/desktop/lib/widgets/sign_in_step.dart
+++ b/desktop/lib/widgets/sign_in_step.dart
@@ -3,11 +3,14 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
+import '../auth/phone_sign_in.dart';
import '../auth/sign_in_provider.dart';
import '../logging/app_log.dart';
import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
+import 'approval_sign_in_panel.dart';
+import 'or_divider.dart';
import 'quiet_link.dart';
import 'setup_tour.dart';
import 'sign_in_provider_button.dart';
@@ -17,11 +20,15 @@ import 'window_chrome.dart';
/// ([AppNotifier.signInStepShowing]).
///
/// It stands where the tour stood and looks like its last slide: what an
-/// account adds on the left, one line each, and Continue with Google and
-/// Continue with Apple on the right. The buttons stand alone, with Continue
-/// with email centered under them (owner, 2026-10-12).
-/// Nothing else is on the page, and nothing on it changes while the browser is
-/// open — every way in stays live instead (owner, 2026-10-11).
+/// account adds on the left, one line each, and the ways in on the right:
+/// Continue with Google, Continue with Apple, and the browser sign-in page's
+/// other ways (email, GitHub, passkey) as a button of the same size; then,
+/// after OR, Scan with your phone and Sign in on another device — the ways a
+/// new or remote computer signs in with no browser of its own (Scholes's
+/// end-to-end test of 1.3.44, 2026-10-31: a remote computer stopped here).
+/// Nothing on it changes while the browser is open — every way in stays live
+/// instead (owner, 2026-10-11). A scan or code under way takes the ways in's
+/// place ([approval]) until it is approved or cancelled.
/// Design: `docs/research/2026-10-08-onboarding-redesign/index.html`, 1b.
/// The page's two lines of title.
@@ -40,6 +47,8 @@ class SignInStep extends StatelessWidget {
const SignInStep({
super.key,
required this.onSignIn,
+ this.onApprove,
+ this.approval,
this.starting = false,
this.startingProvider,
this.finishing = false,
@@ -51,10 +60,18 @@ class SignInStep extends StatelessWidget {
this.recovery,
});
- /// Continue with Google, Continue with Apple, or — with no provider —
- /// Continue with email, which is the sign-in page's own chooser.
+ /// Continue with Google, Continue with Apple, or — with no provider — Email,
+ /// GitHub or passkey, which is the sign-in page's own chooser.
final ValueChanged<SignInProvider?> onSignIn;
+ /// Scan with your phone, or Sign in on another device. Null where this app
+ /// cannot sign in that way: the page then offers the browser alone.
+ final ValueChanged<ApprovalSignIn>? onApprove;
+
+ /// A scan or a code under way ([ApprovalSignInPanel]): shown in place of the
+ /// ways in.
+ final Widget? approval;
+
/// A sign-in was pressed and its browser has not opened yet. The control
/// that began it ([startingProvider]; none is email) steps back for that
/// moment so the press reads as taken. Its words do not change.
@@ -206,6 +223,8 @@ class SignInStep extends StatelessWidget {
onPressed: onRetrySignOut,
child: const Text('Retry sign out'),
)
+ else if (approval case final approval?)
+ approval
else ...[
for (final provider in SignInProvider.values)
_stepsBack(
@@ -218,17 +237,44 @@ class SignInStep extends StatelessWidget {
onPressed: () => onSignIn(provider),
),
),
- Align(
- alignment: Alignment.center,
- child: _stepsBack(
- starting && startingProvider == null,
- QuietLink(
- key: const Key('sign-in-step-email'),
- label: 'Continue with email',
- onPressed: () => onSignIn(null),
+ // The sign-in page's own chooser: an email and its code, GitHub,
+ // or a passkey. A button named for what it opens, not small print.
+ _stepsBack(
+ starting && startingProvider == null,
+ FilledButton.icon(
+ key: const Key('sign-in-step-email'),
+ onPressed: () => onSignIn(null),
+ style: _otherWay(filled: true),
+ icon: const Icon(AppIcons.mail, size: 18),
+ label: const Text(
+ 'Email, GitHub or passkey',
+ overflow: TextOverflow.ellipsis,
),
),
),
+ if (onApprove case final approve?) ...[
+ const OrDivider(),
+ OutlinedButton.icon(
+ key: const Key('sign-in-step-scan'),
+ onPressed: () => approve(ApprovalSignIn.phone),
+ style: _otherWay(),
+ icon: const Icon(AppIcons.smartphone, size: 18),
+ label: const Text(
+ 'Scan with your phone',
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ OutlinedButton.icon(
+ key: const Key('sign-in-step-code'),
+ onPressed: () => approve(ApprovalSignIn.code),
+ style: _otherWay(),
+ icon: const Icon(AppIcons.keyboard, size: 18),
+ label: const Text(
+ 'Sign in on another device',
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ],
],
if ((signOutError ?? error) case final error?)
Semantics(
@@ -247,6 +293,34 @@ class SignInStep extends StatelessWidget {
),
);
+ /// The ways in beside Google and Apple: their size and type, in the app's
+ /// own colours — a raised card fill for the browser page's other ways, an
+ /// outline for those another device approves.
+ ButtonStyle _otherWay({bool filled = false}) {
+ final ink = grid.AppPalette.textPrimary;
+ return ButtonStyle(
+ minimumSize: WidgetStatePropertyAll(
+ SignInProviderButton.minimumSize(prominent: true),
+ ),
+ textStyle: WidgetStatePropertyAll(grid.AppType.heading()),
+ foregroundColor: WidgetStatePropertyAll(ink),
+ iconColor: WidgetStatePropertyAll(ink),
+ backgroundColor: WidgetStatePropertyAll(
+ filled ? grid.AppPalette.cardBg : Colors.transparent,
+ ),
+ side: WidgetStatePropertyAll(BorderSide(color: grid.AppPalette.divider)),
+ overlayColor: WidgetStateProperty.resolveWith(
+ (states) => ink.withValues(
+ alpha: states.contains(WidgetState.pressed)
+ ? .12
+ : states.contains(WidgetState.hovered)
+ ? .06
+ : 0,
+ ),
+ ),
+ );
+ }
+
/// [child], stepped back while its own sign-in is starting.
Widget _stepsBack(bool back, Widget child) => AnimatedOpacity(
opacity: back ? 0.55 : 1,
@@ -442,6 +516,23 @@ class _SignInStepScreenState extends State<SignInStepScreen> {
},
child: SignInStep(
onSignIn: (provider) => unawaited(app.signInFromStep(provider)),
+ onApprove: app.canSignInWithPhone && app.canSignInWithCode
+ ? (method) => unawaited(app.approveFromStep(method))
+ : null,
+ approval: switch (app.approvalSignIn) {
+ final method? => ApprovalSignInPanel(
+ method: method,
+ qrLink: app.pendingQrLink,
+ code: app.pendingSignInCode,
+ refreshAt: app.approvalRefreshAt,
+ confirmEmail: app.pendingConfirmEmail,
+ previousEmail: app.previousAccountEmail,
+ answered: app.approvalAnswered,
+ onConfirm: app.confirmPhoneSignIn,
+ onCancel: app.cancelLogin,
+ ),
+ null => null,
+ },
// Its browser is not open yet: the CLI has to start before it can
// name the page.
starting: app.canCancelLogin && app.pendingAuthorizeUrl == null,
diff --git a/desktop/test/approval_sign_in_panel_test.dart b/desktop/test/approval_sign_in_panel_test.dart
new file mode 100644
index 000000000..b9ad34fa7
--- /dev/null
+++ b/desktop/test/approval_sign_in_panel_test.dart
@@ -0,0 +1,268 @@
+import 'dart:io';
+
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/phone_sign_in.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/widgets/qr_code_view.dart';
+import 'package:harness/widgets/approval_sign_in_panel.dart';
+import 'package:harness/widgets/sign_in_step.dart';
+
+import 'support/capture.dart';
+
+/// What the first-run page shows in place of its ways in while a phone scans its QR or another
+/// device takes its code: the QR or the code, where to go on the other device, when a new one
+/// comes, and then whose account approved it. `HARNESS_SIGN_IN_CAPTURE_DIR` writes what it draws.
+final _boundary = GlobalKey();
+
+Future<void> _mount(
+ WidgetTester tester,
+ Widget panel, {
+ Size size = const Size(1280, 800),
+ Brightness brightness = Brightness.dark,
+ double textScale = 1,
+}) async {
+ final previousBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(textScale)),
+ child: child!,
+ ),
+ // On the page itself, as a person sees it.
+ home: RepaintBoundary(
+ key: _boundary,
+ child: SignInStep(onSignIn: (_) {}, onApprove: (_) {}, approval: panel),
+ ),
+ ),
+ );
+ await tester.pump();
+}
+
+Future<void> _capture(WidgetTester tester, String name) => captureBoundary(
+ tester,
+ _boundary.currentContext!.findRenderObject()! as RenderRepaintBoundary,
+ Platform.environment['HARNESS_SIGN_IN_CAPTURE_DIR'],
+ name,
+);
+
+ApprovalSignInPanel _panel({
+ ApprovalSignIn method = ApprovalSignIn.code,
+ String? qrLink,
+ String? code,
+ DateTime? refreshAt,
+ String? confirmEmail,
+ String? previousEmail,
+ ValueChanged<bool>? onConfirm,
+ VoidCallback? onCancel,
+}) => ApprovalSignInPanel(
+ method: method,
+ qrLink: qrLink,
+ code: code,
+ refreshAt: refreshAt,
+ confirmEmail: confirmEmail,
+ previousEmail: previousEmail,
+ onConfirm: onConfirm ?? (_) {},
+ onCancel: onCancel ?? () {},
+);
+
+const _link =
+ 'https://harness.autonomous.ai/signin#k=hnq_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
+
+void main() {
+ setUpAll(
+ () => loadCaptureFonts(Platform.environment['HARNESS_SIGN_IN_CAPTURE_DIR']),
+ );
+
+ testWidgets('the code, where to type it on a phone or a computer, and when '
+ 'a new one comes', (tester) async {
+ var cancels = 0;
+ await _mount(
+ tester,
+ _panel(
+ code: '12345678',
+ refreshAt: clock.now().add(const Duration(minutes: 9, seconds: 45)),
+ onCancel: () => cancels++,
+ ),
+ );
+ // Split in two, the way the CLI says it, so it reads and types in halves.
+ expect(find.text('1234 5678'), findsOneWidget);
+ expect(
+ find.text(
+ 'Harness ▸ Settings ▸ Sign in a computer ▸ Type a code instead',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Machines ▸ Approve a device'), findsOneWidget);
+ expect(find.text('New code in 9:45'), findsOneWidget);
+ await tester.pump(const Duration(seconds: 1));
+ expect(find.text('New code in 9:44'), findsOneWidget);
+ // No QR on this path.
+ expect(find.byType(QrCodeView), findsNothing);
+
+ await tester.tap(find.text('Cancel'));
+ expect(cancels, 1);
+ });
+
+ testWidgets('Copy puts the code itself on the clipboard, and says so for '
+ 'that code only', (tester) async {
+ final copied = <String>[];
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method == 'Clipboard.setData') {
+ copied.add((call.arguments as Map)['text'] as String);
+ }
+ return null;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ null,
+ ),
+ );
+ final refreshAt = clock.now().add(const Duration(minutes: 5));
+ await _mount(tester, _panel(code: '12345678', refreshAt: refreshAt));
+ await tester.tap(find.byKey(const Key('sign-in-code-copy')));
+ await tester.pump();
+ expect(copied, ['12345678']);
+ expect(find.text('Copied'), findsOneWidget);
+
+ // A new code: the old one's "Copied" does not speak for it.
+ await _mount(tester, _panel(code: '87654321', refreshAt: refreshAt));
+ expect(find.text('Copied'), findsNothing);
+ expect(find.text('Copy'), findsOneWidget);
+ });
+
+ testWidgets('the QR, and where to go on the phone', (tester) async {
+ await _mount(
+ tester,
+ _panel(
+ method: ApprovalSignIn.phone,
+ qrLink: _link,
+ refreshAt: clock.now().add(const Duration(seconds: 45)),
+ ),
+ );
+ expect(find.byKey(const Key('login-phone-qr')), findsOneWidget);
+ expect(
+ find.text('On your phone: Harness ▸ Settings ▸ Sign in a computer'),
+ findsOneWidget,
+ );
+ expect(find.text('New code in 0:45'), findsOneWidget);
+ expect(find.text('Cancel'), findsOneWidget);
+ });
+
+ testWidgets('before the CLI has a code: getting one, with Cancel', (
+ tester,
+ ) async {
+ await _mount(tester, _panel());
+ expect(find.text('Getting a code…'), findsOneWidget);
+ expect(find.text('Cancel'), findsOneWidget);
+ expect(find.textContaining('New code in'), findsNothing);
+ await _mount(tester, _panel(method: ApprovalSignIn.phone));
+ expect(find.text('Getting a QR code…'), findsOneWidget);
+ });
+
+ testWidgets('a code whose refresh is due says a new one is coming, never a '
+ 'negative time', (tester) async {
+ await _mount(
+ tester,
+ _panel(
+ code: '12345678',
+ refreshAt: clock.now().add(const Duration(seconds: 1)),
+ ),
+ );
+ await tester.pump(const Duration(seconds: 3));
+ expect(find.text('Getting a new code…'), findsOneWidget);
+ expect(find.textContaining('-'), findsNothing);
+ });
+
+ testWidgets(
+ 'approved elsewhere: whose account, before anything is signed in',
+ (tester) async {
+ final answers = <bool>[];
+ await _mount(
+ tester,
+ _panel(
+ code: '12345678',
+ confirmEmail: '[email protected]',
+ onConfirm: answers.add,
+ ),
+ );
+ expect(find.text('Sign in as [email protected]?'), findsOneWidget);
+ expect(
+ find.text('Continue only if this is your account.'),
+ findsOneWidget,
+ );
+ // The code is no longer shown: it has done its work.
+ expect(find.text('1234 5678'), findsNothing);
+ await tester.tap(find.byKey(const Key('login-phone-continue')));
+ await tester.tap(find.byKey(const Key('login-phone-refuse')));
+ expect(answers, [true, false]);
+
+ await _mount(
+ tester,
+ _panel(
+ confirmEmail: '[email protected]',
+ previousEmail: '[email protected]',
+ ),
+ );
+ expect(
+ find.text(
+ 'This computer was signed in as [email protected]. Continue only if [email protected] is yours.',
+ ),
+ findsOneWidget,
+ );
+ },
+ );
+
+ for (final brightness in Brightness.values) {
+ for (final (size, scale) in const [
+ (Size(1280, 800), 1.0),
+ (Size(880, 560), 1.0),
+ (Size(880, 560), 2.0),
+ ]) {
+ final tag =
+ '${brightness.name}-${size.width.round()}'
+ '${scale == 1.0 ? '' : '-text-${(scale * 100).round()}'}';
+ testWidgets('draws the scan, the code and the account question in $tag '
+ 'without overflow', (tester) async {
+ final refreshAt = clock.now().add(
+ const Duration(minutes: 9, seconds: 45),
+ );
+ final states = {
+ 'scan': _panel(
+ method: ApprovalSignIn.phone,
+ qrLink: _link,
+ refreshAt: refreshAt,
+ ),
+ 'code': _panel(code: '12345678', refreshAt: refreshAt),
+ 'confirm': _panel(code: '12345678', confirmEmail: '[email protected]'),
+ };
+ for (final MapEntry(key: name, value: panel) in states.entries) {
+ await _mount(
+ tester,
+ panel,
+ size: size,
+ brightness: brightness,
+ textScale: scale,
+ );
+ expect(tester.takeException(), isNull, reason: name);
+ await _capture(tester, 'sign-in-step-$name-$tag');
+ }
+ });
+ }
+ }
+}
diff --git a/desktop/test/login_screen_phone_test.dart b/desktop/test/login_screen_phone_test.dart
index d602cc91e..0b47d25c4 100644
--- a/desktop/test/login_screen_phone_test.dart
+++ b/desktop/test/login_screen_phone_test.dart
@@ -112,7 +112,10 @@ void main() {
addTearDown(app.dispose);
await tester.pumpWidget(_host(app));
expect(find.text('Continue with Google'), findsOneWidget);
- expect(find.text('Continue with email'), findsOneWidget);
+ expect(find.text('Email, GitHub or passkey'), findsOneWidget);
+ // The phone's scan is the page's own button, beside a code for another device.
+ expect(find.byKey(const Key('sign-in-step-scan')), findsOneWidget);
+ expect(find.byKey(const Key('sign-in-step-code')), findsOneWidget);
expect(find.byKey(const Key('login-scan-with-phone')), findsNothing);
},
);
diff --git a/desktop/test/login_screen_test.dart b/desktop/test/login_screen_test.dart
index b915f5c98..e55ff18d6 100644
--- a/desktop/test/login_screen_test.dart
+++ b/desktop/test/login_screen_test.dart
@@ -119,12 +119,16 @@ void main() {
for (final label in [
'Continue with Google',
'Continue with Apple',
- 'Continue with email',
+ 'Email, GitHub or passkey',
+ // The ways a new or remote computer signs in with no browser of its own.
+ 'Scan with your phone',
+ 'Sign in on another device',
]) {
expect(find.text(label), findsOneWidget);
}
expect(find.byType(LoginFleetMap), findsNothing);
- expect(find.text('Scan with your phone'), findsNothing);
+ // The page's own buttons, not the old card's.
+ expect(find.byKey(const Key('login-scan-with-phone')), findsNothing);
expect(find.byKey(const Key('login-close-button')), findsNothing);
},
);
@@ -184,7 +188,13 @@ void main() {
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text('Continue with Google').hitTestable(), findsOneWidget);
- expect(find.text('Continue with email').hitTestable(), findsOneWidget);
+ for (final label in const [
+ 'Email, GitHub or passkey',
+ 'Scan with your phone',
+ 'Sign in on another device',
+ ]) {
+ expect(find.text(label).hitTestable(), findsOneWidget, reason: label);
+ }
final page = tester.widget<Material>(
find.byKey(const Key('sign-in-step')),
);
diff --git a/desktop/test/phone_sign_in_test.dart b/desktop/test/phone_sign_in_test.dart
index 198d005d8..09dbf1d55 100644
--- a/desktop/test/phone_sign_in_test.dart
+++ b/desktop/test/phone_sign_in_test.dart
@@ -214,6 +214,80 @@ void main() {
});
});
+ group('CliLogin.loginWithCode', () {
+ test('asks the CLI for a code, shows each one it says, and answers the account question', () async {
+ final process = _Process();
+ final runner = _Runner(process);
+ final codes = <(String, int)>[];
+ final done = CliLogin(runner: runner).loginWithCode(
+ onCode: (code, expiresIn) => codes.add((code, expiresIn)),
+ onConfirm: (email) async => email == '[email protected]',
+ );
+ await Future<void>.delayed(Duration.zero);
+ expect(runner.arguments, [
+ 'login',
+ '--force',
+ '--json',
+ '--code',
+ '--entry-point=desktop',
+ ]);
+ process.emit({'type': 'code', 'code': '12345678', 'expiresIn': 120});
+ // Kept alive: the same code again, with its new time left.
+ process.emit({'type': 'code', 'code': '12345678', 'expiresIn': 95});
+ process.emit({'type': 'confirm', 'email': '[email protected]'});
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ expect(process.written.join(), 'yes\n');
+ process.emit({'type': 'result', 'status': 'success'});
+ process.finish();
+ await done;
+ expect(codes, [('12345678', 120), ('12345678', 95)]);
+ });
+
+ test('a code that runs out says so with its own reason', () async {
+ final process = _Process();
+ final done = CliLogin(runner: _Runner(process))
+ .loginWithCode(onCode: (_, _) {}, onConfirm: (_) async => false);
+ await Future<void>.delayed(Duration.zero);
+ process.emit({
+ 'type': 'result',
+ 'status': 'error',
+ 'code': 'EXPIRED',
+ 'message': 'The code expired.',
+ });
+ process.finish(1);
+ await expectLater(
+ done,
+ throwsA(
+ isA<PhoneSignInException>().having((e) => e.code, 'code', 'EXPIRED'),
+ ),
+ );
+ });
+
+ test('a CLI from before --code starts SSO instead: stops it and says the CLI is too old', () async {
+ final process = _Process();
+ final done = CliLogin(runner: _Runner(process)).loginWithCode(
+ onCode: (_, _) => fail('no code from an old CLI'),
+ onConfirm: (_) async => fail('nothing to confirm'),
+ );
+ await Future<void>.delayed(Duration.zero);
+ process.emit({
+ 'type': 'authorize_url',
+ 'url': 'https://sso.example/authorize',
+ });
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ expect(process.killed, isTrue);
+ process.finish(143);
+ await expectLater(
+ done,
+ throwsA(
+ isA<PhoneSignInException>()
+ .having((e) => e.code, 'code', 'CLI_TOO_OLD')
+ .having((e) => e.message, 'message', contains('code')),
+ ),
+ );
+ });
+ });
+
group('viewerQrSignIn', () {
test('claims only after the person confirms the account', () async {
final api = _Api(['pending', 'approved']);
diff --git a/desktop/test/sign_in_measurement_test.dart b/desktop/test/sign_in_measurement_test.dart
index 772bd9914..4485106b0 100644
--- a/desktop/test/sign_in_measurement_test.dart
+++ b/desktop/test/sign_in_measurement_test.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/auth/cli_login.dart';
@@ -38,6 +39,20 @@ class _Cli extends CliLogin {
return attempt.future;
}
+ /// Each code sign-in's way to show its code.
+ final showCode = <void Function(String code, int expiresIn)>[];
+
+ @override
+ Future<void> loginWithCode({
+ required void Function(String code, int expiresIn) onCode,
+ required Future<bool> Function(String email) onConfirm,
+ }) {
+ showCode.add(onCode);
+ final attempt = Completer<void>();
+ attempts.add(attempt);
+ return attempt.future;
+ }
+
/// What the real one does to the attempt it stops: the process is killed and its wait throws.
@override
void cancel() {
@@ -236,4 +251,21 @@ void main() {
expect(usage.reasons, [end.$2]);
});
});
+
+ test('a code the page replaces before it runs out counts as expired, not '
+ 'as the person cancelling', () {
+ fakeAsync((async) {
+ final cli = _Cli(), usage = _Recorder();
+ final app = _app(cli, usage);
+ unawaited(app.loginWithCode());
+ async.flushMicrotasks();
+ cli.showCode.single('12345678', 120);
+ async.elapse(AppNotifier.approvalCodeLife);
+ async.flushMicrotasks();
+ expect(cli.attempts, hasLength(2));
+ expect(usage.reasons, [SignInEndReason.expired]);
+ app.dispose();
+ async.flushMicrotasks();
+ });
+ });
}
diff --git a/desktop/test/sign_in_step_flow_test.dart b/desktop/test/sign_in_step_flow_test.dart
index 38490ee5e..d7761d147 100644
--- a/desktop/test/sign_in_step_flow_test.dart
+++ b/desktop/test/sign_in_step_flow_test.dart
@@ -1,9 +1,12 @@
import 'dart:async';
+import 'package:clock/clock.dart';
+import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/api/api_client.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/auth/cli_login.dart';
+import 'package:harness/auth/phone_sign_in.dart';
import 'package:harness/auth/sign_in_provider.dart';
import 'package:harness/bootstrap/environment_provisioner.dart';
import 'package:harness/core/config.dart';
@@ -34,8 +37,42 @@ class _Login extends CliLogin {
@override
Future<void> logout() async => loggedIn = false;
+ /// Each phone scan or code sign-in begun: what it shows, the account question, and its end.
+ final approvals = <_Approval>[];
+
+ @override
+ void cancel() {
+ cancels++;
+ // What the real one does to the attempt it stops: its process is killed and its wait throws.
+ for (final approval in approvals) {
+ if (!approval.done.isCompleted) {
+ approval.done.completeError(StateError('Sign-in was cancelled.'));
+ }
+ }
+ }
+
@override
- void cancel() => cancels++;
+ Future<void> loginWithPhone({
+ required void Function(String link, int expiresIn) onQr,
+ required Future<bool> Function(String email) onConfirm,
+ }) => _approve(ApprovalSignIn.phone, onQr, onConfirm);
+
+ @override
+ Future<void> loginWithCode({
+ required void Function(String code, int expiresIn) onCode,
+ required Future<bool> Function(String email) onConfirm,
+ }) => _approve(ApprovalSignIn.code, onCode, onConfirm);
+
+ Future<void> _approve(
+ ApprovalSignIn method,
+ void Function(String, int) show,
+ Future<bool> Function(String) confirm,
+ ) async {
+ final approval = _Approval(method, show, confirm);
+ approvals.add(approval);
+ await approval.done.future;
+ loggedIn = true;
+ }
@override
Future<void> login({
@@ -50,6 +87,16 @@ class _Login extends CliLogin {
}
}
+/// One phone scan or code sign-in as the CLI runs it: [show] is its QR link or code (again each time
+/// it is kept alive), [confirm] asks whose account approved it, [done] is how it ends.
+class _Approval {
+ _Approval(this.method, this.show, this.confirm);
+ final ApprovalSignIn method;
+ final void Function(String shown, int expiresIn) show;
+ final Future<bool> Function(String email) confirm;
+ final done = Completer<void>();
+}
+
class _Api extends ApiClient {
_Api()
: super(
@@ -364,4 +411,267 @@ void main() {
expect(app.setupTourShowing, isFalse);
expect(app.signInStepShowing, isTrue);
});
+
+ group('Sign in on another device and Scan with your phone', () {
+ test('the code shows, another device approves it, and the person here '
+ 'says whose account it is', () async {
+ final app = _Desktop(_Login());
+ addTearDown(app.dispose);
+ await app.bootstrap();
+ app.finishSetupTour();
+
+ final signIn = app.approveFromStep(ApprovalSignIn.code);
+ await _settle();
+ final attempt = app.cli.approvals.single;
+ expect(attempt.method, ApprovalSignIn.code);
+ expect(app.approvalSignIn, ApprovalSignIn.code);
+ // Nothing to show until the CLI has its code.
+ expect(app.pendingSignInCode, isNull);
+ expect(app.signInStepShowing, isTrue);
+
+ attempt.show('12345678', 120);
+ expect(app.pendingSignInCode, '12345678');
+ expect(app.pendingQrLink, isNull);
+ expect(app.signInStepShowing, isTrue);
+
+ // Machines ▸ Approve a device on a signed-in computer (faked): the CLI asks whose account.
+ final answer = attempt.confirm('[email protected]');
+ expect(app.pendingConfirmEmail, '[email protected]');
+ app.confirmPhoneSignIn(true);
+ expect(await answer, isTrue);
+ attempt.done.complete();
+ await signIn;
+ expect(app.signedIn, isTrue);
+ expect(app.signInStepShowing, isFalse);
+ expect(app.pendingSignInCode, isNull);
+ expect(app.approvalSignIn, isNull);
+ });
+
+ test('Scan with your phone shows the QR on the same page', () async {
+ final app = _Desktop(_Login());
+ addTearDown(app.dispose);
+ await app.bootstrap();
+ app.finishSetupTour();
+
+ unawaited(app.approveFromStep(ApprovalSignIn.phone));
+ await _settle();
+ app.cli.approvals.single.show(
+ 'https://harness.autonomous.ai/signin#k=hnq_x',
+ 120,
+ );
+ expect(app.approvalSignIn, ApprovalSignIn.phone);
+ expect(app.pendingQrLink, 'https://harness.autonomous.ai/signin#k=hnq_x');
+ expect(app.pendingSignInCode, isNull);
+ expect(app.signInStepShowing, isTrue);
+
+ // Back: the ways in again, and nothing left running.
+ app.cancelLogin();
+ expect(app.signingIn, isFalse);
+ expect(app.approvalSignIn, isNull);
+ expect(app.pendingQrLink, isNull);
+ expect(app.signInStepShowing, isTrue);
+ expect(app.isGuest, isTrue);
+ });
+
+ test('another way in ends the one under way, browser or code', () async {
+ final app = _Desktop(_Login());
+ addTearDown(app.dispose);
+ await app.bootstrap();
+ app.finishSetupTour();
+
+ unawaited(app.signInFromStep(SignInProvider.google));
+ await _settle();
+ unawaited(app.approveFromStep(ApprovalSignIn.code));
+ await _settle();
+ expect(app.cli.cancels, 1);
+ expect(app.cli.approvals.single.method, ApprovalSignIn.code);
+ app.cli.approvals.single.show('12345678', 120);
+
+ unawaited(app.approveFromStep(ApprovalSignIn.phone));
+ await _settle();
+ expect(app.cli.cancels, 2);
+ expect(app.cli.approvals.map((a) => a.method), [
+ ApprovalSignIn.code,
+ ApprovalSignIn.phone,
+ ]);
+ // The old code is gone with its attempt, and a late one cannot come back.
+ expect(app.pendingSignInCode, isNull);
+ app.cli.approvals.first.show('99999999', 120);
+ expect(app.pendingSignInCode, isNull);
+ expect(app.approvalSignIn, ApprovalSignIn.phone);
+ });
+ });
+
+ group('the code and QR never run out on screen', () {
+ /// A desktop on the sign-in step, in fake time.
+ _Desktop onStep(FakeAsync async) {
+ final app = _Desktop(_Login());
+ unawaited(app.bootstrap());
+ async.flushMicrotasks();
+ app.finishSetupTour();
+ return app;
+ }
+
+ test(
+ "a new code takes the old one's place shortly before its life ends",
+ () {
+ fakeAsync((async) {
+ final app = onStep(async);
+ unawaited(app.approveFromStep(ApprovalSignIn.code));
+ async.flushMicrotasks();
+ final started = clock.now();
+ app.cli.approvals.single.show('11111111', 120);
+ expect(
+ app.approvalRefreshAt,
+ started.add(
+ AppNotifier.approvalCodeLife - AppNotifier.approvalRefreshLead,
+ ),
+ );
+ // The CLI keeps the same code alive meanwhile.
+ for (var i = 1; i <= 4; i++) {
+ async.elapse(const Duration(seconds: 90));
+ app.cli.approvals.single.show('11111111', 120);
+ }
+ async.elapse(const Duration(minutes: 3, seconds: 44));
+ expect(app.cli.approvals, hasLength(1));
+ expect(app.pendingSignInCode, '11111111');
+
+ async.elapse(const Duration(seconds: 1));
+ async.flushMicrotasks();
+ expect(app.cli.approvals, hasLength(2));
+ expect(app.cli.approvals.first.done.isCompleted, isTrue);
+ expect(app.cli.approvals.last.method, ApprovalSignIn.code);
+ // Still signing in on the same page; the old code is not shown while the next one comes.
+ expect(app.signingIn, isTrue);
+ expect(app.signInStepShowing, isTrue);
+ expect(app.pendingSignInCode, isNull);
+ expect(app.lastError, isNull);
+ app.cli.approvals.last.show('22222222', 120);
+ expect(app.pendingSignInCode, '22222222');
+ // A late word from the replaced attempt changes nothing.
+ app.cli.approvals.first.show('11111111', 120);
+ expect(app.pendingSignInCode, '22222222');
+ app.dispose();
+ });
+ },
+ );
+
+ test('a code reported with less than its usual time is near its end: '
+ 'replaced before then', () {
+ fakeAsync((async) {
+ final app = onStep(async);
+ unawaited(app.approveFromStep(ApprovalSignIn.phone));
+ async.flushMicrotasks();
+ app.cli.approvals.single.show(
+ 'https://harness.autonomous.ai/signin#k=a',
+ 120,
+ );
+ async.elapse(const Duration(minutes: 2));
+ // The backend has less life left than a full extension.
+ app.cli.approvals.single.show(
+ 'https://harness.autonomous.ai/signin#k=a',
+ 40,
+ );
+ expect(
+ app.approvalRefreshAt,
+ clock.now().add(
+ const Duration(seconds: 40) - AppNotifier.approvalRefreshLead,
+ ),
+ );
+ async.elapse(const Duration(seconds: 25));
+ async.flushMicrotasks();
+ expect(app.cli.approvals, hasLength(2));
+ expect(app.cli.approvals.last.method, ApprovalSignIn.phone);
+ expect(app.pendingQrLink, isNull);
+ app.dispose();
+ });
+ });
+
+ test('no new code while the person is answering whose account it is', () {
+ fakeAsync((async) {
+ final app = onStep(async);
+ unawaited(app.approveFromStep(ApprovalSignIn.code));
+ async.flushMicrotasks();
+ final attempt = app.cli.approvals.single;
+ attempt.show('11111111', 120);
+ unawaited(attempt.confirm('[email protected]'));
+ async.elapse(AppNotifier.approvalCodeLife);
+ async.flushMicrotasks();
+ expect(app.cli.approvals, hasLength(1));
+ expect(app.pendingConfirmEmail, '[email protected]');
+ app.dispose();
+ });
+ });
+
+ test('a code the CLI says ran out is replaced at once, a bounded number '
+ 'of times, then the page says so and shows no code', () {
+ fakeAsync((async) {
+ final app = onStep(async);
+ unawaited(app.approveFromStep(ApprovalSignIn.code));
+ async.flushMicrotasks();
+ for (var i = 0; i <= AppNotifier.maxApprovalRefreshes; i++) {
+ expect(app.cli.approvals, hasLength(i + 1));
+ app.cli.approvals.last.show('$i' * 8, 120);
+ app.cli.approvals.last.done.completeError(
+ const PhoneSignInException('EXPIRED', 'The code expired.'),
+ );
+ async.flushMicrotasks();
+ }
+ // One person's first try plus the bounded refreshes; then it stops asking.
+ expect(
+ app.cli.approvals,
+ hasLength(AppNotifier.maxApprovalRefreshes + 1),
+ );
+ async.elapse(const Duration(hours: 1));
+ expect(
+ app.cli.approvals,
+ hasLength(AppNotifier.maxApprovalRefreshes + 1),
+ );
+ expect(app.signingIn, isFalse);
+ expect(app.pendingSignInCode, isNull);
+ expect(app.approvalSignIn, isNull);
+ expect(app.lastError, contains('ran out'));
+ expect(app.signInStepShowing, isTrue);
+
+ // Asked again by hand: a fresh run of codes.
+ unawaited(app.approveFromStep(ApprovalSignIn.code));
+ async.flushMicrotasks();
+ expect(
+ app.cli.approvals,
+ hasLength(AppNotifier.maxApprovalRefreshes + 2),
+ );
+ expect(app.lastError, isNull);
+ app.dispose();
+ });
+ });
+
+ test('Cancel, sign-out and closing the app stop the refresh', () {
+ fakeAsync((async) {
+ final app = onStep(async);
+ unawaited(app.approveFromStep(ApprovalSignIn.code));
+ async.flushMicrotasks();
+ app.cli.approvals.single.show('11111111', 120);
+ app.cancelLogin();
+ async.elapse(const Duration(minutes: 30));
+ expect(app.cli.approvals, hasLength(1));
+ expect(app.approvalRefreshAt, isNull);
+
+ unawaited(app.approveFromStep(ApprovalSignIn.code));
+ async.flushMicrotasks();
+ app.cli.approvals.last.show('22222222', 120);
+ unawaited(app.logout());
+ async.flushMicrotasks();
+ async.elapse(const Duration(minutes: 30));
+ expect(app.cli.approvals, hasLength(2));
+ expect(app.pendingSignInCode, isNull);
+
+ unawaited(app.approveFromStep(ApprovalSignIn.code));
+ async.flushMicrotasks();
+ app.cli.approvals.last.show('33333333', 120);
+ app.dispose();
+ async.elapse(const Duration(minutes: 30));
+ expect(app.cli.approvals, hasLength(3));
+ });
+ });
+ });
}
diff --git a/desktop/test/sign_in_step_test.dart b/desktop/test/sign_in_step_test.dart
index 8c086c582..16b584097 100644
--- a/desktop/test/sign_in_step_test.dart
+++ b/desktop/test/sign_in_step_test.dart
@@ -1,28 +1,39 @@
+import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.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/auth/phone_sign_in.dart';
import 'package:harness/auth/sign_in_provider.dart';
+import 'package:harness/core/config.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
import 'package:harness/widgets/setup_tour.dart';
import 'package:harness/widgets/sign_in_step.dart';
import 'support/capture.dart';
/// The sign-in step as a computer new to Harness sees it after setup: one
-/// headline, four lines, two buttons, and Continue with email under
-/// them. The page takes callbacks and flags, so no app, CLI or browser is
+/// headline, four lines, and five ways in — Google, Apple, the browser page's
+/// email/GitHub/passkey, then a phone's scan and a code another device approves. The page takes callbacks and flags, so no app, CLI or browser is
/// involved. `HARNESS_SIGN_IN_CAPTURE_DIR` writes what it draws.
final _email = find.byKey(const Key('sign-in-step-email'));
final _google = find.byKey(const Key('login-continue-google'));
final _apple = find.byKey(const Key('login-continue-apple'));
+final _scan = find.byKey(const Key('sign-in-step-scan'));
+final _code = find.byKey(const Key('sign-in-step-code'));
final _boundary = GlobalKey();
Future<void> _mount(
WidgetTester tester, {
ValueChanged<SignInProvider?>? onSignIn,
+ ValueChanged<ApprovalSignIn>? onApprove,
+ bool offerApproval = true,
+ Widget? approval,
bool starting = false,
SignInProvider? startingProvider,
bool finishing = false,
@@ -50,6 +61,8 @@ Future<void> _mount(
key: _boundary,
child: SignInStep(
onSignIn: onSignIn ?? (_) {},
+ onApprove: offerApproval ? (onApprove ?? (_) {}) : null,
+ approval: approval,
starting: starting,
startingProvider: startingProvider,
finishing: finishing,
@@ -68,12 +81,44 @@ Future<void> _capture(WidgetTester tester, String name) => captureBoundary(
name,
);
+/// The CLI's sign-in as the page drives it: which way in was asked for, and a code sign-in a test
+/// approves from "another device".
+class _Cli extends CliLogin {
+ final browser = <SignInProvider?>[];
+ void Function(String code, int expiresIn)? showCode;
+ Future<bool> Function(String email)? confirm;
+ final codeDone = Completer<void>();
+ var cancels = 0;
+
+ @override
+ Future<void> login({
+ required void Function(String url) onAuthorizeUrl,
+ SignInProvider? provider,
+ }) async {
+ browser.add(provider);
+ await Completer<void>().future;
+ }
+
+ @override
+ Future<void> loginWithCode({
+ required void Function(String code, int expiresIn) onCode,
+ required Future<bool> Function(String email) onConfirm,
+ }) async {
+ showCode = onCode;
+ confirm = onConfirm;
+ await codeDone.future;
+ }
+
+ @override
+ void cancel() => cancels++;
+}
+
void main() {
setUpAll(
() => loadCaptureFonts(Platform.environment['HARNESS_SIGN_IN_CAPTURE_DIR']),
);
- testWidgets('one headline, four lines, two buttons and email; no Skip', (
+ testWidgets('one headline, four lines, and every way in; no Skip', (
tester,
) async {
await _mount(tester);
@@ -88,14 +133,25 @@ void main() {
}
expect(find.text('Continue with Google'), findsOneWidget);
expect(find.text('Continue with Apple'), findsOneWidget);
+ // Named for what it opens, as a button, not small print.
+ expect(find.text('Email, GitHub or passkey'), findsOneWidget);
+ expect(find.text('Continue with email'), findsNothing);
+ expect(
+ find.ancestor(
+ of: find.text('Email, GitHub or passkey'),
+ matching: find.byType(FilledButton),
+ ),
+ findsOneWidget,
+ );
+ // A new or remote computer's ways in that need no browser here.
+ expect(find.text('Scan with your phone'), findsOneWidget);
+ expect(find.text('Sign in on another device'), findsOneWidget);
+ expect(find.text('OR'), findsOneWidget);
expect(find.text('Skip'), findsNothing);
- expect(find.text('Continue with email'), findsOneWidget);
// It follows the tour: the same tagline, and the install line finished.
expect(find.text(tourTagline), findsOneWidget);
expect(find.text('Sign in to continue.'), findsOneWidget);
- // Nothing the sign-in sheet carries beside its buttons is on this page.
for (final absent in const [
- 'Scan with your phone',
'End-to-end encrypted',
'Sign in through your browser to continue.',
'Cancel',
@@ -107,11 +163,21 @@ void main() {
await _capture(tester, 'sign-in-step-dark');
});
+ testWidgets('a sign-in client that cannot be approved from elsewhere offers '
+ 'the browser alone', (tester) async {
+ await _mount(tester, offerApproval: false);
+ expect(_scan, findsNothing);
+ expect(_code, findsNothing);
+ expect(find.text('OR'), findsNothing);
+ expect(_email, findsOneWidget);
+ });
+
testWidgets('each control reports itself; Return is Continue with Google', (
tester,
) async {
final pressed = <SignInProvider?>[];
- await _mount(tester, onSignIn: pressed.add);
+ final approvals = <ApprovalSignIn>[];
+ await _mount(tester, onSignIn: pressed.add, onApprove: approvals.add);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
@@ -119,7 +185,7 @@ void main() {
await tester.tap(_apple);
await tester.tap(_google);
- // No provider is the sign-in page's own chooser, which takes an email.
+ // No provider is the sign-in page's own chooser: email, GitHub, passkey.
await tester.tap(_email);
expect(pressed, [
SignInProvider.google,
@@ -127,31 +193,54 @@ void main() {
SignInProvider.google,
null,
]);
+ await tester.tap(_scan);
+ await tester.tap(_code);
+ expect(approvals, [ApprovalSignIn.phone, ApprovalSignIn.code]);
+ expect(pressed, hasLength(4));
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(find.byType(SignInStep), findsOneWidget);
});
- testWidgets('email is centered beneath the two provider buttons', (
- tester,
- ) async {
+ testWidgets('the five ways in are one width, accounts first, the others '
+ 'after OR', (tester) async {
for (final size in const [Size(1280, 800), Size(880, 560)]) {
await _mount(tester, size: size);
- final button = tester.getRect(_google);
- expect(tester.getRect(_apple).left, button.left);
- expect(tester.getRect(_apple).right, button.right);
- expect(
- tester.getRect(find.text('Continue with email')).center.dx,
- moreOrLessEquals(button.center.dx, epsilon: 0.5),
- reason: '$size',
- );
+ final google = tester.getRect(_google);
+ for (final other in [_apple, _email, _scan, _code]) {
+ expect(tester.getRect(other).left, google.left, reason: '$size');
+ expect(tester.getRect(other).right, google.right, reason: '$size');
+ }
+ expect(tester.getRect(_apple).top, greaterThan(google.bottom));
expect(
tester.getRect(_email).top,
greaterThan(tester.getRect(_apple).bottom),
);
+ final or = tester.getRect(find.text('OR'));
+ expect(or.top, greaterThan(tester.getRect(_email).bottom));
+ expect(tester.getRect(_scan).top, greaterThan(or.bottom));
+ expect(
+ tester.getRect(_code).top,
+ greaterThan(tester.getRect(_scan).bottom),
+ );
}
});
+ testWidgets('a phone scan or a code under way takes the ways in\'s place', (
+ tester,
+ ) async {
+ await _mount(
+ tester,
+ approval: const SizedBox(key: Key('approval-under-way')),
+ );
+ expect(find.byKey(const Key('approval-under-way')), findsOneWidget);
+ expect(_google, findsNothing);
+ expect(_email, findsNothing);
+ expect(_scan, findsNothing);
+ // The rest of the page stays.
+ expect(find.text(signInStepTitle), findsOneWidget);
+ });
+
testWidgets('nothing changes while the browser is open, and every way in '
'stays live', (tester) async {
final pressed = <SignInProvider?>[];
@@ -196,6 +285,63 @@ void main() {
expect(find.text('Sign in to continue.'), findsOneWidget);
});
+ testWidgets('on the app: the email button opens the browser sign-in page, '
+ 'and a code approved elsewhere gets as far as whose account', (
+ tester,
+ ) async {
+ final cli = _Cli();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLogin: cli,
+ )..status = AppStatus.authenticated;
+ addTearDown(app.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SignInStepScreen(app: app),
+ ),
+ );
+
+ // The browser page with no account named: its own chooser, where email, GitHub and passkey are.
+ await tester.tap(_email);
+ await tester.pump();
+ expect(cli.browser, [null]);
+
+ // Another way in ends that one and shows its code where the buttons were.
+ await tester.tap(_code);
+ await tester.pump();
+ expect(cli.cancels, 1);
+ expect(find.text('Getting a code…'), findsOneWidget);
+ cli.showCode!('12345678', 120);
+ await tester.pump();
+ expect(find.text('1234 5678'), findsOneWidget);
+ expect(find.textContaining('New code in 9:'), findsOneWidget);
+ expect(_google, findsNothing);
+
+ // Approved on another device (faked): the person here is asked whose account.
+ final answer = cli.confirm!('[email protected]');
+ await tester.pump();
+ expect(find.text('Sign in as [email protected]?'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('login-phone-continue')));
+ await tester.pump();
+ expect(await answer, isTrue);
+ expect(find.text('Signing in…'), findsWidgets);
+ expect(find.text('1234 5678'), findsNothing);
+
+ // Cancel goes back to the ways in, with nothing left on screen.
+ await tester.tap(find.byKey(const Key('approval-sign-in-cancel')));
+ await tester.pump();
+ expect(_google, findsOneWidget);
+ expect(find.text('1234 5678'), findsNothing);
+ expect(app.signingIn, isFalse);
+ await tester.pumpWidget(const SizedBox());
+ });
+
for (final brightness in Brightness.values) {
for (final (size, scale) in const [
(Size(1280, 800), 1.0),
diff --git a/desktop/test/workspace_account_test.dart b/desktop/test/workspace_account_test.dart
index c02626273..c47bf5e6a 100644
--- a/desktop/test/workspace_account_test.dart
+++ b/desktop/test/workspace_account_test.dart
@@ -141,23 +141,15 @@ void main() {
await tester.pump();
expect(find.byType(SignInStep), findsOneWidget);
expect(find.text('Continue with Google'), findsOneWidget);
- // The quiet way in is on this sign-in too — as words, not as one more
- // button the width of the two above it.
+ // Email, GitHub and passkey are on this sign-in too, as a button of the
+ // same width as the two above it (Scholes's test, 2026-10-31: small print
+ // hid that it leads to GitHub and passkey too).
final email = find.byKey(const Key('sign-in-step-email'));
expect(email, findsOneWidget);
- expect(
- find.ancestor(
- of: find.text('Continue with email'),
- matching: find.byType(TextButton),
- ),
- findsNothing,
- );
+ expect(find.text('Email, GitHub or passkey'), findsOneWidget);
expect(
tester.getSize(email).width,
- lessThan(
- tester.getSize(find.byKey(const Key('login-continue-google'))).width *
- .8,
- ),
+ tester.getSize(find.byKey(const Key('login-continue-google'))).width,
);
expect(find.byKey(const Key('login-close-button')), findsNothing);