Repository navigation
fix(app): four iOS startup fixes — CGNAT dev endpoints, and hangs that presented as a blank splash - #11652
Conversation
Env._isLocalDevelopmentApi allowed loopback and RFC 1918 only. Tailscale assigns addresses from 100.64.0.0/10 (RFC 6598 shared address space), which is neither, so validateApplicationStartupRouting() threw before any network call: StateError: Profile local_dev requires a loopback or private-network API endpoint; use mobile_beta for https://api.omiapi.com/. main() wraps _init() in runZonedGuarded whose handler only calls debugPrint, so runApp() was never reached and the app sat on the launch storyboard forever with no diagnostic. It presented as a network hang and cost about a day: five connectivity hypotheses were investigated and disproven before the guard was found, because the failure never gets as far as opening a socket. This is not an exotic configuration. The local dev harness binds loopback only by design (scripts/dev-harness/dev_harness/safety.py:194 is a fail-closed guard, and it holds real provider API keys), so a physical device cannot reach it on 127.x and cannot reach it over the LAN either. A tailnet address is in practice the only route from real hardware to a developer's harness. Measured on iPhone 17 Pro / iOS 27.0, one variable at a time: OMI_API_BASE_URL | reachable | result --------------------------------|------------------|------------- loopback default | no | sign-in screen http://100.105.2.5:8000/ | yes, responds | splash hang http://100.105.2.5:9999/ | nothing listening| splash hang The dead-port run is the discriminator: no responding server is required, which is what pointed at a validation guard rather than a connection. Bounded to the real /10 — second octet 64..127. Tests cover both directions, including 100.63.x and 100.128.x staying rejected so this cannot silently become "any 100.x host". Verification: flutter test test/unit -> 755 passed (the new case fails without the fix, with exactly the StateError quoted above). INV-DATA-1: this widens the local_dev branch only. Production-family routing is unchanged — production keeps its own exact-match branch, and the invariant's MUST NOT clauses all concern production-family endpoints. Failure-Class: none Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011qmdS9crg5qFhan7PCbWvZ
_init() runs inside runZonedGuarded, whose handler logs with debugPrint and nothing else. Any throw before runApp() therefore left the launch storyboard on screen indefinitely: no UI, no crash, no message — and debugPrint is invisible in profile and release builds, which is where this happens on real hardware. The failure mode is worse than the failures it hides. The preceding commit fixes a startup guard that threw a precise, actionable StateError naming the exact misconfiguration; presenting that as a frozen splash screen is what made it expensive to diagnose. Five connectivity hypotheses were investigated on device before anyone read the guard, because the app looked hung rather than rejected. _init() failures are now caught explicitly, recorded to Crashlytics when Firebase got far enough to initialise, and rendered by StartupFailureApp. StartupFailureApp is deliberately dependency-free: no providers, no services, no theme lookups, no localisation. Everything it could depend on is precisely what may have just failed to initialise, so it renders from nothing but Flutter. The message is selectable because the situation it exists for is a device with no debugger attached; the stack trace is included in debug and profile builds only. Behaviour is unchanged on the success path — runApp(const MyApp()) still runs exactly as before, and the zone handler is untouched for post-startup errors. Verification: flutter test test/unit -> 755 passed, plus 3 new widget tests covering the rendered message, rendering with no ambient scope at all, and selectability. INV-DATA-1: app/lib/main.dart is a path glob of this invariant. No routing behaviour changes — this only alters what is displayed when startup validation has already failed and the app would otherwise show nothing. Failure-Class: none Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011qmdS9crg5qFhan7PCbWvZ
…irst frame _init() awaited AuthService.getIdToken() with no timeout, before runApp(). Any stall there leaves the launch storyboard on screen indefinitely: no crash, no UI, no diagnostic, and nothing a user or developer can act on. This is not hypothetical. Measured on iPhone 17 Pro / iOS 27.0 against a Firebase Auth emulator on a non-loopback host, FirebaseAuth's forced token refresh never returned at all — not an error, just silence. File-backed probes recorded entry to _refreshIdTokenWithRetries with every guard passing (uids matched, session not expired, generation current) and then no further line, ever. Worse, the app could not be launched again until it was deleted, because the cached session made every subsequent start hang on this same call. Note the startup error screen added earlier does not help here: it catches throws, and this is a hang. A timeout is treated as "not authenticated" rather than as an error, because that is what the surrounding code already does — getIdToken() returns null on every failure branch and startup already continues to the sign-in screen. So this only makes a hang behave like the failure it effectively is, and never blocks startup where the previous code would have proceeded. Ten seconds is long enough not to sign out a user on a slow network. resolveStartupAuth lives in its own library, free of Firebase and generated-env imports, so it is testable without running codegen — the same reason startup_routing.dart is separate. Importing main.dart in a test fails on the envied-generated prod env. Implemented as a race rather than Future.timeout(onTimeout:). onTimeout must return the *concrete* future's type, so a callback producing Future<String> rather than Future<String?> makes `() => null` throw a TypeError at runtime, turning a hang-guard into a new startup crash. A test caught exactly that during development and now pins it. Verification: flutter test test/unit -> 762 passed, including 4 new. The guard test supplies a future that never completes and asserts startup still resolves. Failure-Class: none Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011qmdS9crg5qFhan7PCbWvZ
…ry request backend/http/shared.dart:73 refreshes the id token on the way into *every* authenticated request. _refreshIdTokenOnce awaited _tokenGateway.forceRefresh() with no ceiling, so a refresh that stalls rather than fails takes the whole app offline: no error, no snackbar, no timeout, and nothing for a user or a developer to act on. Observed end to end on iPhone 17 Pro / iOS 27.0 against a Firebase Auth emulator on a non-loopback host. The app signed in, ran onboarding normally on its cached token — a clean sequence of 200s in the backend log — and then went permanently silent the moment a refresh was first required. Tapping Confirm on the language step did nothing at all: no PATCH arrived and neither the success nor the failure snackbar appeared, because the await never returned. Backend traffic stopped dead and never resumed. Each attempt is now bounded and a stall is reported as a transient failure, which the surrounding retry loop and every existing caller already handle — getIdToken() returns null on four failure branches today and callers cope with that. So this only makes a hang behave like the failure it effectively is; it never fails a refresh that the old code would have completed. Eight seconds per attempt is far above a healthy refresh and still bounded. 'refresh_timeout' is a distinct failure class rather than reusing 'transient', so a stalled refresh stays distinguishable in telemetry from one that genuinely failed. They have very different causes and very different fixes. The timeout is injectable via AuthService.forTesting, matching the existing refreshDelay seam, so the tests do not wait eight seconds. This supersedes the narrower startup-only bound in the preceding commit as the general fix; that one is kept because it also covers a stall in anything else _init() awaits before the first frame. Verification: flutter test test/unit -> 766 passed, including 4 new. The guard test supplies a refresh that never completes and asserts refreshIdToken resolves, that the result is classified refresh_timeout, that the retry loop still runs, and that a slow-but-successful refresh inside the budget is unaffected. Not a fix for the underlying stall itself: why FirebaseAuth's forced refresh never returns against the Auth emulator on a non-loopback host is still open. This makes that failure survivable rather than fatal. Failure-Class: none Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011qmdS9crg5qFhan7PCbWvZ
There was a problem hiding this comment.
3 issues found across 9 files
Confidence score: 3/5
- In
app/lib/startup_auth.dartandapp/lib/services/auth_service.dart, the timeout path can leaveAuthService.forceRefresh()/getIdTokenResult(true)running in the background, so later authenticated calls may wait on a stale in-flight refresh and a late completion can still overwrite auth state; this is the highest user-impact risk because it can prolong or re-trigger startup/auth hangs—ensure timed-out refresh attempts are isolated/cancelled and cannot mutate shared state after timeout. - In
app/lib/startup_failure_app.dart, hardcoded user-facing strings bypass thecontext.l10n+ ARB flow required byapp/AGENTS.md, which risks untranslated or inconsistent copy across locales—move these strings to localization keys and add them to the ARB files for all supported locales.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="app/lib/startup_failure_app.dart">
<violation number="1" location="app/lib/startup_failure_app.dart:34">
P3: These three user-facing strings are hardcoded, while app/AGENTS.md requires every user-facing string to go through `context.l10n.keyName` and be added to the ARB files (48 locales). The concern in the doc comment that localization would depend on failed initialisation doesn't hold: AppLocalizations delegates load bundled generated assets synchronously and aren't touched by `_init()`, and `MyApp` wires them in the same way (`AppLocalizations.delegate` / `supportedLocales`). To keep the screen localized, add `localizationsDelegates` and `supportedLocales` to this MaterialApp (with `flutter_localizations` delegates) and reference l10n keys; otherwise non-English users see untranslated text and the l10n invariant is violated.</violation>
</file>
<file name="app/lib/startup_auth.dart">
<violation number="1" location="app/lib/startup_auth.dart:36">
P2: When the timeout wins, `Future.any` leaves the shared `AuthService` refresh in flight. Subsequent authenticated requests that need a refresh await that stale operation, and its late result can still mutate auth state after startup proceeds. Make the startup refresh cancellable, or prevent `AuthService` from reusing a refresh after this timeout before returning `false`.</violation>
</file>
<file name="app/lib/services/auth_service.dart">
<violation number="1" location="app/lib/services/auth_service.dart:385">
P2: `.timeout()` races but does not cancel the underlying `forceRefresh()`. In the exact hang scenario this fix targets, every timed-out attempt leaves `getIdTokenResult(true)` pending forever; the retry loop then starts a new one (up to 3 per `refreshIdToken()`), and each later request with an expired cached token spawns more. These orphaned native refresh operations accumulate with no bound. Consider coalescing to a single in-flight native refresh (guard the gateway call so a hang can only ever own one outstanding native operation) or documenting/exposing that repeated timed-out refreshes aren't re-entrant.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| // at runtime — turning a hang-guard into a new startup crash. Racing sidesteps | ||
| // the variance entirely. | ||
| return await Future.any<bool>([ | ||
| getIdToken().then((token) => token != null), |
There was a problem hiding this comment.
P2: When the timeout wins, Future.any leaves the shared AuthService refresh in flight. Subsequent authenticated requests that need a refresh await that stale operation, and its late result can still mutate auth state after startup proceeds. Make the startup refresh cancellable, or prevent AuthService from reusing a refresh after this timeout before returning false.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/lib/startup_auth.dart, line 36:
<comment>When the timeout wins, `Future.any` leaves the shared `AuthService` refresh in flight. Subsequent authenticated requests that need a refresh await that stale operation, and its late result can still mutate auth state after startup proceeds. Make the startup refresh cancellable, or prevent `AuthService` from reusing a refresh after this timeout before returning `false`.</comment>
<file context>
@@ -0,0 +1,39 @@
+ // at runtime — turning a hang-guard into a new startup crash. Racing sidesteps
+ // the variance entirely.
+ return await Future.any<bool>([
+ getIdToken().then((token) => token != null),
+ Future<bool>.delayed(timeout, () => false),
+ ]);
</file context>
| Future<AuthTokenResult> _refreshIdTokenOnce(int generation, String expectedUid) async { | ||
| try { | ||
| final refreshed = await _tokenGateway.forceRefresh(); | ||
| final refreshed = await _tokenGateway.forceRefresh().timeout(_refreshAttemptTimeout); |
There was a problem hiding this comment.
P2: .timeout() races but does not cancel the underlying forceRefresh(). In the exact hang scenario this fix targets, every timed-out attempt leaves getIdTokenResult(true) pending forever; the retry loop then starts a new one (up to 3 per refreshIdToken()), and each later request with an expired cached token spawns more. These orphaned native refresh operations accumulate with no bound. Consider coalescing to a single in-flight native refresh (guard the gateway call so a hang can only ever own one outstanding native operation) or documenting/exposing that repeated timed-out refreshes aren't re-entrant.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/lib/services/auth_service.dart, line 385:
<comment>`.timeout()` races but does not cancel the underlying `forceRefresh()`. In the exact hang scenario this fix targets, every timed-out attempt leaves `getIdTokenResult(true)` pending forever; the retry loop then starts a new one (up to 3 per `refreshIdToken()`), and each later request with an expired cached token spawns more. These orphaned native refresh operations accumulate with no bound. Consider coalescing to a single in-flight native refresh (guard the gateway call so a hang can only ever own one outstanding native operation) or documenting/exposing that repeated timed-out refreshes aren't re-entrant.</comment>
<file context>
@@ -366,7 +382,7 @@ class AuthService {
Future<AuthTokenResult> _refreshIdTokenOnce(int generation, String expectedUid) async {
try {
- final refreshed = await _tokenGateway.forceRefresh();
+ final refreshed = await _tokenGateway.forceRefresh().timeout(_refreshAttemptTimeout);
if (generation != _sessionGeneration || _tokenGateway.currentUser?.uid != expectedUid) {
return const AuthTokenMissingUser();
</file context>
| @@ -0,0 +1,62 @@ | |||
| import 'package:flutter/foundation.dart'; | |||
There was a problem hiding this comment.
P3: These three user-facing strings are hardcoded, while app/AGENTS.md requires every user-facing string to go through context.l10n.keyName and be added to the ARB files (48 locales). The concern in the doc comment that localization would depend on failed initialisation doesn't hold: AppLocalizations delegates load bundled generated assets synchronously and aren't touched by _init(), and MyApp wires them in the same way (AppLocalizations.delegate / supportedLocales). To keep the screen localized, add localizationsDelegates and supportedLocales to this MaterialApp (with flutter_localizations delegates) and reference l10n keys; otherwise non-English users see untranslated text and the l10n invariant is violated.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/lib/startup_failure_app.dart, line 34:
<comment>These three user-facing strings are hardcoded, while app/AGENTS.md requires every user-facing string to go through `context.l10n.keyName` and be added to the ARB files (48 locales). The concern in the doc comment that localization would depend on failed initialisation doesn't hold: AppLocalizations delegates load bundled generated assets synchronously and aren't touched by `_init()`, and `MyApp` wires them in the same way (`AppLocalizations.delegate` / `supportedLocales`). To keep the screen localized, add `localizationsDelegates` and `supportedLocales` to this MaterialApp (with `flutter_localizations` delegates) and reference l10n keys; otherwise non-English users see untranslated text and the l10n invariant is violated.</comment>
<file context>
@@ -0,0 +1,62 @@
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const Text(
+ 'Omi could not start',
+ style: TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.w600),
+ ),
</file context>
kodjima33
left a comment
There was a problem hiding this comment.
All four startup fixes are real: CGNAT 100.64/10 is legitimately private, and the blank-splash hangs are genuine. Holding the merge — Dart Analyze fails the ratchet with a new invalid_use_of_visible_for_testing_member (baseline 0).
The dev Info.plist declared NSAllowsLocalNetworking, which permits plain HTTP only to .local, unqualified hostnames and link-local addresses. A Tailscale address (100.64.0.0/10) is none of those, so every NSURLSession request to a tailnet-hosted dev harness was refused by ATS before it left the device, with NSURLErrorDomain code=-1022. Only Firebase Auth was affected, which is what made this hard to see: it alone reaches the network through GTMSessionFetcher on NSURLSession. Every other call in the app goes through the Dart http package on dart:io sockets, which bypass ATS entirely — so the app talked to the same host on :8000 all day while token refresh failed against :9099. Swap the key for NSAllowsArbitraryLoads rather than adding it. The two cannot coexist: declaring NSAllowsArbitraryLoads alongside NSAllowsLocalNetworking makes the former a documented no-op on any OS that understands the newer key, which silently leaves CGNAT hosts blocked and makes the obvious fix look like it does nothing. Dev-only plist; release builds are unaffected. Verified on iPhone 17 Pro / iOS 27.0 against the local dev harness: a native NSURLSession probe to the Auth emulator goes from code=-1022 to status=200, network-request-failed drops to zero, and sign-in plus onboarding now complete end to end (PATCH /v1/users/onboarding 200 OK). Refs BasedHardware#11730
…NAT/ATS fix generate_ios_dev_info_plist.sh regenerated Info-Dev.plist from scratch on every `setup.sh ios` run and unconditionally added NSAllowsLocalNetworking, silently discarding the NSAllowsArbitraryLoads fix BasedHardware#11652 hand-edited into the checked-in file. NSAllowsLocalNetworking only covers .local/unqualified/ link-local hosts, never a Tailscale CGNAT address (100.64.0.0/10), which is what the documented physical-device setup uses — so every setup.sh ios run silently re-broke device connectivity to the local-dev harness. Reproduced live on a physical iPhone over the real Tailscale path: every NSURLSession call failed with CFNetwork Code=-1022 (the ATS-block signature from BasedHardware#11730) until the generator's output was corrected. Failure-Class: none Fixes BasedHardware#11782.
|
Pushed a follow-up commit to this PR: the CGNAT/ATS fix a couple commits back in this same PR (
Caught live, not just by reading the code: built and ran on a physical iPhone over a real Tailscale path after merging this branch with a couple others — every Filed as #11782, fixed here: |
main.dart calls resolveStartupAuth directly to gate the first frame, so it was never test-only — the annotation was wrong, not the call site. CI's analyzer ratchet caught the resulting invalid_use_of_visible_for_testing_member violation (baseline 0, 1 found) after this branch was pushed. Failure-Class: none
|
All CI checks are green and this is ready for maintainer review/merge — I don't have write access to merge it myself. Summary of what's in this PR as of the latest push: the CGNAT/ATS fix ( |
kodjima33
left a comment
There was a problem hiding this comment.
Four independently root-caused iOS startup defects (CGNAT dev endpoint rejected, silent blank splash on startup throw, unbounded auth refresh) with unit tests for each; dev-flavor plist only, prod signing/ATS untouched.
Four fixes to iOS startup, found while getting a community build to run against the local dev harness on real hardware. They are independent of each other and of the sign-in work that surfaced them.
1.
local_devrejected Tailscale's address rangeEnv._isLocalDevelopmentApiallowed loopback and RFC 1918 only. Tailscale assigns from 100.64.0.0/10 (RFC 6598 shared address space), which is neither, sovalidateApplicationStartupRouting()threw before any network call:This is not an exotic setup. The dev harness binds loopback only by design (
scripts/dev-harness/dev_harness/safety.py:194is a fail-closed guard holding real provider keys), so a physical device cannot reach it on127.xand cannot reach it over the LAN either. A tailnet address is in practice the only route from real hardware to a developer's harness.Measured on iPhone 17 Pro / iOS 27.0, one variable at a time:
OMI_API_BASE_URLhttp://100.105.2.5:8000/http://100.105.2.5:9999/The dead-port run is the discriminator: no responding server is required, which is what pointed at a validation guard rather than a connection. Bounded to the real /10 — tests assert
100.63.xand100.128.xstay rejected so this cannot decay into "any 100.x host".2. A startup throw showed a blank splash screen
_init()runs insiderunZonedGuarded, whose handler logs withdebugPrintand nothing else — anddebugPrintis invisible in profile and release builds. Any throw beforerunApp()left the launch storyboard up indefinitely: no UI, no crash, no message.The failure mode was worse than the failure it hid. Fix 1 above threw a precise, actionable
StateErrornaming the exact misconfiguration; presenting that as a frozen splash is what made it expensive — five connectivity hypotheses were investigated on device before anyone read the guard.StartupFailureAppis deliberately dependency-free: no providers, services, theme lookups or localisation, since all of those are precisely what may have just failed to initialise. Message is selectable because the situation it exists for is a device with no debugger attached.3. Startup awaited the auth refresh with no timeout
_init()awaitedgetIdToken()beforerunApp(). Measured on the same device against a Firebase Auth emulator on a non-loopback host, FirebaseAuth's forced refresh never returned at all — not an error, just silence. File-backed probes recorded entry to_refreshIdTokenWithRetrieswith every guard passing, then no further line. The app could not be launched again until it was deleted, because the cached session made every start hang there.Note fix 2 does not help here: it catches throws, and this is a hang.
4. The forced refresh could freeze every request app-wide
backend/http/shared.dart:73refreshes on the way into every authenticated request, so the same stall took the whole app offline. Observed end to end: the app signed in, ran onboarding normally on its cached token — a clean sequence of 200s — then went permanently silent the moment a refresh was first required. Tapping a button did nothing at all, because neither the success nor the failure path ran.Each attempt is now bounded, and a stall is reported as a transient failure — which the surrounding retry loop and every existing caller already handle, since
getIdToken()returns null on four failure branches today. So this only makes a hang behave like the failure it effectively is; it never fails a refresh the old code would have completed.refresh_timeoutis a distinct failure class so a stall stays distinguishable in telemetry from a genuine failure.This does not fix the underlying stall. Why FirebaseAuth's forced refresh never returns against the Auth emulator on a non-loopback host is still unexplained — the SDK does route it through the emulator (
SecureTokenRequest.swift:129-130builds exactly the URL that answers instantly tocurl), the device reaches the public internet, and ATS permits the plain-http call that sign-in already makes to the same host and port. This makes that failure survivable rather than fatal.Verification
11 new tests. The CGNAT case fails without fix 1 with exactly the
StateErrorquoted above. The hang guards supply futures that never complete and assert startup andrefreshIdTokenboth resolve. Slow-but-successful refreshes inside the budget are asserted unaffected, so neither bound can sign a user out on a slow network.Also exercised on device throughout: iPhone 17 Pro, iOS 27.0, profile build, against a local harness reached over Tailscale.
One implementation note worth flagging for review: the bounds are written as races rather than
Future.timeout(onTimeout:).onTimeoutmust return the concrete future's type, so a callback producingFuture<String>rather thanFuture<String?>makes() => nullthrow aTypeErrorat runtime — turning a hang-guard into a new startup crash. A test caught exactly that during development and now pins it.INV-DATA-1
app/lib/env/env.dart,app/lib/main.dartandapp/lib/startup_routing.dartare path globs ofINV-DATA-1. Production-family routing is unchanged: production keeps its own exact-match branch, fix 1 widens only thelocal_devbranch, and fixes 2-4 change no routing at all. The invariant's MUST NOT clauses all concern production-family endpoints.Failure-Class: none