Skip to content

feat(network): let phones and computers connect without setup - #60

Merged
nixuuu merged 1 commit into
devfrom
feat/network-access-1
Nov 4, 2026
Merged

nixuuu merged 1 commit into
devfrom
feat/network-access-1

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 4, 2026

Copy link
Copy Markdown
Member

Stage 1 of zero-config network access (docs/network-access.md; stacked — the whole stack merges into dev together).

One per-computer switch, Settings → Network access → "Let phones and other computers connect" (off by default on desktop): a single TLS listener on all interfaces with the computer's identity certificate, port picked once and persisted in the DB (changeable in the app; CANOPY_NETWORK_PORT only as a server/container override), auto-detected addresses (LAN, VPN/Tailscale; virtual interfaces skipped) plus manual hostnames, announced to linked computers when they change. Linked computers use it directly — no Desktop-settings detour, no CANOPY_LINK_* env vars, no UI text telling users to set env vars. Migration 0055.

Tests: tests/integration/network-access.test.ts + all linked-computer suites on the shared listener; check:tmp 844 pass / 0 fail.

@nixuuu
nixuuu added this pull request to stack #62 November 4, 2026 14:10
@nixuuu
nixuuu marked this pull request as ready for review November 4, 2026 14:35
@nixuuu
nixuuu merged commit b8429f2 into dev Nov 4, 2026
3 checks passed
@nixuuu
nixuuu deleted the feat/network-access-1 branch November 4, 2026 14:36
nixuuu added a commit that referenced this pull request Nov 7, 2026
## 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

1. **Stale pooled connections after a suspension (main cause).** While
the app sleeps, a NAT mapping expires or the network changes, and the
HTTP/2 connection dies without either side being told. On resume,
URLSession (iOS has no HTTP/2 PING there) and OkHttp (no PING,
`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).
2. **The status stayed "Connected" after resume.** `useStream` kept the
old `live` state until something new arrived. "Gateway unavailable" only
appeared after an error, never while a connect hung.
3. **Sequential probing before every request** (above). Also, a request
canceled while probing left a dead `lastAddress` unmarked.
4. **Android: probes blocked Expo's shared module thread.** Expo runs
every module's `AsyncFunction` on one thread. The probe's blocking
connect + handshake (and a DNS lookup with no timeout) held up `start`
of every request and every other native module.
5. **Gateway: half-open sessions lived forever.** The network access
listener had no liveness check. A vanished phone's streams and their
overview subscriptions stayed open with unbounded queues.

Not a cause: no per-device stream cap on the gateway.
`maxConcurrentStreams: 16` applies 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
`lastAddress` was 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 new `URLSession` on 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`).
- OkHttp `pingInterval(15 s)`. A **stream** with no response headers in
20 s fails with `timeout` and reconnects. Every watched stream starts
with a snapshot, which brings its headers. Unary calls get no new limit.
- Route selection: happy-eyeballs race (next probe 250 ms later, or
right after a failure; the first pin match wins). One shared race for
all waiting requests; canceling a request doesn't stop it. A route that
just worked is reused for 30 s without a handshake. A failure clears the
cache. `reset()` clears the cache and the failed marks. A JS-side probe
deadline covers lookups that never end.
- Android probes run on their own threads (every failure still resolves
the promise).
- Gateway listener: HTTP/2 PING every 20 s; a session that doesn't
answer within 10 s is destroyed, so its streams and subscriptions end.
HTTP/1.1 sockets get TCP keepalive.
- Status: "Reconnecting…" from resume until the first answer, and
"Gateway unavailable" after 12 s even when the connect just hangs.
- Safety rules unchanged: no RPC is replayed after it may have reached
the computer (only probes run again), and the pinned fingerprint is
still the only trust.

## Measurements

Integration test (`tests/integration/mobile-routes.test.ts`, real TLS;
two blackholed routes and a refused one before the computer, dead
`lastAddress`). The same scenarios were run against the old `routes.ts`
from `dev`:

| | before | after |
|---|---|---|
| first request with dead routes first | 4.0 s | 0.56 s |
| no route works → error | 4.0 s | 2.3 s |
| handshakes for 13 requests (12 at once + 1) | 13 per route | 1 |

iOS simulator (iPhone 17 Pro, iOS 26.0, Debug build with this native
module). The before runs used the `dev` JS on the same binary (the
native change only adds `reset`). Isolated gateway + Postgres + scripted
worker on free ports, paired over a proxy route. Measured from the
foreground until the gateway receives the app's new `WatchOverview`;
about 1.2–1.5 s of each figure is device-tool latency:

| scenario (45 s in the background) | before | after |
|---|---|---|
| last route's connections go silent, new ones work (expired NAT) |
**12.0 s**, "Connected" shown while dead | **2.7 s** |
| last route goes fully dead, another works | 2.6 s | 2.8 s |
| gateway network listener restarted | 2.8 s | 2.8 s |

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

- **Real iPhone / Android devices**: not available. The fix ships native
changes through the normal TestFlight nightly. Please check on the
iPhone: minimize, wait a few minutes, switch Wi-Fi ↔ cellular, then
return.
- **Android runtime**: the Kotlin compiles
(`: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 (Bun `node:http2`) answers
client PINGs at once, so OkHttp's ping won't drop healthy connections.
- iOS in the foreground on a network change iOS itself doesn't report:
there's no client PING on URLSession, so a quiet stream there is only
caught by expo-network events or the 20 s header timeout on the next
subscribe.
- The final AppState tweak (track "was in the background", since iOS may
pass through `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, mobile `tsc` + `expo lint`,
`expo export` (ios + android) are clean. `check:tmp` ran 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:
- "Reconnecting…" now also shows right after resume, until the first
answer. Before, the stale "Connected" stayed.
- "Gateway unavailable" / "The gateway is not responding…" now also
shows when a connect hangs for 12 s.
- A stream timeout reuses "Could not connect to this computer. Check the
network, then try again." with the code `(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
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