Repository navigation
fix(mobile): reconnect quickly after background and dead routes - #324
Merged
Merged
Conversation
A phone that returned from the background sent new requests into pooled connections that had died while it was suspended (expired NAT mapping, network change). URLSession has no HTTP/2 PING and OkHttp had no read timeout, so streams waited for hours while the status said Connected. Route selection probed every address one after another before every request, so each dead route cost its full 2 s timeout, again and again. - reset() after the background or a network change: new URLSession on iOS, evicted OkHttp pool on Android; streams subscribe again - OkHttp pings every 15 s; a stream without response headers in 20 s fails and reconnects (unary calls keep no limit, never replayed) - routes race happy-eyeballs style (250 ms stagger), one shared race for concurrent requests, a working route is reused for 30 s - Android probes run off Expo's shared module thread - the gateway pings HTTP/2 sessions and drops silent ones, so their streams and overview subscriptions end - status shows Reconnecting on resume and Gateway unavailable when a connect hangs for 12 s Fixes: #61 Related: #60
nixuuu
added a commit
that referenced
this pull request
Nov 7, 2026
## Problem and cause A linked computer could stall local pages because aggregate RPCs synchronously waited for peer responses. The original peer gathering budget was 3 seconds, matching the BFF's existing 3-second deadline (#20, `66f30fef`), so the BFF could time out before the gateway discarded the failed peer response. Updates loads `/api/updates` → `GetUpdates` → `GetComputerUpdates`. Connectors loads both local `/api/connectors` and merged `/api/bots` → `ListBots`. Overview, threads, models, schedules, worktrees and the linked-agent catalog had the same coupling. Updates and Connectors poll every few seconds; each refresh could repeat the wait. The supplied desktop log contains 425 recurring 504s beginning at 2026-11-07T15:38:55Z, with failures still occurring during read-only inspection at 16:05:26Z, while local health returned 200 in under 1 ms. These failures were current. The old logs cannot identify the exact production RPC or prove a particular half-open socket. The worker governor's `active=5` message is not evidence of causation: linked reads do not consume worker process slots. Mobile also replaced its list with incomplete reconnect snapshots. Available peers were excluded from the offline mirror fallback, so a flap could remove their rows. Paginated mobile thread opening bypassed the mirror seed while a stale link still looked reachable. ## Change - Local aggregate reads return committed mirrors and cached peer snapshots immediately. Bounded, single-flight background reads refresh the linked part; completion events refresh interested catalogs. Ordinary reads allow 10 seconds; update checks allow 120 seconds and installs 15 minutes. A slow read keeps its prior value and cools down for 30 seconds without declaring the computer dead. The cache is limited to 128 keys/16 MiB and four active reads per peer. - Lost links open a per-peer circuit with 30/60/120-second backoff capped at 3 minutes. HTTP/2 PING runs every 15 seconds with a 10-second pong budget, alongside the existing application heartbeat. Authenticated reconnect/discovery, wake and network changes reset backoff. Wake and changed interfaces retire old sockets; route changes flush the new address before rotation, including outbound-only peers. Sessions close explicitly. Saved mTLS pins and TLS 1.3 remain enforced; sent actions are never replayed. - The BFF uses four HTTP/2 pools: local unary calls, linked unary calls, local subscriptions and linked subscriptions. A stalled linked stream cannot queue local thread streaming even when the server allows only one concurrent stream. Outgoing peer calls are bounded separately from incoming calls. Connectors polling and Update all ticks are single-flight. BFF failure logs include only RPC method, duration, status and sanitized message. - Shared domain reconciliation retains linked rows during partial refreshes, even before liveness expires. Presence dims rows and disables peer-dependent actions with a reason. Explicit deletions, authoritative home snapshots and unlink still reconcile removals. Thread reads, including paginated phone history, seed immediately from the durable local mirror. - Mirror frames retain the home's history version, so older pages can extend the immediate local window safely. Mirror cursors resume locally; reconnect replaces them with an authoritative home snapshot. A stale/legacy mirror with a different history version cannot extend a live window. All timing constants and cache/availability rules are documented in `docs/linked-computers.md`; architecture, desktop, mobile, UI API and update docs describe the changed behavior. Proto changes are additive; the frozen update protocol is untouched. ## Covered surfaces | Surface | Behavior while the peer is unavailable | | --- | --- | | Web/desktop/mobile overview, sidebar, thread lists, project filters and command search | Retained mirrored/last-known rows; offline/read-only state; local navigation stays responsive. | | Thread opening, streaming and paginated history | Local mirror seed for reading; sending, steering and other home actions require availability. | | New-thread worker/project/workspace/model choices; project picker; command worker choices | Retained choices; offline execution targets disabled with reasons; a shared project with a local workspace remains usable. | | Worker/project Settings lists and details | Retained rows; remote administration is read-only when unavailable or configuration is not shared. | | Bot lists, bot/schedule targets, schedules and worktrees | Background cached lists; retained offline rows and disabled peer actions. | | Updates and Connectors/access choices | Local data immediately; peer loading/stale/unavailable notes and automatic refresh; cached offline update actions disabled. | | Providers, proxies, agent environment, shared configuration and Devices | Local owner-scoped records; no synchronous peer I/O in page reads. Explicit remote edits remain separate operations. | | Linked agent catalogs/overview and agent/bot `list_agents`, `list_threads`, `list_bots` tools | Local/last-known data from the same cache/mirrors; background refresh with availability/loading state. | | Search and mentions | Sidebar/command search uses retained overview. `SearchThreads` and `#` mentions remain local-home only; file/catalog requests explicitly target a worker rather than merging peers. | ## Validation - Passed: `bun install`, `bun run gen:check`, `bun run typecheck`, `bun run lint`, `bun run format:check`, and the web production build. After rebasing onto current `dev`, generation, typecheck, lint, formatting and the web build passed again. - Full `bun run check:tmp --timeout 20000` on the submitted head: **1,764 passed, 161 skipped, 0 failed across 316 files** (862.22 seconds), with nothing left in the temp directory. Multi-gateway integration files ran sequentially. - Focused linked-timeout regression: 7 passed, covering stalled/half-open peers, recovery with the same mTLS pin, slow healthy reads, outbound-only route changes, and four independent BFF pools with `maxConcurrentStreams: 1`. During a peer stall, local aggregate/settings/tool calls and local streaming stay below 500 ms. - Focused history paging: 6 passed, including mirror-first linked pages, matching home history versions, live handoff, offline pagination and durable resume. The full gate caught and this change fixes the missing history version in mirror frames. - Real browser: two isolated linked gateways with controlled connection blackholes; Updates and Connectors, retained mirrored threads, worker/project pickers, worker Settings, and recovery. Light/dark, 1280×800 and 390×844; short, typical and long computer names. Local APIs returned 200 in 17–64 ms during the outage. Desktop's shared frontend was checked in the browser and its pinned BFF transport in integration tests; an Electron shell was not launched. - Android: Linux-built isolated development client on the restored MacStudio device host, Canopy_Fold. Light/dark; repeated blackholes retain dimmed Read-only threads and readable mirror history, disable sending and remote targets with reasons, preserve local navigation, and recover normally without re-linking. Healthy remote model choices were also checked. The isolated app was removed afterward; the existing app was untouched. Fold closed/open was exercised, but cover-width layout was not independently established. - Own preview tab, gateways, web server, Metro, tunnels and database containers were stopped/removed; production apps were inspected read-only. ## Copy audit (§8) Before: global `Update failed` or whole-page `The gateway request timed out`, despite healthy local data. After: `Waiting for {name}. Local updates are ready.` during background refresh, or a named unavailable note with automatic retry; Connectors explains an incomplete linked bot list beside working local accounts. Retained rows use the existing `Offline`/`Read-only` vocabulary, with short reasons for disabled actions and remote administration. Text uses sentence case, plain language, active voice and the existing glossary. No new confirmations, empty states, humor or glossary terms. Controls use verbs; loading, offline and read-only states have text cues as well as dimming. No transport jargon is exposed in the new notes. Short, typical and long-name browser/device checks are recorded with validation below. Fixes: #20 Related: #324
nixuuu
added a commit
that referenced
this pull request
Nov 8, 2026
## 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
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
This was referenced Nov 13, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
iPhone (TestFlight nightly): after the app is minimized a few times and reopened later, it sometimes can't reach the gateway for a long time.
Asked: does the phone try every route before it reaches the working one? Yes. Before this fix it probed the pairing's addresses one after another (last working one first, each a 2 s TLS handshake) before every request. Each dead route cost its full timeout on every request, and 12 requests at once on resume meant 12 separate races.
Root causes
readTimeout(0)) sent new requests into the dead connection. The route probe opens a fresh handshake, so it succeeded and never helped. iOS request timeout was 24 h, so a stream could wait for hours. Reproduced on the simulator: the gateway got the app's new stream only 12 s after resume, and the status said "Connected" the whole time (a real network can take much longer).useStreamkept the oldlivestate until something new arrived. "Gateway unavailable" only appeared after an error, never while a connect hung.lastAddressunmarked.AsyncFunctionon one thread. The probe's blocking connect + handshake (and a DNS lookup with no timeout) held upstartof every request and every other native module.Not a cause: no per-device stream cap on the gateway.
maxConcurrentStreams: 16applies per connection only. I found no backoff state that survives restarts (backoff resets on resume)."Even restarting the app doesn't help": I couldn't reproduce this part directly. A restart gives a fresh connection pool, but a saved dead
lastAddresswas probed first on every request, which costs its timeout each time. Over a slow or flaky route that adds up. With this fix a dead first route costs 250 ms once, and the working route is then reused for 30 s.Fix
reset()in the pinned transport: a newURLSessionon iOS (running tasks finish on the old one),connectionPool.evictAll()on Android. It runs inside the AppState and expo-network events, before React restarts any stream, after the app was in the background or when the network type or connectivity changes. After a network change, streams subscribe again (epoch).pingInterval(15 s). A stream with no response headers in 20 s fails withtimeoutand reconnects. Every watched stream starts with a snapshot, which brings its headers. Unary calls get no new limit.reset()clears the cache and the failed marks. A JS-side probe deadline covers lookups that never end.Measurements
Integration test (
tests/integration/mobile-routes.test.ts, real TLS; two blackholed routes and a refused one before the computer, deadlastAddress). The same scenarios were run against the oldroutes.tsfromdev:iOS simulator (iPhone 17 Pro, iOS 26.0, Debug build with this native module). The before runs used the
devJS on the same binary (the native change only addsreset). Isolated gateway + Postgres + scripted worker on free ports, paired over a proxy route. Measured from the foreground until the gateway receives the app's newWatchOverview; about 1.2–1.5 s of each figure is device-tool latency:Gateway (
tests/integration/network-liveness.test.ts): a quiet stream survives several PING rounds while the peer answers. Once the path goes silent, the stream ends in under 2 s with test timings. With the old listener it never ends (verified by disabling liveness in the test).Not verified
:canopy-pinned-fetch:compileDebugKotlin, AGP on the Mac). No emulator run: the Mac's disk is 98% full, and Mac emulators stall live HTTP/2 streams anyway. I checked that the gateway (Bunnode:http2) answers client PINGs at once, so OkHttp's ping won't drop healthy connections.inactive) came after the simulator runs. It's covered by typecheck/lint only.Checks
bun install,gen:check,typecheck,lint,format:check,check:tmp(1654 pass, 0 fail), web build, mobiletsc+expo lint,expo export(ios + android) are clean.check:tmpran before the docs and AppState tweaks (mobile-only, no bun tests import them). The new and touched integration tests were re-run after.Copy audit (docs/copy.md §8)
No UI text added or changed. The existing labels are now shown in more states:
(timeout). The code shows only in the details sheet as "Last error".Checklist 1–10: nothing new to check. The error copy is unchanged (what happened, then what to do), and the code stays behind Details.
Fixes: #61
Related: #60