fix(mobile): name the cause of account-unavailable sign-in errors (#9628)

## Problem

Organization sign-in can fail with `Couldn't sign in
(account-unavailable)`. That code covers several different failures, so
a screenshot can't tell them apart:

- the account server can't be reached at all (DNS, connection, or TLS
failure, or a timeout), for example when a required VPN profile isn't
applied to the app;
- a redirect, since the client doesn't follow redirects, so an
access-proxy login page lands here;
- a 5xx from the server.

## Change

- `BuilderlabAccountClient` records why a request failed as
`unavailable`, in `lastUnavailableCause`, and logs it. It follows the
existing `lastRejectedRequest` pattern. The cause is one of:
- a transport category: `unreachable`, `insecure`, `timedOut` (reusing
`transportFailure`), or `network` as the fallback;
  - the status code, such as `http302`.
- `OrganizationSignIn` saves the cause at the moment the exchange fails,
so later account requests can't change it. It adds the cause to the
failure code, for example `account-unavailable-http302` or
`account-unavailable-unreachable`. Each new attempt clears it.

- The organization sign-in page now ends its failure message with advice
for that cause instead of "Try again.":
- unreachable, timeout, TLS failure, redirect: "Check your network or
VPN connection, then try again."
  - a 5xx: "The sign-in service is unavailable. Try again later."
- The in-app banner keeps "Try again.": its capsule clips longer
messages at default text size, and the existing banner layout test
caught that.
- Unexpected statuses are classified as soon as the headers arrive, so a
slow or oversized error body can't hide the status.

| Before | After |
|---|---|
|
![Before](https://github.com/user-attachments/assets/17a2a3ac-a488-46b3-9995-1bd95a529f60)
|
![After](https://github.com/user-attachments/assets/3813d1e9-7dc4-4726-9f40-ace57ed12d7a)
|

The log line contains only the host, route, and cause. It has no
headers, credentials, or response bodies.

## Validation

- A new journey test in `organization_sign_in_test.dart` covers an
exchange that fails with a 302, a 503, and a client exception, then a
successful retry. With the cause capture removed, the test fails
(`Expected: 'account-unavailable-http302'`, `Actual:
'account-unavailable'`).
- The same test checks the advice for each cause. The internal-build
landing tests pass with `--dart-define=BUZZ_DISTRIBUTION=internal`.
- The screenshots come from the real `PairingPage` rendered in a scratch
widget test with a 390×844 surface, cropped. The scratch test isn't
committed.
- `just mobile-check` passes, and the full `flutter test` run passes:
+5018, 71 skipped.
- Not yet done: a device run that reproduces an unreachable account
server and captures the new message on screen.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Diem Nguyen <diem@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Diem Nguyen
2026-11-18 10:34:49 -08:00
committed by GitHub
parent 7cf19b713c
commit c18bed1f46
5 changed files with 152 additions and 35 deletions

View File

@@ -141,7 +141,7 @@ class OrganizationAppEntry extends HookConsumerWidget {
} ??
switch (signIn.failureCode) {
null => null,
final code => 'Couldn’t sign in ($code). Try again.',
final code => 'Couldn’t sign in ($code). ${signIn.failureAdvice}',
};
return PairingPage(

View File

@@ -25,7 +25,14 @@ Future<http.Response> boundedHttpResponse(
StreamIterator<List<int>>? body;
Future<http.Response> read() async {
final response = await client.send(request);
onHeaders?.call(response);
try {
onHeaders?.call(response);
} catch (_) {
// Some clients hold the connection until the body is listened to and
// cancelled; an abort alone leaves it open.
unawaited(response.stream.listen(null).cancel());
rethrow;
}
final iterator = body = StreamIterator(response.stream);
if (abort.isCompleted) {
await iterator.cancel();

View File

@@ -90,6 +90,11 @@ class BuilderlabAccountClient {
/// Safe request diagnostics: no headers, credentials, bodies or user data.
({String path, int status})? lastRejectedRequest;
/// Why the last request failed as [AccountFailure.unavailable]: a transport
/// failure (`unreachable`, `insecure`, `timedOut`, `network`) or an
/// unexpected status such as `http302`. Safe to show; callers clear it.
String? lastUnavailableCause;
/// Runs [operation], giving it the clock hint of the last refusal (403) that
/// its own requests to any account client received: how many minutes the
/// local clock looked off from the server's `Date` when its headers arrived,
@@ -615,16 +620,16 @@ class BuilderlabAccountClient {
);
}
}
var refused = false;
final http.Response response;
try {
response = await boundedHttpResponse(
_http,
request,
maxBytes: _responseLimit(path),
onHeaders: (headers) {
if (headers.statusCode != 403) return;
refused = true;
// Classified from the headers, so a lost, slow or oversized error body
// never hides the status.
final response = await boundedHttpResponse(
_http,
request,
maxBytes: _responseLimit(path),
onHeaders: (headers) {
final status = headers.statusCode;
if (status >= 200 && status < 300) return;
if (status == 403) {
final evidence = Zone.current[_RefusalEvidence];
if (evidence is _RefusalEvidence) {
evidence.clockHint = clockHintMinutes(
@@ -632,27 +637,22 @@ class BuilderlabAccountClient {
_now(),
);
}
},
);
} catch (_) {
// The status is the answer; a lost or oversized body does not change it.
if (refused) throw AccountFailure.denied;
rethrow;
}
if (kDebugMode && response.statusCode >= 400) {
debugPrint(
'Builderlab ${accountOrigin.host} ${request.method} $path: HTTP ${response.statusCode} contentType=${response.headers['content-type']?.split(';').first}',
);
}
if (response.statusCode == 401) throw AccountFailure.signedOut;
if (response.statusCode == 403) throw AccountFailure.denied;
if (const {400, 404, 409, 422}.contains(response.statusCode)) {
lastRejectedRequest = (path: path, status: response.statusCode);
throw AccountFailure.rejected;
}
if (response.statusCode < 200 || response.statusCode >= 300) {
throw AccountFailure.unavailable;
}
}
if (const {401, 403, 400, 404, 409, 422}.contains(status) &&
kDebugMode) {
debugPrint(
'Builderlab ${accountOrigin.host} ${request.method} $path: HTTP $status contentType=${headers.headers['content-type']?.split(';').first}',
);
}
if (status == 401) throw AccountFailure.signedOut;
if (status == 403) throw AccountFailure.denied;
if (const {400, 404, 409, 422}.contains(status)) {
lastRejectedRequest = (path: path, status: status);
throw AccountFailure.rejected;
}
_unavailable(path, 'http$status');
},
);
final value = jsonDecode(utf8.decode(response.bodyBytes));
if (value is! Map<String, dynamic>) throw AccountFailure.invalidResponse;
return value;
@@ -660,11 +660,19 @@ class BuilderlabAccountClient {
rethrow;
} on FormatException {
throw AccountFailure.invalidResponse;
} catch (_) {
throw AccountFailure.unavailable;
} on TimeoutException {
_unavailable(path, 'timedOut');
} catch (error) {
_unavailable(path, transportFailure(error)?.name ?? 'network');
}
}
Never _unavailable(String path, String cause) {
lastUnavailableCause = cause;
debugPrint('Builderlab ${accountOrigin.host} $path: unavailable ($cause)');
throw AccountFailure.unavailable;
}
void dispose() {
_disposed = true;
_credential = null;

View File

@@ -54,10 +54,26 @@ class OrganizationSignIn extends ChangeNotifier {
String? get failureCode => switch (failure) {
null => null,
final BrowserAuthFailure f => 'browser-${f.name}',
AccountFailure.unavailable when _unavailableCause != null =>
'account-unavailable-$_unavailableCause',
final AccountFailure f => 'account-${f.name}',
final f => throw StateError('Unexpected sign-in failure: $f'),
};
/// What the user can do about [failure], ending the sign-in page's failure
/// message. The banner keeps "Try again." so its capsule stays compact.
String get failureAdvice => switch (_unavailableCause) {
final cause? when cause.startsWith('http5') =>
'The sign-in service is unavailable. Try again later.',
final cause? when cause.startsWith('http3') || !cause.startsWith('http') =>
'Check your network or VPN connection, then try again.',
_ => 'Try again.',
};
// What [BuilderlabAccountClient.lastUnavailableCause] held when the
// exchange failed, so later account requests cannot change the code.
String? _unavailableCause;
final _subscriptions = <StreamSubscription<Object>>[];
/// Advanced by every start or cancel, so an exchange from an abandoned
@@ -112,6 +128,7 @@ class OrganizationSignIn extends ChangeNotifier {
// Busy before any await, so a second tap cannot start another attempt.
final attempt = ++_attempt;
failure = null;
_unavailableCause = null;
_set(OrganizationSessionStatus.signingIn);
if (clear) {
try {
@@ -140,6 +157,7 @@ class OrganizationSignIn extends ChangeNotifier {
if (_disposed) return;
final attempt = ++_attempt;
failure = null;
_unavailableCause = null;
_set(OrganizationSessionStatus.checking);
try {
await account.clearLocalSession();
@@ -166,6 +184,7 @@ class OrganizationSignIn extends ChangeNotifier {
Future<void> _exchange(BrowserAuthCode code) async {
final attempt = _attempt;
account.lastUnavailableCause = null;
try {
await account.exchange(
code: code.code,
@@ -176,6 +195,7 @@ class OrganizationSignIn extends ChangeNotifier {
} on AccountFailure catch (error) {
if (attempt != _attempt) return;
failure = error;
_unavailableCause = account.lastUnavailableCause;
_set(_currentStatus());
return;
}

View File

@@ -180,6 +180,88 @@ void main() {
signIn.dispose();
});
test('an unreachable account server names the cause in the code', () async {
late Uri login;
http.StreamedResponse Function()? failExchange;
http.StreamedResponse respond(http.Response response) =>
http.StreamedResponse(
Stream.value(response.bodyBytes),
response.statusCode,
);
final signIn = OrganizationSignIn(
account: BuilderlabAccountClient(
accountOrigin: organization,
httpClient: MockClient.streaming((request, _) async {
if (!request.url.path.endsWith('/exchange')) return respond(me());
return failExchange?.call() ?? respond(exchanged());
}),
),
browser: BrowserAuth(
origin: organization,
openBrowser: (uri) async {
login = uri;
return null;
},
),
reconnect: () async {},
);
await signIn.initialize();
const network = 'Check your network or VPN connection, then try again.';
const outage = 'The sign-in service is unavailable. Try again later.';
// An error body the server holds open, which must not keep the
// connection after its status decides the failure.
var heldCancelled = false;
final held = StreamController<List<int>>(
onCancel: () => heldCancelled = true,
);
for (final (fail, code, advice)
in <(http.StreamedResponse Function(), String, String)>[
(
() => respond(http.Response('', 302)),
'account-unavailable-http302',
network,
),
(
() => respond(http.Response('', 503)),
'account-unavailable-http503',
outage,
),
(
() => http.StreamedResponse(held.stream, 503),
'account-unavailable-http503',
outage,
),
(
() => respond(http.Response('', 429)),
'account-unavailable-http429',
'Try again.',
),
(
() => throw http.ClientException('offline'),
'account-unavailable-network',
network,
),
]) {
failExchange = fail;
await signIn.signIn();
await signIn.browser.receive(callback(login, 'org-code'));
await pumpEventQueue();
expect(signIn.status, OrganizationSessionStatus.signedOut);
expect(signIn.failureCode, code);
expect(signIn.failureAdvice, advice);
}
expect(heldCancelled, isTrue);
failExchange = null;
await signIn.signIn();
expect(signIn.failureCode, isNull);
expect(signIn.failureAdvice, 'Try again.');
await signIn.browser.receive(callback(login, 'org-code'));
await pumpEventQueue();
expect(signIn.status, OrganizationSessionStatus.signedIn);
expect(signIn.failureCode, isNull);
signIn.dispose();
});
test('a failed cancel cleanup still leaves the busy state', () async {
final storage = _FailingDeleteStorage('buzz_browser_auth_attempt_v1_');
final signIn = OrganizationSignIn(