fix(oauth): surface backend outage instead of opening browser to 504 (#1985)
Summary
Fixes #1985 (also refs #1998) — when api.tinyhumans.ai returns a Cloudflare 504 Gateway Time-out on OAuth login, the desktop app currently opens the system browser to a broken page and then silently re-enables the button after 90s with no user feedback. There is no way to tell service down from user cancelled. The same UX gap also makes #1998 (users in China hitting NXDOMAIN / 530 / 503 on the auth + API hosts) look like silent failure. This PR adds:
- A short
/healthpre-flight on click that blocksopenUrl()and surfaces a clear "OpenHuman cloud sign-in is temporarily unavailable" banner when the backend is unreachable. - A background probe on browser-return (focus / visibilitychange / 90s timeout reset) so an outage that starts mid-flow also gets attributed correctly instead of looking like a user cancellation.
What changed
New: app/src/services/backendHealth.ts
checkBackendHealthy({ timeoutMs?, fetchImpl? }) → Promise<BackendHealthResult>.- Uses an
AbortControllerwith a 6s default budget (4s for the inline click pre-flight) againstGET /health. - Discriminated result:
reason ∈ 'timeout' | 'network' | 'http-5xx' | 'resolve-failure'. - Treats 4xx as healthy — the goal is to catch edge/origin outages (Cloudflare 5xx, DNS, offline), not endpoint existence. A
/healththat happens to be 404 in some environment still proves the edge is reachable. - No new dependencies; uses native
fetch+AbortController.
app/src/components/oauth/OAuthProviderButton.tsx
- Pre-flight on click — before
openUrl(loginUrl), runcheckBackendHealthy({ timeoutMs: 4_000 }). Unhealthy → show banner, skip the browser open, re-enable the button. - Post-return probe — after focus / visibilitychange / 90s safety timeout fires and no deep-link round-trip is in flight, fire a non-blocking
checkBackendHealthy()to attribute the "didn't complete" signal. Healthy → silent reset (same as today, user cancelled). Unhealthy → same banner. - A
browserOpenedRefso a pre-flight failure doesn't trigger a redundant probe via the focus listener that gets armed whileisLoading=true.
Tests
- New
app/src/services/__tests__/backendHealth.test.ts— 7 cases: 200 happy / 404 (still healthy) / 504 → reasonhttp-5xx/AbortError→ reasontimeout/TypeError→ reasonnetwork/getBackendUrl()rejection → reasonresolve-failure/ default-timeout regression guard. - Updated
app/src/components/oauth/__tests__/OAuthProviderButton.test.tsx— 6 new cases: parametrized pre-flight failure (eachreason) blocksopenUrland shows banner; post-return probe shows banner when backend is unhealthy; stays silent when backend is healthy (user cancelled); 90s-timeout probe surfaces banner; no double-probe when pre-flight already blocked the browser open. - Updated
app/test/OAuthDiscord.test.tsx,OAuthGitHub.test.tsx,OAuthLoginSection.test.tsx,OAuthTwitter.test.tsx— mockservices/backendHealthwith a default healthy result so their existing happy-path flows aren't blocked by the new pre-flight.
Why this approach
- Fail fast on click — pre-flight catches Cloudflare 504 / DNS / offline before the user is sent to the broken provider page. With a healthy backend, overhead is ~100-200ms; the 4s click budget is well under the typical browser-open latency.
- Catch outages that start mid-flow — the background probe on browser-return covers the case where the OAuth endpoint was up at click time but went down before the user finished.
- Distinguish cancel from outage — without the probe, "OAuth didn't complete" is the only signal, and it fires both for user cancellation and backend down. The probe lets us only surface the banner for genuine outages, so we don't badger users who deliberately cancelled.
- Same fix covers the China-region symptom from #1998 —
reason: 'resolve-failure'/'network'/'http-5xx'all funnel into the same banner, so DNS NXDOMAIN onauth.tinyhumans.aiand 530/503 onapp.openhuman.ai/api.tinyhumans.ainow produce a clear user-visible signal instead of a hung sign-in button. - No architecture change — small, contained fix specifically for the reported failure mode. The reporter's broader suggestion of full offline / local-only mode is out of scope here.
Out of scope
- Fixing the actual server outage / DNS / regional reachability — server-side and infra (incl. the
auth.tinyhumans.aiNXDOMAIN + Cloudflare 530 in #1998), not in this repo. - Full offline / local-only fallback — the second suggestion in both #1985 and #1998. Big architecture change; deserves a separate design discussion.
Test plan
- [x]
pnpm debug unit— full suite green locally (268 files / 2622 tests passed, including the 4 OAuth files that previously failed before the mock update). - [x]
pnpm lint— no new errors/warnings introduced by the new files. - [x]
pnpm compile(tsc --noEmit) — clean.
Manual smoke (recommended before merge)
These exercise the user-visible behavior and cannot be covered by unit tests alone:
- With
api.tinyhumans.aireachable → click Google → system browser opens normally to OAuth (no perceptible added latency). - With backend deliberately unreachable (e.g.
VITE_BACKEND_URL=http://127.0.0.1:1) → click Google → red banner appears, browser does not open. - Backend healthy at click, then taken down mid-OAuth → on browser-return, banner appears within ~6s instead of the user waiting through the 90s safety timer.
Refs #1985, #1998.
Summary by CodeRabbit
-
New Features
- OAuth login now checks backend availability before opening the browser and again after returning, showing a temporary “backend unavailable” banner when needed.
- A short safety timeout ensures users see an unavailable message if the backend is unresponsive.
-
Tests
- Expanded tests cover backend health probe scenarios, pre-flight blocking of browser launch, post-return behavior, and the timeout case.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 1a010a1a-862a-435e-97f9-be97d940cd35
📥 Commits
Reviewing files that changed from the base of the PR and between b3cf1a88dfba80c0d6163ca660d15416d875fbd2 and 2d1bc592a2fa1348754a33414719abb6e78c3d2e.
📒 Files selected for processing (7)
app/src/components/oauth/OAuthProviderButton.tsxapp/src/components/oauth/__tests__/OAuthProviderButton.test.tsxapp/src/services/backendHealth.tsapp/test/OAuthDiscord.test.tsxapp/test/OAuthGitHub.test.tsxapp/test/OAuthLoginSection.test.tsxapp/test/OAuthTwitter.test.tsx
📝 Walkthrough
Walkthrough
Adds a backend /health probe service and integrates pre-flight and return-path health checks into the OAuth provider button; tests and OAuth test harnesses are updated to mock and validate probe outcomes.
Changes
OAuth Backend Health Pre-Flight and Return-Path Probing
| Layer / File(s) | Summary |
|---|---|
Backend health probe service and tests app/src/services/backendHealth.ts, app/src/services/__tests__/backendHealth.test.ts |
Adds BACKEND_HEALTH_TIMEOUT_MS, types, and checkBackendHealthy() that fetches /health with abort timeout; classifies results (healthy, http-5xx, timeout, network, resolve-failure) and records latency; tests cover all outcomes. |
OAuth button pre-flight and return-path health checks app/src/components/oauth/OAuthProviderButton.tsx |
Integrates pre-flight health probe before opening the system browser, tracks browserOpenedRef, and probes backend on return paths (focus, visibility, timeout); sets BACKEND_UNAVAILABLE_MESSAGE and clears loading when unhealthy. |
OAuthProviderButton unit tests and regression tests app/src/components/oauth/__tests__/OAuthProviderButton.test.tsx |
Mocks checkBackendHealthy (default healthy), replaces microtask drains with looped drains, and adds regression tests for pre-flight blocking, post-return probing behavior, banner visibility, and 90s safety timeout. |
Integration test harness mocks for OAuth app/test/OAuthDiscord.test.tsx, app/test/OAuthGitHub.test.tsx, app/test/OAuthLoginSection.test.tsx, app/test/OAuthTwitter.test.tsx |
Adds mockCheckBackendHealthy hoisted mocks and module mocks for ../src/services/backendHealth so OAuth integration tests default to a healthy backend probe. |
Sequence Diagram
sequenceDiagram
participant User
participant OAuthProviderButton
participant checkBackendHealthy
participant getBackendUrl
participant FetchAPI
participant SystemBrowser
User->>OAuthProviderButton: click provider button
OAuthProviderButton->>checkBackendHealthy: call()
checkBackendHealthy->>getBackendUrl: resolve backend URL
alt resolved
checkBackendHealthy->>FetchAPI: GET {backendUrl}/health (AbortController)
FetchAPI->>checkBackendHealthy: response (status / error)
alt healthy
checkBackendHealthy-->>OAuthProviderButton: healthy
OAuthProviderButton->>SystemBrowser: open browser (set browserOpenedRef)
SystemBrowser-->>OAuthProviderButton: user returns (focus/visibility)
OAuthProviderButton->>checkBackendHealthy: probe on return
else unhealthy
checkBackendHealthy-->>OAuthProviderButton: unhealthy -> set BACKEND_UNAVAILABLE_MESSAGE
end
else resolve-failure
getBackendUrl-->>checkBackendHealthy: throw -> checkBackendHealthy returns resolve-failure
checkBackendHealthy-->>OAuthProviderButton: unhealthy -> set BACKEND_UNAVAILABLE_MESSAGE
end
Estimated code review effort
🎯 3 (Moderate) | ⏱️ ~25 minutes
Suggested reviewers
- senamakel
Poem
🐰 I sniff the network, tiny paws in flight,
A pre-flight probe before the browser's light.
If servers nap, I drum the warning bell,
If they're awake, the OAuth dance goes well.
Hooray—health checks keep the login bright!
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The title accurately describes the main change: adding backend health checking to prevent opening the browser on OAuth failures, matching the PR's primary objective of surfacing outage messages instead of opening to error pages. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.
🔧 ESLint
If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.
ESLint skipped: no ESLint configuration detected in root package.json. To enable, add
eslintto devDependencies.
Comment @coderabbitai help to get the list of available commands and usage tips.
Re: review feedback — verification summary
Verified each suggestion against the codebase before acting.
Applied (1 of 5):
- Nitpick — explicit local
vi.mock('../backendUrl', …)inbackendHealth.test.ts— small isolation win; the suite no longer relies on the global mock atapp/src/test/setup.ts:172. Commitb3cf1a88.
Skipped, with reasoning (see inline replies for the two "Potential issue" threads):
try/catcharoundawait checkBackendHealthy(...)in the click handler — the function is contract-bound to never throw. Both rejection paths (getBackendUrl()andfetch) are caught internally and converted to{healthy: false, reason}. There is also a unit test (resolve-failurecase) protecting that contract. An outer try/catch would be defensive code for an unreachable state. (replied inline)- Replace
fetchwithinvoke('core_rpc_relay', …)—core_rpc_relayis the local in-process JSON-RPC relay (http://127.0.0.1:<port>/rpc, bearer-authenticated withOPENHUMAN_CORE_TOKEN). It cannot reachapi.tinyhumans.aiand probing the local core's/healthwould not detect the Cloudflare 504 from issue #1985. Also confirmedapi.tinyhumans.ai/healthreturnsaccess-control-allow-origin: *, so the directfetchworks from the WebView without CORS workarounds. (replied inline) - Namespaced
debuglogger inOAuthProviderButton.tsx— the file already usesconsole.debug/warn/errorubiquitously (8 pre-existing calls in handlers I didn't touch). Migrating only the new additions would create inconsistency; migrating all is out of scope for the #1985 fix. The new code follows the file's existing convention. - Namespaced
debuglogger inbackendHealth.ts— services inapp/src/services/(analytics.ts,meetCallService.ts,daemonHealthService.ts,rewardsApi.ts) all useconsole.*. The new file follows the dominant convention in that directory.
Suite still green: pnpm debug unit OAuth → 5 files / 101 tests passing; pnpm compile clean; targeted lint clean.