Repository navigation
feat(mobile): pair phones over the shared network listener - #61
Merged
Merged
Conversation
nixuuu
marked this pull request as ready for review
November 4, 2026 14:36
nixuuu
added a commit
that referenced
this pull request
Nov 4, 2026
Stage 3 of zero-config network access (stacked on #61). - Remote workers connect over the Network access listener with pinned TLS: every install command carries the full certificate fingerprint; enrollment checks it before sending the token and stores certificate + pin in a private `worker.json`; WorkerLink and UpdateService verify the exact pin. The worker address is set in Settings → Workers; the add-worker wizard can enable network access in one click. `CANOPY_WORKER_HOST/PORT` and `CANOPY_PUBLIC_GATEWAY_URL` are gone. - **Seamless migration of existing workers:** the server's existing worker port keeps serving WorkerLink, Enrollment and the frozen UpdateService, so old workers (incl. self-update) keep working untouched. When network access is on, the gateway upgrades capable workers over their authenticated link: the worker verifies the pin and an authenticated probe on the new route, then atomically rewrites `worker.json` (private `.bak`, original endpoint kept as fallback). Any failure keeps the old link and shows the reason in Settings → Workers. Desktop local mode is unaffected; protocol version unchanged. - Attachment limits move from env to owner settings (Network access → Attachments) with version checks; the desktop/compose BFF body limit covers the max file size. Tests: pinned enrollment, trust storage, WorkerLink/UpdateService over the pin, revoke, wrong pin without spending the invitation, settings durability, upload limits; migration (old-style worker connects, automatic upgrade, failed route keeps the old link, worker without the capability, UpdateService on the old port, restart durability); check:tmp 856 pass / 0 fail.
nixuuu
added a commit
that referenced
this pull request
Nov 6, 2026
## Root cause
The first production iOS build (TestFlight) failed to pair at once with
`[unknown] Connection interrupted. Try again.`, while Android works
against the same gateway.
I reproduced it on an iOS 26.3 simulator with a **Release** build (same
ATS settings as `production`), pairing over HTTPS with pinning against a
throwaway gateway with network access on (self-signed P-256 listener
certificate, reached over Tailscale from the Mac).
The CFNetwork log of the failing request:
```
Connection 2: asked to evaluate TLS Trust
Task <…> auth completion disp=0 cred=0x… ← our delegate: pin matches, .useCredential
Trust evaluate failure: [leaf AnchorTrusted OtherTrustValidityPeriod SSLHostname ServerAuthEKU]
System Trust Evaluation yielded status(-9802)
ATS failed system trust
HTTP load failed, 0/0 bytes (error code: -1200 [3:-9802])
```
- With ATS on, URLSession runs a second system trust evaluation
**after** the delegate accepts the pinned certificate: SSL policy, host
name, system roots. The gateway's self-signed certificate (no SAN or
EKU, 20-year validity) can never pass it.
- I tried setting `SecPolicyCreateBasicX509` plus the pinned certificate
as the only anchor on the trust object first. It made no difference: the
ATS evaluation still failed on `AnchorTrusted` and `SSLHostname`.
- The TLS-only `probe` uses Network.framework, which ATS doesn't cover.
So the route check passed and the first RPC failed.
- Ruled out:
- ALPN/HTTP/2: the handshake completed with `h2` and TLS 1.3 / ECDHE,
which ATS accepts.
- Network and Local Network permission: the probe connected, and Safari
on the phone reaches the gateway.
## Fix
- `app.config.ts`: `NSAppTransportSecurity: { NSAllowsArbitraryLoads:
true }`.
- `NSExceptionDomains` can't take IP addresses, and gateway host names
are set by the user, so a per-domain exception isn't possible.
- `NSAllowsLocalNetworking` is removed: when it is present, iOS
**ignores** `NSAllowsArbitraryLoads`.
- The URLSession delegate's exact SHA-256 pin stays the only trust
decision. The app reaches the computer only through this module (HTTPS
only, pinned, no redirects or cookies).
- **App Store review:** `NSAllowsArbitraryLoads` needs a justification.
Ours: the app connects to a user-hosted server (an IP address or a
custom name) with a self-signed certificate, verified by a SHA-256
fingerprint pinned during pairing. This is noted in `docs/mobile.md`.
## Native error codes in the UI
A failure can now be diagnosed from a screenshot. The code goes in
parentheses; it never includes an address.
- iOS: `onError` carries `NSURLErrorDomain -1200 / -9802` (the domain,
the code and the TLS stream error). Probe failures carry `POSIX 61`,
`TLS -9808`, `DNS …` or `timeout`.
- Android: the exception class and its root cause, e.g.
`SSLHandshakeException / CertPathValidatorException`.
- `pinned.ts` adds the code to the message. `routes.ts` adds probe codes
to "Cannot reach this computer securely…". Stream reconnects show it in
the "Connection lost" banner.
## Verified (iOS 26.3 simulator, Release build, HTTPS + pin, gateway
reached over Tailscale)
- **Before:** `[unknown] Connection interrupted. Try again.` (same as
TestFlight).
- **With error codes, ATS unchanged:** `[unknown] Could not connect to
this computer. Check the network, then try again. (NSURLErrorDomain
-1200 / -9802)`.
- **With ATS relaxed:**
- pairing succeeds;
- Threads shows **Connected** (WatchOverview is streaming);
- New thread → "hello from ios" → the scripted worker's "Echo: hello
from ios" arrives (CreateThread + WatchThread stream).
- The ATS run used the build with error codes, with only its Info.plist
edited to the new ATS dict and re-signed ad hoc. The Mac didn't have the
disk for another full Release build.
- That binary also had three `SecTrustSet*` anchor lines, which I
removed afterwards.
- It did not have the `stream.ts` banner change, which is JS only.
- Gates: `bun install`, `gen:check`, `typecheck`, `lint`, `format:check`
and `expo lint` are clean.
- `check:tmp`: 1454 pass. Three Git-origin tests in
`add-project`/`linked-projects` failed only because I had set TMPDIR
inside the git worktree; they pass with the default TMPDIR. No mobile
tests are involved.
**Not verified:**
- a physical iPhone (TestFlight builds after merge);
- the Android build on a device or emulator: the Mac had no disk left
for a Gradle build. The Kotlin change only adds a `code` field (class
names), and Android typecheck and `expo lint` pass.
## Copy audit (docs/copy.md §8)
| Before | After | Reason |
| --- | --- | --- |
| `Connection interrupted. Try again.` (any non-pin failure) | Before a
response: `Could not connect to this computer. Check the network, then
try again. (code)` | It is a connect failure, not an interruption. What
happened, then what to do. |
| `Connection interrupted. Try again.` | After a response: `Connection
interrupted. Try again. (code)` | Unchanged, plus the native code. |
| `Cannot reach this computer securely. …` | Same text, plus ` (code,
…)` | Probe reasons. |
| `Connection lost. Reconnecting automatically…` | Same text, plus `
(code)` when the transport gave one | Diagnosable from a screenshot. |
- The codes are on the surface, not behind `Show details`. That goes
against §4.4 on purpose: the mobile pair screen and the banner have no
details disclosure, and the task needs the code to be visible in a
screenshot. The codes are short and in parentheses at the end.
- No new glossary terms. No buttons changed.
Related: #61
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
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
This was referenced Nov 13, 2026
nixuuu
added a commit
that referenced
this pull request
Nov 15, 2026
## Change Active subagent watches could exhaust Android's request slots, leaving messages and task actions waiting. The pinned transport now separates bounded unary and streaming dispatchers and cleans up calls, probes and pools when the native bridge is destroyed. Certificate pinning and cancellation remain enforced. This also fixes the issues found during the mobile audit: - Android Back hides the keyboard before closing a form, preserving its draft. - Connector headers use native masked fields. Failed saves retain tokens, headers and OAuth input. - The composer no longer reserves an empty draft slot, and compact text reserves the measured send-button width. Headers and footers have opaque backgrounds. - Intentional unpairing ends on a neutral pairing screen; failed unpairing retains the session, and actual revocation still reports revoked access. Late errors from an old client cannot clear a new pairing. - Settings search finds the added option keywords. Schedule previews use the selected time zone, show its name and discard results after a pattern or zone change. - File and schedule links use the existing `/thread/` route. The Android transport change requires a rebuilt APK; a JavaScript update alone is insufficient. ## Verification - Mobile TypeScript check, oxlint and formatting for edited files, and `git diff --check`: passed. - `bun run check:tmp ./tests/integration/mobile-devices.test.ts`: 11 passed, 0 failed; temporary directory clean. - Android `assembleDebug`: passed; rebuilt APK installed and exercised in the emulator. - Manual Android checks: Queue accepted and executed a message with two active subagents; Stop task completed; Add account and Create bot retained drafts after first Back and closed after second; secrets were masked on screen and in accessibility output; a failed connector save retained input; search found `font` and `contrast`; 09:00 UTC stayed 09:00 UTC on a Europe/Warsaw phone; changing the zone cleared the preview; failed unpair, successful unpair, re-pair and actual revocation behaved correctly. - Visual checks covered light/dark, normal phone width, 360 dp with enlarged text and a wide modal. Native probes covered saturated stream slots, cancellation, reset, pin rejection and teardown. - Copy audit (§8): passed. “Use one header per line” became “Use Header-Name: value in each field” to match the new controls. Add/Paste/Remove actions use verbs, clipboard errors provide recovery, and changed labels fit the checked widths. - Existing Expo ESLint diagnostics remain; comparison of edited files found no new diagnostics before the final rebase. Full repository checks are left to CI. iOS and external OAuth flows were not exercised. Fixes: #61
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.
Stage 2 of zero-config network access (stacked on stage 1).
Phones use the same listener: the pairing QR (v2) carries the full SHA-256 certificate pin and every address (incl. added hostnames); the app handshakes and checks the pin before sending the token, keeps a route list tried by last success, falls back to other routes, and receives pinned route announcements when the computer's addresses change. Native iOS/Android transports with streaming and cancellation.
CANOPY_MOBILE_PORT/CANOPY_MOBILE_GATEWAY_URLand the Tailscale Serve requirement are gone; Settings → Mobile devices shows real status and can enable network access in one click. Migration 0056 revokes old pairings; web and phone say to pair again.Tests: gateway↔phone client over real TLS (one-time codes, wrong pin sends no HTTP, fallback, route push, streaming, revoke, no replay); check:tmp 848 pass / 0 fail. Native modules not yet built/run on devices.