Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(mobile): compressed websocket frames for iOS #4794

Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 5 commits intomain fromt3code/improve-mobile-data-loadingopened View on GitHub

iPhones were left out of the websocket compression we shipped in #4705. React Native's iOS WebSocket is backed by SocketRocket, which never offers permessage-deflate, so every frame to the iOS app still crossed the wire uncompressed while Android (OkHttp offers the extension by default) got the win for free.

This adds a small Apple-only Expo module backed by URLSessionWebSocketTask, which offers permessage-deflate in its handshake automatically. A thin JS wrapper exposes the W3C WebSocket surface Effect's Socket.fromWebSocket drives, and the mobile runtime injects it as the Socket.WebSocketConstructor on iOS only. Android and iOS binaries predating the module fall back to the global WebSocket unchanged, so older TestFlight builds keep working.

Details worth noting:

  • maximumMessageSize is raised to 128 MB on the URLSession task. The default receive cap is 1 MB, and socket-fallback snapshot frames can exceed that.
  • On abnormal termination the module synthesizes close code 1006 after the error event, matching browser semantics so the connection supervisor classifies it as a transport error and reconnects.
  • RN's global WebSocket is untouched; only the Effect runtime socket switches implementation.

Tests: vp test run src/lib/nativeWebSocket.test.ts (6 tests: id routing, once-listeners, binary round-trip, idempotent close), mobile typecheck, lint.

Built with Claude Fable 5 in Claude Code.

🤖 Generated with Claude Code


Note

Medium Risk Swaps the transport for all Effect-driven iOS WebSockets (reconnect/close semantics and large-frame handling must stay correct), but scope is limited to mobile relay sockets with explicit fallbacks and unit tests on the JS bridge.

Overview iOS relay WebSockets now use a native URLSessionWebSocketTask path so the client can negotiate permessage-deflate with the server (SocketRocket behind RN’s global WebSocket cannot). Android and older iOS builds without the module keep the existing global WebSocket.

A new Apple-only Expo module (T3WebSocket) manages connections by id, raises the receive cap to 128 MB for large snapshot frames, clears custom URLProtocol classes so dev proxies don’t break upgrades, and on transport failure emits error + synthetic close 1006 for Effect’s reconnect logic. A thin JS NativeWebSocket implements the subset Effect needs (events, send, close, multi-connection routing), and runtime.ts injects it as Socket.WebSocketConstructor when loadNativeWebSocketConstructor() succeeds.

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

Note

Add compressed WebSocket native module for iOS using URLSessionWebSocketTask

  • Introduces a new native iOS module T3WebSocketModule built on URLSessionWebSocketTask, supporting text/binary messaging, subprotocols, and per-connection events (onOpen, onMessage, onClose, onError) keyed by caller-supplied integer ids.
  • Adds a JS-side NativeWebSocket class that mirrors browser WebSocket semantics (readyState transitions, once listeners, idempotent close, base64↔Uint8Array conversion for binary frames).
  • Updates runtime.ts to dynamically select the native WebSocket constructor on iOS when available, falling back to the global constructor on other platforms.
  • Maximum message size is capped at 128 MiB; abnormal connection termination emits an onClose with code 1006.
Macroscope summarized a7adbc1.

Summary by CodeRabbit

  • New Features

    • Added a native iOS WebSocket implementation for improved mobile connectivity.
    • Supports text and binary messaging, connection lifecycle events, custom protocols, and graceful closure.
    • Automatically uses the native implementation when available, with fallback support to the standard WebSocket.
  • Bug Fixes

    • Improved handling of connection states, errors, close events, and late connection callbacks.
  • Tests

    • Added comprehensive coverage for native WebSocket connections, messaging, listeners, and lifecycle behavior.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: b9bf6195-023b-4445-b573-5bf5ad15a1f6

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • ✅ Review completed - (🔄 Check again to review again)
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `t3code/improve-mobile-data-loading`

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      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. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      This PR introduces a new native iOS module for WebSocket handling with compression support. The addition of new native networking infrastructure (~400+ lines of new Swift and TypeScript code) that changes runtime WebSocket behavior warrants human review.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      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 95f6b12918c99c0e6e4898e59ac441b78770a984. Configure [here](https://www.cursor.com/dashboard/bugbot).
    5. Actionable comments posted: 1

      🧹 Nitpick comments (2)
      apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift (1)

      30-37: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

      Report dropped sends instead of returning silently.

      sendBinary drops the frame when base64 decoding fails. send (line 95) drops the frame when no task exists for id. The JS adapter receives no signal in either case, so a caller sees a successful send() for data that never left the device. Emit onError on both paths.

      ♻️ Proposed change
           Function("sendBinary") { (id: Int, base64: String) in
      -      guard let data = Data(base64Encoded: base64) else { return }
      +      guard let data = Data(base64Encoded: base64) else {
      +        self.connections.reportError(id: id, message: "Invalid base64 payload")
      +        return
      +      }
             self.connections.send(id: id, message: .data(data))
           }

      Add the helper and the missing-task signal in T3WebSocketConnections:

      func reportError(id: Int, message: String) {
        queue.async { self.emitLocked(id: id, event: "onError", payload: ["message": message]) }
      }
      
      func send(id: Int, message: URLSessionWebSocketTask.Message) {
        queue.async {
          guard let task = self.tasksById[id] else {
            self.emitLocked(id: id, event: "onError", payload: ["message": "Socket is not open"])
            return
          }
          // ... existing send
        }
      }
      🤖 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 `@apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift` around lines 30
      - 37, Update sendBinary and T3WebSocketConnections.send to report failed sends
      through onError instead of silently returning: use a
      T3WebSocketConnections.reportError helper for invalid base64 input, and emit an
      onError event with “Socket is not open” when no task exists for the requested
      id. Preserve the existing send behavior for valid data and open sockets.
      apps/mobile/src/lib/nativeWebSocket.test.ts (1)

      106-131: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Add coverage for onError and for protocol forwarding.

      The suite does not exercise handleError or the protocols argument. handleError dispatches an Error instance rather than an event object, which is the least obvious part of the adapter contract. A short test for each closes that gap.

      💚 Suggested tests
      it("dispatches native errors and forwards protocols", async () => {
        const construct = await loadNativeWebSocketConstructor();
        const socket = construct!("wss://example.test/ws", ["t3"]);
        expect(lastCall("connect")!.args[2]).toEqual(["t3"]);
      
        const id = connectionIdOf(socket);
        const errors: unknown[] = [];
        socket.addEventListener("error", (event) => errors.push(event));
        mocks.emit("onError", { id, message: "boom" });
        expect(errors[0]).toBeInstanceOf(Error);
      });
      🤖 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 `@apps/mobile/src/lib/nativeWebSocket.test.ts` around lines 106 - 131, Add test
      coverage in the native WebSocket test suite for the constructor’s protocols
      argument and the onError path handled by handleError. Instantiate the socket
      with a protocol list and assert connect receives it, then emit onError, capture
      the error event, and assert the dispatched value is an Error instance.
      🤖 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 `@apps/mobile/src/lib/nativeWebSocket.ts`:
      - Around line 46-63: Update attachNativeListeners so nativeListenersAttached is
      set to true only after all four module.addListener registrations complete
      successfully. Keep the flag false when any registration throws, allowing a later
      invocation to retry attaching listeners and deliver events to sockets.
      
      ---
      
      Nitpick comments:
      In `@apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift`:
      - Around line 30-37: Update sendBinary and T3WebSocketConnections.send to report
      failed sends through onError instead of silently returning: use a
      T3WebSocketConnections.reportError helper for invalid base64 input, and emit an
      onError event with “Socket is not open” when no task exists for the requested
      id. Preserve the existing send behavior for valid data and open sockets.
      
      In `@apps/mobile/src/lib/nativeWebSocket.test.ts`:
      - Around line 106-131: Add test coverage in the native WebSocket test suite for
      the constructor’s protocols argument and the onError path handled by
      handleError. Instantiate the socket with a protocol list and assert connect
      receives it, then emit onError, capture the error event, and assert the
      dispatched value is an Error instance.
      🪄 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: 13b4bc2a-5a6e-4d6f-9422-ebf4f5d26330

      📥 Commits

      Reviewing files that changed from the base of the PR and between 694f8d1c6eaaabafbf5c2861ae524174919ef625 and a7adbc1161c1458129d3c8f5eb030c621493054e.

      📒 Files selected for processing (6)
      • apps/mobile/modules/t3-websocket/expo-module.config.json
      • apps/mobile/modules/t3-websocket/ios/T3WebSocket.podspec
      • apps/mobile/modules/t3-websocket/ios/T3WebSocketModule.swift
      • apps/mobile/src/lib/nativeWebSocket.test.ts
      • apps/mobile/src/lib/nativeWebSocket.ts
      • apps/mobile/src/lib/runtime.ts
      @@ -0,0 +43,21 @@
      43+let nextSocketId = 1;
      44+let nativeListenersAttached = false;
      45+
      46+function attachNativeListeners(module: T3WebSocketNativeModule) {
      47+ if (nativeListenersAttached) {
      48+ return;
      49+ }
      50+ nativeListenersAttached = true;
      51+ module.addListener("onOpen", (payload) => {
      52+ activeSockets.get(payload.id)?.handleOpen();
      53+ });
      54+ module.addListener("onMessage", (payload) => {
      55+ activeSockets.get(payload.id)?.handleMessage(payload.data ?? "", payload.binary === true);
      56+ });
      57+ module.addListener("onClose", (payload) => {
      58+ activeSockets.get(payload.id)?.handleClose(payload.code ?? 1006, payload.reason ?? "");
      59+ });
      60+ module.addListener("onError", (payload) => {
      61+ activeSockets.get(payload.id)?.handleError(payload.message ?? "WebSocket error");
      62+ });
      63+}
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

      Set the attached flag only after the listeners attach.

      If the first module.addListener call throws, nativeListenersAttached stays true. No later socket then receives native events, and every socket stays in CONNECTING until Effect's open timeout.

      🛡️ Proposed change
         if (nativeListenersAttached) {
           return;
         }
      -  nativeListenersAttached = true;
         module.addListener("onOpen", (payload) => {
      @@
         module.addListener("onError", (payload) => {
           activeSockets.get(payload.id)?.handleError(payload.message ?? "WebSocket error");
         });
      +  nativeListenersAttached = true;
       }
      📝 Committable suggestion

      ‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      Suggested change
      46-function attachNativeListeners(module: T3WebSocketNativeModule) {
      47- if (nativeListenersAttached) {
      48- return;
      49- }
      50- nativeListenersAttached = true;
      51- module.addListener("onOpen", (payload) => {
      52- activeSockets.get(payload.id)?.handleOpen();
      53- });
      54- module.addListener("onMessage", (payload) => {
      55- activeSockets.get(payload.id)?.handleMessage(payload.data ?? "", payload.binary === true);
      56- });
      57- module.addListener("onClose", (payload) => {
      58- activeSockets.get(payload.id)?.handleClose(payload.code ?? 1006, payload.reason ?? "");
      59- });
      60- module.addListener("onError", (payload) => {
      61- activeSockets.get(payload.id)?.handleError(payload.message ?? "WebSocket error");
      62- });
      63-}
      46+function attachNativeListeners(module: T3WebSocketNativeModule) {
      47+ if (nativeListenersAttached) {
      48+ return;
      49+ }
      50+ module.addListener("onOpen", (payload) => {
      51+ activeSockets.get(payload.id)?.handleOpen();
      52+ });
      53+ module.addListener("onMessage", (payload) => {
      54+ activeSockets.get(payload.id)?.handleMessage(payload.data ?? "", payload.binary === true);
      55+ });
      56+ module.addListener("onClose", (payload) => {
      57+ activeSockets.get(payload.id)?.handleClose(payload.code ?? 1006, payload.reason ?? "");
      58+ });
      59+ module.addListener("onError", (payload) => {
      60+ activeSockets.get(payload.id)?.handleError(payload.message ?? "WebSocket error");
      61+ });
      62+ nativeListenersAttached = true;
      63+}
      🤖 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 `@apps/mobile/src/lib/nativeWebSocket.ts` around lines 46 - 63, Update
      attachNativeListeners so nativeListenersAttached is set to true only after all
      four module.addListener registrations complete successfully. Keep the flag false
      when any registration throws, allowing a later invocation to retry attaching
      listeners and deliver events to sockets.
    6. Closing as part of the open-PR backlog sweep (wave 1).

      Reason: iOS native compressed WS; server permessage-deflate already shipped in #4705. Related: #4705

      Reopen if this is still wanted and you’re willing to rebase onto current main.

    7. juliusmarminge closed this

Sign in to join this conversation.