Skip to content

fix(mobile): connect reliably over tailscale and explain failures - #361

Merged
nixuuu merged 1 commit into
devfrom
fix/mobile-gateway-connect
Nov 8, 2026
Merged

nixuuu merged 1 commit into
devfrom
fix/mobile-gateway-connect

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Cause and evidence

A gateway can be reachable while every phone route is rejected by the fixed 2 s TLS probe deadline. This reproduces hypothesis (a); it does not establish that a real phone's Tailscale radio/tunnel was the source of the delay.

The isolated Bun client fixture uses the actual pinned TLS listener, a TCP proxy delaying the first TLS reply by 3.5 s on every connection, one DNS failure and one blackholed route. Before the change, the request failed after 2.26 s despite the healthy listener. After the change, it connects in about 9.3 s, including a second probe and a separately delayed RPC connection. The gateway receives exactly one RPC. Ordinary dead-first-route selection still completes in about 0.5 s.

The combined error hid which address failed (hypotheses b/c). There is no evidence of excessive route counts, a per-device limit or a listener concurrency problem. Source review also found that Android's reset only evicted idle sockets; an active, half-open HTTP/2 connection could still be reused. Slow-pong integration coverage demonstrates why a short pong deadline can close an otherwise healthy session; it does not prove that this happened on the maintainer's phones.

The original 2 s probe is from #61, before #324 (4f3f1c55, checked against #324's parent). #324 reworked the race, added liveness limits and introduced the pool reset being corrected here.

Change

  • Keep the shared, 250 ms staggered race and 30 s route cache. Give a timed-out handshake one additional 8 s recovery attempt after its fast 2 s attempt. DNS failures, refusal and pin mismatches do not trigger that recovery. JS deadlines also bound stuck DNS/native promises; losing probes close their native sockets.
  • Prefer the pinned Tailscale IP over MagicDNS. Share a successful probe immediately, including while RPC headers are pending. Reset cancels the previous race; stale results cannot restore its route. Caller cancellation does not demote a healthy shared route.
  • Keep “Reconnecting…” while a bounded route race is pending. “Reconnect now” refreshes native connections and restarts all subscriptions with fresh backoff. A received stream value continues to reset its backoff. Android gets a separate new pool, including when old connections still carry streams.
  • Allow 60 s for gateway PONGs (20 s checks; at most about 80 s before an unresponsive session is removed), 60 s Android PING intervals, 15 s native connection/server handshake limits and 40 s for initial stream headers. Quiet streams retain no read timeout. No RPC is replayed after it may have reached the computer; pinning and owner authorization stay enforced.

Diagnostics

Details now shows each route's kind, truncated host/port and result: DNS failed, timed out with elapsed milliseconds, TLS pin mismatch, connection refused or OK with latency. It marks the route in use, distinguishes request failures from probe results and offers Copy details with full hosts and timestamps. Diagnostics stay in memory and exclude tokens, fingerprints and payloads.

Desktop/server gateway logs record timestamped TLS/session starts, protocol, listener port, session ID, close reason/duration and liveness timeouts. They contain no peer addresses, certificates, credentials, headers or payloads. pin_check=client_side is deliberate: the gateway cannot attest that its client checked the server pin. The phone's successful probe confirms that comparison.

Verification

  • Focused real-TLS tests: 14 pass, including delayed routes, DNS failure, blackholes, IP preference, cache reuse while headers are pending, cancellation/reset, refusal/pin failure, no replay after header/body failures, slow pongs and dead-session cleanup.
  • Passed: bun install, bun run gen:check, root/mobile typecheck, root lint/format check, web build and mobile bunx expo lint.
  • Full bun run check:tmp: 1808 pass, 161 skip, 0 fail (1969 tests across 323 files, 942.46 s); temp check passed. Temp data stayed under the worktree; GIT_CEILING_DIRECTORIES prevented empty test directories from inheriting its enclosing repository. An initial run exposed that environment issue; the complete run passed with the boundary set.
  • Android local-module :canopy-pinned-fetch:compileDebugKotlin passed on Linux with a private SDK/JDK, no daemon, 2 workers, in-process Kotlin and a 2 GB Gradle heap. CNG prebuild and Gradle clean passed; generated native output was removed. Swift's native parser passed on macOS over stdin, without producing files or launching an app. No EAS/store builds or publication.

Unverified: iOS compilation and native device/visual QA (light/dark, phone/tablet and clipboard interaction). The reproducible measurement uses the authorized Bun client-library alternative, not a physical radio or the maintainer's running apps. Native changes require new builds; the existing fingerprint runtime policy prevents an OTA update from calling the new native API on old binaries.

Copy audit — docs/copy.md §8

  • 1–2: the aggregate route error now says “Cannot reach this computer securely. Check the connection, then reconnect.” Technical route outcomes remain behind Details, in English, with sentence case and spaced units.
  • 3–4: “Copy details” names its action. “Reconnect now” retains its action and now refreshes the whole connection. Copy failure explains how to select/copy the text instead.
  • 5–8: no new empty state, repeated route-in-use heading, optional-dependency warning or sentence with “soul”. Existing availability copy is unchanged; pending probes keep the reconnecting state.
  • 9: long hostnames use middle truncation, results wrap separately, the list scrolls and existing phone/tablet overlay sizing and theme tokens apply. Native visual QA remains unverified as stated above.
  • 10: every outcome and the active route have text labels; meaning does not rely on color or icons.

Fixes: #61
Related: #324

@nixuuu
nixuuu marked this pull request as ready for review November 8, 2026 17:20
@nixuuu
nixuuu merged commit 6c70640 into dev Nov 8, 2026
12 checks passed
@nixuuu
nixuuu deleted the fix/mobile-gateway-connect branch November 8, 2026 17:21
nixuuu added a commit that referenced this pull request Nov 9, 2026
The phone now keeps a verified route until transport failure, network
change, return from background, Reconnect, or removal of that address.
Long-lived streams and quiet periods no longer cause a new race after 30
seconds, so normal requests keep their connection and Details keeps its
route results.

- Response headers and stream data/heartbeats confirm the current
selection. Late responses or failures from an abandoned selection cannot
restore or demote a newer one, including a new selection of the same
address. RPCs that may have reached the computer are never replayed.
- Added/reordered addresses retain the working route and live streams.
There are no background upgrade probes. The phone drops private IPv4
`.0` candidates from old pairings and persists the sanitized list even
when its last working address stays the same.
- Gateway advertisements exclude virtual/container/macOS bridge
adapters, unrelated utun interfaces, non-unicast/link-local/loopback
addresses, and subnet network/broadcast endpoints using the actual mask.
/31 and /32 host routes, Tailscale IP/MagicDNS, physical LAN and
configured public addresses remain supported. Pairing, overview
announcements and UpdateNetworkAccess use the existing shared address
list.

The 30-second cache was introduced by #324 and retained by #361,
verified in git history. The gateway change ships with the
desktop/server update; mobile changes are TS only and remain compatible
with OTA.

Validation:

- 47 distinct focused tests pass: route policy without networking, real
pinned-TLS streaming/recovery/no-replay, macOS/Linux/Windows interface
samples and subnet boundaries, network access, phone port
changes/address propagation and Tailscale advertisement ordering.
- Passed: frozen-lockfile install, root typecheck, root lint,
format:check, gen:check, web build and ESLint for all changed mobile
transport files. Full local check:tmp was intentionally omitted as
requested; CI remains the full-suite gate.
- EAS CLI 27.4.1 production fingerprints match the starting dev commit
5e07154 on both platforms: iOS
`6ddec9ef559ee0095ac33e94ff9418a942053b17`, Android
`5f6eae3ab278f1cd543e9ed763f923a319b65ec9`. No native/config/dependency
changes or OTA publication.
- Extra whole-app Expo lint reports 36 errors and 3 warnings in
unchanged React UI files; none are in the changed transport files.
Physical-phone QA and E2E were not run. The defensive private IPv4 `.0`
filter is a documented heuristic because pairing routes carry no subnet
mask; it can omit a valid `.0` host in a larger private subnet. Gateway
filtering uses the actual mask.

Polish network/mobile documentation is updated. Copy audit (docs/copy.md
§8): no UI text or layout changes; existing English route/result labels
are preserved.

Fixes: #324
Related: #361
nixuuu added a commit that referenced this pull request Nov 10, 2026
Repeated failures against an unreachable paired gateway made the mobile
sheet alternate between “Reconnecting…” and “Gateway unavailable”. Route
probes erased their previous results, the sheet changed height, and the
sidebar banner could unmount an open sheet. Independent requests could
also start another failed route race as soon as the preceding race
finished.

Availability and retry activity now use one shared domain state machine
across mobile and web/desktop. After 3 failures or 12 seconds without
success, “Gateway unavailable” stays until a successful stream
snapshot/resynchronization. Retry activity appears in a reserved line.
Retries use 1/2/4/8/16/30-second backoff with 80–100% jitter;
network/foreground/manual reconnect reset the delay without clearing
unavailable.

- Mobile route rows retain their last result while checking, use fixed
heights and a bounded scroll area. All requests share the failed route
race’s cooldown; no sent RPC is replayed.
- The mobile sheet remains mounted through retries, manual reconnect and
recovery. The sidebar banner overlays the list. Web/desktop has a
matching status popover, manual reconnect and an overlay banner below
the header.
- Documented states, transitions, route cooldown and lifecycle resets in
`docs/mobile.md` and `docs/ui-api.md`. No native, dependency or protocol
changes.

## Validation

- Passed: `bun install`, `bun run gen:check`, `bun run typecheck`, root
`bun run lint`, `bun run format:check`, and the production web build.
- Focused domain/transport/route tests: 32 passed, 333 assertions, 0
failed. Coverage includes sticky unavailable, hanging opens, exponential
backoff/cap/jitter, lifecycle/manual resets, late callbacks,
linked-computer outages, diagnostics retention and independent-request
cooldown.
- Browser: stopped and restarted a disposable gateway; sampled title,
open state, panel/button geometry and content positions every 200 ms. No
unavailable-to-reconnecting bounce, sheet closure or content movement;
automatic recovery succeeded. Checked light/dark and desktop/phone
widths with short and long thread names. Measured retry intervals grew
exponentially to the capped range; manual reconnect restarted
immediately without clearing unavailable.
- Both production fingerprints generated with `[email protected]` are
unchanged: iOS `6ddec9ef559ee0095ac33e94ff9418a942053b17`, Android
`5f6eae3ab278f1cd543e9ed763f923a319b65ec9`.

Limitations: native iOS/Android visual QA was unavailable. Full
`check:tmp` was not run; this task’s verification scope permits focused
tests. Additional Expo ESLint reports existing errors in unchanged
files; changed mobile UI files have no ESLint errors (the keyed recovery
memo has one dependency warning). Root oxlint and all requested checks
above pass. Evidence is kept outside the repository.

## Copy audit — docs/copy.md §8

1. “No route in use” / “Checking routes…” → “Routes”; per-route
replacement status → last result plus “Checking route” activity. These
distinguish availability from an attempt without rewriting the heading.
Added “Retrying in N s” / “Retrying…” in a reserved line; digits are
localized, units spaced, sentence case retained.
2. Glossary unchanged. “Reconnect now”, “Copy details” and “Open
Tailscale” name actions. The web popover explains the last known state
and automatic reconnect; technical failures remain in Details. Tailscale
guidance stays in the description while the availability title remains
stable.
3. No new empty states, duplicated availability heading,
optional-dependency warning or expressive sentence. Existing failure
copy retains its automatic resolution/manual reconnect action.
4. Short, typical and long thread titles checked at desktop and phone
widths in both themes; route hosts keep middle truncation and results
have a fixed row. Native text sizing/layout remains unverified as noted
above.
5. Availability and countdown have text labels; checking activity has an
accessible label. Color is supplementary and spinners respect reduced
motion.

## Regression attribution

The merged diff for #361 explicitly introduced `down && stale ===
subscriptionKey && !routes.pending`, which returns the availability
presentation to reconnecting whenever a new probe begins. This fixes
that condition and the resulting presentation instability. #366’s
Tailscale hint and fixed retry interval were checked as context; they
did not introduce that condition.

Fixes: #361
Related: #366
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant