Skip to content

Mobile: stabilise connection + terminal-fit fixes + share one RpcClient per host - #1481

Merged
Jinwoo-H merged 9 commits into
mainfrom
Jinwoo-H/mobile-loadhosts-cache
May 6, 2026
Merged

Jinwoo-H merged 9 commits into
mainfrom
Jinwoo-H/mobile-loadhosts-cache

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Series of mobile reliability fixes on top of the v0.0.3 paste-pair / Keychain release. Centralises connection state into a single shared RpcClient per host, fixes connection churn / stuck-reconnecting, makes Disconnect/Reconnect first-class user actions, and clears two terminal-fit bugs that survived the v0.0.3 cycle.

Changes (in commit order)

  1. 490aa1b — Stop connection churn from Keychain reads + array-identity loops. `loadHosts()` now caches tokens in memory and dedupes concurrent calls. Home effect deps switched from `[hosts]` (new array each render) to a stable `id|endpoint|token` content-key.
  2. 20b64c9 — Dedupe terminals list to silence React duplicate-key warnings. Set-based dedupe in `fetchTerminals` + optimistic-insert guard in `handleCreateTerminal`. Adds the design doc at `docs/mobile-shared-client-per-host.md`.
  3. d16c9be — Single shared RpcClient per host via context provider. New `RpcClientProvider` with refcounted store, 30s idle close timer, and per-host state listeners. All five screens migrated off ad-hoc `connect()`: home, host-detail, accounts, session, plus the pair flows kept on direct connect (intentional). Replaces 3-4 sockets per host with 1.
  4. 05f38f7 — Stale-baseline restore + tab-strip viewport drift. Desktop's safety-net resize on phone-leave was clobbering safeFit's correct DOM-measured fit when the desktop pane geometry had changed since mobile-fit started. Now gated on prior-mobile-dim detection. Mobile re-measures viewport when the tab strip toggles 1↔2 so freshly-created tabs don't subscribe with stale dims.
  5. 2c398b4 — Surface failed connection + Reconnect/Disconnect actions. After 3 failed reconnect attempts, the host card flips from amber "Reconnecting…" to red "Can't connect." Long-press menu adds Reconnect / Disconnect alongside Rename / Remove. Inline Reconnect button on host-detail when in error state.
  6. 619b591 — Distinct icons for Reconnect/Disconnect (RefreshCw / PowerOff) so they don't all look like Rename.
  7. cc651b3 — Disconnect actually visible + survives Reconnect. Mirror effect now flips `hostStates[hostId]` to `'disconnected'` for paired hosts that drop out of `allClients`. `forceReconnect` falls back to active-listener count when prior entry was already closed (otherwise refCount=0 → fresh client got reaped by idle timer).
  8. dadd7b1 — Grey instead of red for plain `Disconnected` (red reserved for actual error states).
  9. 47c7380 — Faster cold-start connect + safety nets:
    • `primeHosts`: home screen feeds already-loaded HostProfiles into the provider so `openEntry` doesn't pay a second Keychain pass behind React state updates.
    • Surface failures: `openEntry` now emits `'disconnected'` on `loadHosts` / `connect` exception so the UI exits the perma-spinner.
    • 5s connect-timeout in rpc-client: belt-and-suspenders against RN WebSockets that occasionally never fire `onopen`/`onerror`/`onclose` (was the "reload Metro to recover" workaround).

Out of scope / known follow-ups

  • Duplicate-prompt artifact when creating a new tab (content reflowed weirdly during phone-fit resize). Not a regression from this branch — pre-exists and would need a server-side viewport hint on `terminal.create` to fully fix.
  • Cold-start Keychain latency itself isn't eliminated; we just stopped paying it twice. A persisted host-metadata-without-token cache could remove the perceived first-load delay entirely.
  • Reconnect-state-listener count proxy in `forceReconnect` is a reasonable approximation but not refcount-perfect across multi-screen scenarios.

Test plan

  • Manual: pair host, navigate home ↔ host-detail ↔ session, browse, create/delete tabs, kill desktop, restore, leave phone, return — connection stays stable and the UI accurately reflects state.
  • Manual: long-press host card on home → Reconnect / Disconnect — both actions take effect immediately and stay in the new state.
  • Manual: force a stale port (run desktop on different port than the paired endpoint) — UI escalates to red "Can't connect" within ~7s, Reconnect button visible.
  • `pnpm tc:web`: clean
  • `pnpm lint`: 7 pre-existing warnings in unrelated GitHub-project / sidekick files; 0 in mobile
  • `pnpm exec vitest run src/renderer/src/lib/pane-manager/mobile-fit-overrides.test.ts`: 35/35 pass
  • mobile `pnpm lint`: 0 warnings, 0 errors
  • mobile `npx tsc --noEmit`: clean

Made with Orca 🐋

Jinwoo-H and others added 9 commits May 5, 2026 20:40
…ty loops

Two bugs that compounded into 'host stuck connecting/reconnecting for
minutes' and 'tab create/delete hangs':

1. host-store.ts: loadHosts() was hitting SecureStore (Android Keystore /
   iOS Keychain) once per host on every call. Each read is 50-200ms;
   navigating between screens called loadHosts() 4x in quick succession.
   Cache the token per hostId in memory (invalidated on save/remove)
   and dedupe concurrent loads via an in-flight promise.

2. app/index.tsx: home-screen useEffect depended on the hosts array
   reference. loadHosts() returns a fresh array each call (e.g. from
   useFocusEffect on every navigate-back), so every navigation tore down
   and rebuilt every WebSocket. Stale sockets piled up on the desktop
   until it hit MAX_WS_CONNECTIONS=32 and started rejecting with WS
   close 1013, which the mobile reconnect loop didn't recognize as
   terminal. Depend on a sorted+serialized id|endpoint|token key so
   rebuilds only happen when the actual connection-shape changes.

Co-authored-by: Orca <[email protected]>
…rnings

Add a guard in handleCreateTerminal's optimistic insert and a
defense-in-depth dedupe in fetchTerminals's setState. The user-visible
'Encountered two children with the same key' error fires when the
optimistic append of a freshly-created handle races with a parallel
fetchTerminals() that already pulled the canonical list containing
that handle. Symptom is harmless to function but breaks React
reconciliation expectations.

Also adds docs/mobile-shared-client-per-host.md — design doc for the
deeper architectural fix (one WebSocket per host instead of one per
screen) that the recent host-store cache + useEffect identity hotfix
only partially mitigates.

Co-authored-by: Orca <[email protected]>
Implements docs/mobile-shared-client-per-host.md.

A new RpcClientProvider sits at the root of the app and owns one
RpcClient per host. Screens consume the shared client via
useHostClient(hostId) (single screen) or useAllHostClients(hostIds)
(home screen). The provider tracks a refcount per host; when it
drops to zero, a 30-second idle close timer is armed. Re-entry
within the window cancels the timer and reuses the live client.

Result: a paired host has at most ONE active WebSocket at any
time, regardless of how many screens are mounted. This removes
the connection-churn pattern that previously caused stuck-
reconnecting and WS code 1013 'maximum connections reached'
rejections from the desktop.

Pair flows (pair-confirm.tsx, pair-scan.tsx) continue to call
connect() directly with explicit close()'s — they need transient
clients before the host record exists in loadHosts().

removeHost() in the home and host-detail screens calls
useCloseHost() to force-close the live client before the host
record disappears, preventing socket leaks.

Co-authored-by: Orca <[email protected]>
Bug 1 (desktop): when mobile leaves and the desktop's pane geometry has
changed since mobile-fit started (split closed, window resized), the
fallback safety-net resize in TerminalPane was clobbering safeFit's
correct DOM-measured fit by forcing xterm back to the captured
mobile-fit baseline. Now thread the prior mobile-fit dims through the
override-change event and only fire the fallback when xterm is still
parked at those mobile dims (i.e. safeFit didn't move it).

Bug 2 (mobile): the tab strip is hidden until a 2nd terminal exists.
Crossing the 1↔2 boundary shrinks the visible terminal area by ~40px,
but viewportRef still held the pre-tab-strip measurement, so the
freshly-created tab subscribed with stale dims. Invalidate the
measurement flag on tab-strip visibility transitions so the existing
init→measure→resubscribe self-correcting loop refreshes the viewport.
Also extracted scheduleViewportRefit into a useCallback so other
layout-affecting state changes can drive it.

Co-authored-by: Orca <[email protected]>
After ~3 failed reconnect attempts, escalate the per-host status from
'Reconnecting…' to a red 'Can't connect' label. Replaces the binary
green/grey dot on the home host card with the existing StatusDot
component so reconnecting (amber), disconnected/auth-failed (red), and
connected (green) are all visually distinct.

Long-press a host on the home screen now offers Reconnect (forces a
fresh socket immediately, bypassing exp-backoff) and Disconnect (tears
down the live client; navigation will lazily re-open). Also adds an
inline Reconnect button next to the host-detail header status text
when the connection is in an error state.

Plumbs reconnectAttempt through RpcClient.getReconnectAttempt() and
exposes it via useReconnectAttempt(hostId) in the RpcClientProvider.

Co-authored-by: Orca <[email protected]>
Reconnect → RefreshCw, Disconnect → PowerOff. Previously both fell
through to ActionSheetModal's default Edit3 (pencil) icon, making them
visually indistinguishable from Rename.

Co-authored-by: Orca <[email protected]>
Disconnect appeared to be a no-op because the home host card kept its
last 'Connected' label after the entry dropped out of allClients —
the mirror effect only ever copied state FROM allClients into
hostStates and had no path to surface 'disconnected' for paired hosts
that no longer have a live client.

Also fixes Reconnect after Disconnect: forceReconnect's restored
refCount was 0 (the closed entry was gone), so the freshly-opened
client tripped the 30s idle-close timer instead of staying alive.
Fall back to the active-listener count as a refcount proxy when the
prior entry was already closed.

Co-authored-by: Orca <[email protected]>
Disconnected is a passive/expected state (e.g. user tapped Disconnect)
— red is too alarming. Reserve red for actual error states
(auth-failed, can't-connect after repeated retry failures).

Co-authored-by: Orca <[email protected]>
Three issues compounding on cold start:

1) Double Keychain pass. The home screen ran loadHosts() in its
   focus-effect, then useAllHostClients's effect fired acquire(hostId)
   which kicked openEntry, which ran loadHosts() AGAIN. Even with the
   in-memory inflight dedupe, this serialised behind the first call
   and added React-render latency between them. Add a primeHosts(hosts)
   API on the provider so screens can hand already-loaded HostProfiles
   directly to the entry-opener, skipping the second load entirely.

2) Permanent stuck on opener failure. If loadHosts() or connect()
   threw inside openEntry, the failure was silently swallowed (the
   acquire-side .then() had no catch and pendingOpens was already
   cleared). Subsequent renders would re-acquire and short-circuit on
   the now-empty store. Catch both paths and emit a 'disconnected'
   notification so the UI exits the perma-spinner state and Reconnect
   becomes usable.

3) WebSocket implementations on RN occasionally never fire
   onerror/onclose for an unreachable host (observed when waking the
   device or with stale DNS). Add a 5s connect-timeout that
   force-closes the WS so the existing reconnect path takes over —
   replaces the 'must reload Metro to recover' workaround.

Co-authored-by: Orca <[email protected]>
@Jinwoo-H
Jinwoo-H merged commit 087c00b into main May 6, 2026
4 checks passed
@Jinwoo-H
Jinwoo-H deleted the Jinwoo-H/mobile-loadhosts-cache branch May 6, 2026 01:58
Jinwoo-H added a commit that referenced this pull request May 6, 2026
…-progress pairs

The 5s CONNECT_TIMEOUT_MS added in #1481 was a speculative band-aid for
'WS sometimes never fires onopen' — but in practice it was force-closing
perfectly fine connections that hadn't completed by 5s (notably first-time
QR pairing on iOS, where Local Network permission prompt blocks the WS open
for several seconds).

Worse, the force-close transitioned state to 'reconnecting' (not
'disconnected'), so waitForConnected() never rejected and sendRequest()
hung. Combined with reconnect re-firing the timer, the result was an
infinite 'Connecting…' loop with no surfaced error.

Pair flows hit this hardest because they call connect() directly without
the shared RpcClientProvider, so there's no UI state listener to even show
'reconnecting' to the user — just the spinner.

Removing the timer entirely. The handshake-timeout (5s, post-onopen) still
catches genuinely stuck handshakes. If we hit a real 'never fires onopen'
case later, we can revisit with proper instrumentation rather than a
guess at the symptom.

Co-authored-by: Orca <[email protected]>
buf0-bot Bot pushed a commit that referenced this pull request May 8, 2026
Split session screen's clearTerminalCache cleanup into a mount-only effect; included client identity in home-screen wireUp dep key via a WeakMap-derived clientKey so forceReconnect re-attaches subs.

Findings addressed:
- mobile/app/h/[hostId]/session/[worktreeId].tsx:436 — clearTerminalCache fires on every client identity change
- mobile/app/index.tsx — useEffect deps array uses inline expression — runs every render

Rebased onto current main.
nwparker pushed a commit that referenced this pull request May 8, 2026
Split session screen's clearTerminalCache cleanup into a mount-only effect; included client identity in home-screen wireUp dep key via a WeakMap-derived clientKey so forceReconnect re-attaches subs.

Findings addressed:
- mobile/app/h/[hostId]/session/[worktreeId].tsx:436 — clearTerminalCache fires on every client identity change
- mobile/app/index.tsx — useEffect deps array uses inline expression — runs every render

Rebased onto current main.

Co-authored-by: orca-bot <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Split session screen's clearTerminalCache cleanup into a mount-only effect; included client identity in home-screen wireUp dep key via a WeakMap-derived clientKey so forceReconnect re-attaches subs.

Findings addressed:
- mobile/app/h/[hostId]/session/[worktreeId].tsx:436 — clearTerminalCache fires on every client identity change
- mobile/app/index.tsx — useEffect deps array uses inline expression — runs every render

Rebased onto current main.

Co-authored-by: orca-bot <[email protected]>
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