Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(mobile): probe network changes and refresh activity leases #5154

Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromt3code/mobile-reconnect-hardeningopened View on GitHub

Mobile can miss Wi-Fi/cellular changes and leave activity leases stale after reconnecting.

Probe the current session when the active network interface changes. Keep retry delays unchanged, and report current activity after each newly connected session generation. Keep the current session owner and credential handling. The earlier Bun-wide idle-timeout change is removed.

Verified on current main with 77 focused tests, mobile and client-runtime typechecks, targeted lint, and formatting. The new activity test waits for typed debounce and report receipts.

Device background/resume, real network switching, and live relay/tunnel behavior were not tested. No UI changes.

Original work by Theo Browne and Julius Marminge with Claude Code and Codex. Original commit authors and co-authors are preserved. Updated by GPT-5.6 Sol in Codex.


Note

Medium Risk Touches connection supervisor wakeup and probe/reconnect logic plus mobile lifecycle networking; mistakes could cause reconnect storms or stale leases, but behavior is heavily tested and path-change wakeups are explicitly non-disruptive during backoff.

Overview Mobile now detects Wi‑Fi/cellular interface changes (even when isConnected stays true) and emits a network-path-changed wakeup while the app is active and online. The shared supervisor probes the current session with the 3s mobile probe timeout; a failed or timed-out probe reconnects immediately without shell resubscription. During backoff, path-change wakeups are ignored so flapping interfaces do not shorten retry delays.

The mobile background activity reporter triggers another debounced serverReportClientActivity when an environment reaches a new connected session generation, so activity leases are restored after reconnect if an earlier report had no RPC session.

Supporting changes: pure network-path-change helpers and unit tests, ping timeout info logging on RPC sessions, supervisor/wakeup tests (including a queue-based test harness), shell-sync test tightening, and user/internal docs for mobile network behavior.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 1d5093b80e37e80dcf9b92a9af7146c7dd5648d7. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Probe connected sessions on mobile network changes and refresh activity leases on reconnect

  • Adds a network-path-changed advisory wakeup that fires when the mobile app's known network interface changes while online and active, prompting a liveness probe of the current session with a mobile timeout
  • The supervisor consumes network-path-changed without interrupting connection establishment or shortening retry backoff; a failed probe triggers an immediate reconnect through the existing wake-probe path
  • Adds a NetworkPathBaseline model in network-path-change.ts that records the first known interface asynchronously and requests probes only on genuine interface transitions, not repeated or unknown observations
  • Updates the mobile activity reporter in background-activity.ts to queue a debounced activity report when an environment reaches a newly connected supervisor generation, deduplicating per generation
  • Behavioral Change: ConnectionWakeup gains a new network-path-changed variant; any out-of-tree consumer pattern-matching on that type without a catch-all will fail to compile
📊 Macroscope summarized 1d5093b. 8 files reviewed, 1 issue evaluated, 1 issue filtered, 0 comments posted

🗂️ Filtered Issues

packages/client-runtime/src/connection/supervisor.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 424: Adding network-path-changed to the probe branch also routes a failed path-change probe through wakeProbeFailed. After the failed probe tears down the lease, the run loop resets the retry ladder and starts the next connection immediately, so a network-change failure skips the normal first backoff delay despite waitForRetrySignal explicitly treating these wakeups as advisory. This can cause reconnect churn on a flapping interface. [ Out of scope (triage) ]
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      🚥 Pre-merge checks | ✅ 3 | ❌ 2

      ❌ Failed checks (2 warnings)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      Description check⚠️ WarningThe description explains the main mobile issue, the intended fix, testing, limitations, and lack of UI changes. However, it omits several changes in the pull request, including warm shell resume, jitt…Update the description using the repository template. Add explicit What Changed, Why, UI Changes, and Checklist sections. Document all current changes, including warm shell resume, jittered reconnect backoff, network-path wakeups, activity …
      ✅ Passed checks (3 passed)
      Check nameStatusExplanation
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Title check✅ PassedThe title clearly summarizes the mobile network probing and activity lease refresh changes. It is concise and relevant, even though it does not describe every runtime and server change.
      Full details: Description check

      Explanation

      The description explains the main mobile issue, the intended fix, testing, limitations, and lack of UI changes. However, it omits several changes in the pull request, including warm shell resume, jittered backoff, RPC ping-timeout logging, and the 30-second Bun WebSocket idle timeout. It also conflicts with the changeset by stating that the Bun idle-timeout change was removed.

      Resolution

      Update the description using the repository template. Add explicit What Changed, Why, UI Changes, and Checklist sections. Document all current changes, including warm shell resume, jittered reconnect backoff, network-path wakeups, activity reporting, RPC ping-timeout logging, and the 30-second Bun WebSocket idle timeout. Resolve the conflicting statements about retry delays and the Bun idle timeout.

      • Fix all pre-merge checks with AI

      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. Cursor Bugbot has reviewed your changes using high effort and found 3 potential issues.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 4abafa4cc621b43989fe0c7c943d80541fe4d416. Configure [here](https://www.cursor.com/dashboard/bugbot).
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This change alters production connection behavior across mobile lifecycle handling, the shared supervisor, and activity leases: network transitions can trigger probes, reconnects, and additional reports. Although the behavior is covered by focused tests, the cross-component runtime impact merits human review.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. Actionable comments posted: 2

      Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (1)
      patches/@effect__platform-bun@4.0.0-beta.102.patch (1)

      5-22: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

      Add focused tests for the Bun WebSocket patch behavior.

      The current perMessageDeflate test runs with NodeHttpServer.layerTest, so it does not cover the Bun runtime. Add a companion test for both patched Bun server variants that exercises compression negotiation plus a compressed round trip, and add a separate idleTimeout: 30 close-path test with deterministic close receipts or configuration.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@patches/`@effect__platform-bun@4.0.0-beta.102.patch around lines 5 - 22, Add
      focused Bun runtime tests for both patched Bun server variants, alongside the
      existing perMessageDeflate coverage, verifying negotiation and a compressed
      client/server round trip. Add a separate Bun test for idleTimeout: 30 that
      deterministically verifies the connection-close receipt or configured timeout
      behavior, using the relevant Bun server test symbols and avoiding
      NodeHttpServer.layerTest.

      Source: Coding guidelines

      🧹 Nitpick comments (2)
      packages/client-runtime/src/state/shell.ts (1)

      190-196: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Reduce the implementation narrative.

      Replace this branch-by-branch comment with a short caller-contract comment, or extract the branch into a named helper. The current comment describes local behavior in detail instead of how makeSubscribeInput is used.

      As per coding guidelines, “Use comments mainly to describe how a function is used; avoid annotating every line of behavior, and move comments when code moves.”

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/client-runtime/src/state/shell.ts` around lines 190 - 196, Replace
      the detailed branch-by-branch comment near makeSubscribeInput with a concise
      caller-contract comment describing when this subscription input is used and its
      expected completion behavior. Do not document internal replay, snapshot, or
      HTTP-path mechanics there; preserve the existing implementation unchanged.

      Source: Coding guidelines

      packages/client-runtime/src/state/shell-sync.test.ts (1)

      50-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Infer the session helper return type.

      Remove : RpcSession.RpcSession. If validation is required, apply satisfies RpcSession.RpcSession to the returned object. The helper is local to this test file, so TypeScript can infer its return type.

      As per coding guidelines, “Prefer inferred types over explicit annotations and do not use any.”

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/client-runtime/src/state/shell-sync.test.ts` around lines 50 - 58,
      Update the local session helper to remove the explicit RpcSession.RpcSession
      return annotation and let TypeScript infer the returned object type. If
      structural validation is needed, apply satisfies RpcSession.RpcSession to the
      returned object without changing its behavior.

      Source: Coding guidelines

      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@packages/client-runtime/src/connection/supervisor.test.ts`:
      - Around line 912-937: Replace the fixed Effect.yieldNow loop in the “does not
      cut backoff short when the network path flaps” test with a deterministic typed
      wait. Extend the visible harness or use TestClock so the test awaits
      confirmation that both network-path-changed signals were consumed before
      asserting prepareCount and supervisor.state.phase, while preserving the backoff
      and no-early-retry assertions.
      
      In `@packages/client-runtime/src/state/shell-sync.test.ts`:
      - Around line 397-419: Replace the polling loops around the
      “application-active”, “application-active-probe”, and
      “application-active-reconnect” wakeups with typed resubscription receipts
      emitted by the subscription handler, including the attempt number and
      afterSequence. Await the corresponding receipt after each Queue.offer, then
      retain the loaderCalls and subscriptionCount assertions; remove the arbitrary
      scheduler-turn polling.
      
      ---
      
      Outside diff comments:
      In `@patches/`@effect__platform-bun@4.0.0-beta.102.patch:
      - Around line 5-22: Add focused Bun runtime tests for both patched Bun server
      variants, alongside the existing perMessageDeflate coverage, verifying
      negotiation and a compressed client/server round trip. Add a separate Bun test
      for idleTimeout: 30 that deterministically verifies the connection-close receipt
      or configured timeout behavior, using the relevant Bun server test symbols and
      avoiding NodeHttpServer.layerTest.
      
      ---
      
      Nitpick comments:
      In `@packages/client-runtime/src/state/shell-sync.test.ts`:
      - Around line 50-58: Update the local session helper to remove the explicit
      RpcSession.RpcSession return annotation and let TypeScript infer the returned
      object type. If structural validation is needed, apply satisfies
      RpcSession.RpcSession to the returned object without changing its behavior.
      
      In `@packages/client-runtime/src/state/shell.ts`:
      - Around line 190-196: Replace the detailed branch-by-branch comment near
      makeSubscribeInput with a concise caller-contract comment describing when this
      subscription input is used and its expected completion behavior. Do not document
      internal replay, snapshot, or HTTP-path mechanics there; preserve the existing
      implementation unchanged.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 697a6784-5144-44fc-9bb0-7f90021f9812

      📥 Commits

      Reviewing files that changed from the base of the PR and between ca72e381c64f25d771236eecf70219f68e5f365b and b889ec4d04d38050e550e810e63d3411058c6469.

      ⛔ Files ignored due to path filters (1)
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (9)
      • apps/mobile/src/connection/background-activity.ts
      • apps/mobile/src/connection/platform.ts
      • packages/client-runtime/src/connection/supervisor.test.ts
      • packages/client-runtime/src/connection/supervisor.ts
      • packages/client-runtime/src/connection/wakeups.ts
      • packages/client-runtime/src/rpc/session.ts
      • packages/client-runtime/src/state/shell-sync.test.ts
      • packages/client-runtime/src/state/shell.ts
      • patches/@effect__platform-bun@4.0.0-beta.102.patch
      @@ -875,0 +917,21 @@
      917+ const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
      918+ initiallyDesired: true,
      919+ }).pipe(Effect.provide(harness.dependencies));
      920+
      921+ yield* awaitState(
      922+ supervisor.state,
      923+ (state) => state.phase === "backoff" && state.attempt === 1,
      924+ );
      925+ expect(yield* Ref.get(harness.prepareCount)).toBe(1);
      926+
      927+ // Advisory path-change wakeups have no session to probe during backoff
      928+ // and must not trigger an early retry.
      929+ yield* harness.wake("network-path-changed");
      930+ yield* harness.wake("network-path-changed");
      931+ for (let attempt = 0; attempt < 20; attempt += 1) {
      932+ yield* Effect.yieldNow;
      933+ }
      934+ expect(yield* Ref.get(harness.prepareCount)).toBe(1);
      935+ expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("backoff");
      936+ }),
      937+ );
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      Replace the fixed Effect.yieldNow loop with a typed wait.

      This test waits for two queued "network-path-changed" wakeups to be processed by looping Effect.yieldNow a fixed 20 times before asserting prepareCount and phase. This does not wait for a typed receipt that the supervisor consumed both signals; it relies on an arbitrary iteration count matching the current fiber-scheduling depth. If the internal signal-processing chain gets deeper (e.g., another yield* is added upstream), this test can pass or fail non-deterministically without a related regression in production code.

      Use a typed receipt instead, for example by extending the harness to expose an effect that completes once the signals queue is drained, or by using TestClock.adjust to a known point (since waitForRetrySignal races against Effect.sleep(delayMs), advancing time deterministically resolves the race without a magic iteration count).

      As per coding guidelines, "Tests must wait for typed receipts and worker drains in event-sourced async flows; do not use sleeps, polling, or arbitrary timeouts to make tests pass."

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/client-runtime/src/connection/supervisor.test.ts` around lines 912 -
      937, Replace the fixed Effect.yieldNow loop in the “does not cut backoff short
      when the network path flaps” test with a deterministic typed wait. Extend the
      visible harness or use TestClock so the test awaits confirmation that both
      network-path-changed signals were consumed before asserting prepareCount and
      supervisor.state.phase, while preserving the backoff and no-early-retry
      assertions.

      Source: Coding guidelines

      @@ -328,18 +403,17 @@
      328403 }
      329-
      330- expect(yield* Ref.get(loaderCalls)).toBe(2);
      404+ expect(yield* Ref.get(loaderCalls)).toBe(0);
      331405 expect(yield* Ref.get(subscriptionCount)).toBe(2);
      332406
      333407 yield* Queue.offer(wakeups, "application-active-probe");
      334408 for (let attempt = 0; attempt < 100; attempt += 1) {
      335409 if ((yield* Ref.get(subscriptionCount)) >= 3) break;
      336410 yield* Effect.yieldNow;
      337411 }
      338- expect(yield* Ref.get(loaderCalls)).toBe(3);
      412+ expect(yield* Ref.get(loaderCalls)).toBe(0);
      339413 expect(yield* Ref.get(subscriptionCount)).toBe(3);
      340414
      341415 yield* Queue.offer(wakeups, "application-active-reconnect");
      342416 for (let attempt = 0; attempt < 10; attempt += 1) {
      343417 yield* Effect.yieldNow;
      344418 }
      345- expect(yield* Ref.get(loaderCalls)).toBe(3);
      419+ expect(yield* Ref.get(loaderCalls)).toBe(0);
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

      Wait for typed resubscription receipts.

      The loops poll subscriptionCount for an arbitrary number of scheduler turns. A slow scheduler can run the subscription after the loop and cause a false test failure. Emit a typed receipt from the subscription handler, such as its attempt number and afterSequence, then await that receipt after each wakeup.

      As per coding guidelines, “Tests must wait for typed receipts and worker drains in event-sourced async flows; do not use sleeps, polling, or arbitrary timeouts to make tests pass.”

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/client-runtime/src/state/shell-sync.test.ts` around lines 397 - 419,
      Replace the polling loops around the “application-active”,
      “application-active-probe”, and “application-active-reconnect” wakeups with
      typed resubscription receipts emitted by the subscription handler, including the
      attempt number and afterSequence. Await the corresponding receipt after each
      Queue.offer, then retain the loaderCalls and subscriptionCount assertions;
      remove the arbitrary scheduler-turn polling.

      Source: Coding guidelines

    6. t3dotgg(GitHub profile, opens in a new tab) changed the title

    7. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire13.4 KiB13.2 KiB−223 B (−1.6%)15.1 KiB✅
      CodexThread snapshot wire6.9 KiB6.9 KiB−14 B (−0.2%)7.3 KiB✅
      CodexLive turn WebSocket wire6.5 KiB6.3 KiB−209 B (−3.1%)7.8 KiB✅
      CodexLive turn WebSocket decoded57.0 KiB55.5 KiB−1.5 KiB (−2.6%)66.4 KiB✅
      CodexLive turn messages108−2 (−20.0%)21✅
      ClaudeTotal thread wire13.5 KiB13.3 KiB−182 B (−1.3%)15.1 KiB✅
      ClaudeThread snapshot wire6.9 KiB6.9 KiB−9 B (−0.1%)7.3 KiB✅
      ClaudeLive turn WebSocket wire6.6 KiB6.4 KiB−173 B (−2.6%)7.8 KiB✅
      ClaudeLive turn WebSocket decoded57.8 KiB56.4 KiB−1.4 KiB (−2.5%)66.4 KiB✅
      ClaudeLive turn messages10100 (0.0%)21✅

      Baseline: ea71a19 · PR result: 1d5093b · Source CI: success

      Scenario and decoded snapshot size

      10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.

      • Codex decoded thread snapshot: 109.4 KiB
      • Claude decoded thread snapshot: 110.1 KiB

      Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.

    8. One change-discipline finding: documentation lost while moving the WebSocket options out of server.ts. Everything else in the changed Effect service code (supervisor wakeup handling, wakeups.ts union, mobile platform layer, rpc/session.ts hooks) follows the conventions.

      Posted via Macroscope — Effect Service Conventions
    9. t3dotgg(GitHub profile, opens in a new tab) changed the title

Sign in to join this conversation.