Skip to content
Source
Sign inSign up
pingdotgg/t3code

Add Expo mobile client and wire up `dev:mobile` workflow #123

Closedjuliusmarmingewants to merge 2 commits intomain fromcodething/ecef18eaopened View on GitHub

juliusmarmingecommented

Summary

  • Add new apps/mobile Expo React Native app with Uniwind styling and React Query state handling.
  • Implement mobile WebSocket client/transport to connect directly to the T3 backend, consume welcome/domain events, and fetch orchestration snapshots.
  • Add backend profile persistence (URL/token, active profile, last connected) via AsyncStorage.
  • Configure Expo app metadata and icons, including environment-based local icon selection for development vs production.
  • Update root docs and scripts to include the new bun run dev:mobile workflow.

Testing

  • Not run (lint/test execution not provided in the supplied context).
  • Manual verification suggested: start bun run dev:mobile, connect to a local server, verify snapshot refresh and domain event rendering.
  • Manual verification suggested: confirm development/production icon selection is reflected in Expo app config.

Note

Medium Risk Adds a new Expo mobile app with persistent server credentials and custom WebSocket request/push handling (including reconnection and token-in-URL), which could introduce connectivity/auth edge cases despite being largely additive.

Overview Adds a new Expo React Native app under apps/mobile (Uniwind styling + React Query) that connects directly to the T3 backend over WebSocket.

The mobile client persists multiple backend profiles (URL + optional auth token, active profile, last-connected timestamp) via AsyncStorage, and implements a lightweight WebSocket transport (WsTransport) plus a typed client (T3MobileClient) to fetch orchestration snapshots and subscribe to welcome/domain events.

Docs are updated to include the new dev:mobile workflow and list /apps/mobile in the workspace layout.

Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit c085e1d47c460a76b3ac13e72afbaba6b66fd9a6. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).

Note

Add Expo mobile client under apps/mobile and add dev:mobile workflow in package.json to run backend and mobile in parallel

Introduce an Expo-based mobile app with core UI, backend profile storage, and WebSocket transport, and add a root dev:mobile script plus docs and configs to run it alongside the backend. Key entry points include AppContent in apps/mobile/src/App.tsx, transport in apps/mobile/src/wsTransport.ts, client wrapper in apps/mobile/src/t3MobileClient.ts, and dev runner wiring in scripts/dev-runner.mjs.

📍Where to Start

Start with the mobile app root AppContent in apps/mobile/src/App.tsx, then follow transport setup in apps/mobile/src/t3MobileClient.ts and apps/mobile/src/wsTransport.ts.

📊 Macroscope summarized c085e1d. 12 files reviewed, 22 issues evaluated, 2 issues filtered, 5 comments posted

🗂️ Filtered Issues

apps/mobile/src/App.tsx — 1 comment posted, 3 evaluated, 1 filtered
  • line 273: The useEffect hook triggers loadBackendState() inside an async IIFE without a try/catch block or .catch() handler. If loadBackendState rejects (e.g. due to AsyncStorage failure or JSON.parse throwing on corrupted data in parseStoredProfiles), the rejection is unhandled. In React Native environments, unhandled promise rejections can cause the application to crash, leading to a persistent crash loop on startup if the locally stored data is invalid. [ Cross-file consolidated ]
apps/mobile/src/wsTransport.ts — 2 comments posted, 12 evaluated, 1 filtered
  • line 65: The request method does not check if the transport is disposed before creating a request. If request is called after dispose() has been executed, it creates a Promise and calls send. The send method (Lines 220-223) detects this.disposed and aborts silently by clearing its interval, but it does not signal failure to the caller. Consequently, the Promise created in request hangs for the full duration of REQUEST_TIMEOUT_MS (20 seconds) before rejecting with a timeout error, causing significant unnecessary latency and resource holding. [ Out of scope ]
    1. 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.

      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:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `codething/ecef18ea`

      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. @@ -0,0 +109,21 @@
      109+export function createBackendProfileId(): string {
      110+ return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
      111+}
      112+
      113+export function normalizeBackendInput(urlInput: string, authTokenInput: string): NormalizedBackendInput {
      114+ const parsed = toWsUrl(urlInput);
      115+ const tokenFromUrl = parsed.searchParams.get("token")?.trim() || "";
      116+ parsed.searchParams.delete("token");
      117+
      118+ const inputToken = authTokenInput.trim();
      119+ const authToken = inputToken.length > 0 ? inputToken : tokenFromUrl.length > 0 ? tokenFromUrl : null;
      120+
      121+ return {
      122+ name: buildBackendName(parsed),
      123+ url: parsed.toString(),
      124+ authToken,
      125+ };
      126+}
      127+
      128+export function buildSocketUrl(profile: Pick<BackendProfile, "url" | "authToken">): string {
      129+ const parsed = new URL(profile.url);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High src/backendProfiles.ts:129

      new URL(profile.url) throws if the stored URL is malformed. Consider wrapping in try/catch or validating the URL format in toBackendProfile to handle corrupted persisted data gracefully.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/mobile/src/backendProfiles.ts around line 129:
      
      `new URL(profile.url)` throws if the stored URL is malformed. Consider wrapping in try/catch or validating the URL format in `toBackendProfile` to handle corrupted persisted data gracefully.
      
      Evidence trail:
      apps/mobile/src/backendProfiles.ts lines 124-132: `buildSocketUrl` function calls `new URL(profile.url)` without try/catch (REVIEWED_COMMIT)
      apps/mobile/src/backendProfiles.ts lines 32-47: `toBackendProfile` validates that `url` is a string but does not validate URL format (REVIEWED_COMMIT)
      apps/mobile/src/backendProfiles.ts lines 51-67: `parseStoredProfiles` loads from raw storage and calls `toBackendProfile` (REVIEWED_COMMIT)
      @@ -0,0 +80,21 @@
      80+ if (status.state === "connected") return "bg-emerald-100 text-emerald-700";
      81+ if (status.state === "connecting") return "bg-amber-100 text-amber-700";
      82+ if (status.state === "error") return "bg-red-100 text-red-700";
      83+ return "bg-slate-200 text-slate-700";
      84+}
      85+
      86+function formatDate(iso: string | null | undefined): string {
      87+ if (!iso) return "-";
      88+
      89+ const value = new Date(iso);
      90+ if (Number.isNaN(value.getTime())) return "-";
      91+ return value.toLocaleString();
      92+}
      93+
      94+function formatEventType(event: OrchestrationEvent): string {
      95+ const eventRecord = event as Record<string, unknown>;
      96+ if (typeof eventRecord.type === "string") return eventRecord.type;
      97+ return "event";
      98+}
      99+
      100+function formatEventTimestamp(event: OrchestrationEvent): string {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/App.tsx:100

      formatEventTimestamp returns "" when createdAt is missing, so events of the same type without timestamps produce duplicate keys (e.g., "log-"). Consider returning a fallback like a random ID or index to ensure uniqueness.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/mobile/src/App.tsx around line 100:
      
      `formatEventTimestamp` returns `""` when `createdAt` is missing, so events of the same type without timestamps produce duplicate keys (e.g., `"log-"`). Consider returning a fallback like a random ID or index to ensure uniqueness.
      
      Evidence trail:
      apps/mobile/src/App.tsx lines 101-111 at REVIEWED_COMMIT:
      - Line 101-104: `formatEventTimestamp` returns `""` when `createdAt` is missing
      - Line 106-111: `eventKey` falls back to `${formatEventType(event)}-${formatEventTimestamp(event)}` when `eventId` and `id` are missing
      - Combined: events without timestamps/ids of the same type produce duplicate keys like `"log-"`
      @@ -0,0 +84,21 @@
      84+ });
      85+
      86+ this.send(message);
      87+ });
      88+ }
      89+
      90+ subscribe(channel: string, listener: PushListener): () => void {
      91+ let channelListeners = this.listeners.get(channel);
      92+ if (!channelListeners) {
      93+ channelListeners = new Set();
      94+ this.listeners.set(channel, channelListeners);
      95+ }
      96+
      97+ channelListeners.add(listener);
      98+
      99+ return () => {
      100+ channelListeners?.delete(listener);
      101+ if (channelListeners && channelListeners.size === 0) {
      102+ this.listeners.delete(channel);
      103+ }
      104+ };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/wsTransport.ts:99

      The unsubscribe closure captures a stale channelListeners Set, which after resubscribe can cause deletion of the new Set. Suggest resolving the current set inside the closure via this.listeners.get(channel), removing the listener from that set, and only deleting the map entry if it’s the same set and now empty.

      Suggested change
      99- return () => {
      100- channelListeners?.delete(listener);
      101- if (channelListeners && channelListeners.size === 0) {
      102- this.listeners.delete(channel);
      103- }
      104- };
      99+ return () => {
      100+ const currentListeners = this.listeners.get(channel);
      101+ currentListeners?.delete(listener);
      102+ if (currentListeners && currentListeners.size === 0) {
      103+ this.listeners.delete(channel);
      104+ }
      105+ };
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/mobile/src/wsTransport.ts around lines 99-104:
      
      The unsubscribe closure captures a stale `channelListeners` Set, which after resubscribe can cause deletion of the new Set. Suggest resolving the current set inside the closure via `this.listeners.get(channel)`, removing the listener from that set, and only deleting the map entry if it’s the same set and now empty.
      
      Evidence trail:
      apps/mobile/src/wsTransport.ts lines 89-103 (commit REVIEWED_COMMIT): The subscribe() method returns an unsubscribe closure at line 99 that captures the local `channelListeners` variable. When unsubscribe is called after a channel has been unsubscribed and re-subscribed, the closure still holds a reference to the old Set and incorrectly deletes the new Set from `this.listeners` via `this.listeners.delete(channel)` at line 101 because the old captured Set has size 0.
      @@ -0,0 +129,21 @@
      129+ const parsed = new URL(profile.url);
      130+ const token = profile.authToken?.trim();
      131+ if (token) {
      132+ parsed.searchParams.set("token", token);
      133+ } else {
      134+ parsed.searchParams.delete("token");
      135+ }
      136+ return parsed.toString();
      137+}
      138+
      139+export async function loadBackendState(): Promise<StoredBackendState> {
      140+ const [rawProfiles, rawActiveProfileId] = await Promise.all([
      141+ AsyncStorage.getItem(BACKEND_PROFILES_KEY),
      142+ AsyncStorage.getItem(ACTIVE_BACKEND_ID_KEY),
      143+ ]);
      144+
      145+ return {
      146+ profiles: parseStoredProfiles(rawProfiles),
      147+ activeProfileId: rawActiveProfileId && rawActiveProfileId.length > 0 ? rawActiveProfileId : null,
      148+ };
      149+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High src/backendProfiles.ts:139

      If AsyncStorage.getItem fails, the error propagates uncaught to App.tsx, leaving loadingProfiles stuck as true and the app on the loading screen. Consider wrapping the calls in try/catch and returning a default empty state on failure.

      +export async function loadBackendState(): Promise<StoredBackendState> {
      +  try {
      +    const [rawProfiles, rawActiveProfileId] = await Promise.all([
      +      AsyncStorage.getItem(BACKEND_PROFILES_KEY),
      +      AsyncStorage.getItem(ACTIVE_BACKEND_ID_KEY),
      +    ]);
      +
      +    return {
      +      profiles: parseStoredProfiles(rawProfiles),
      +      activeProfileId: rawActiveProfileId && rawActiveProfileId.length > 0 ? rawActiveProfileId : null,
      +    };
      +  } catch {
      +    return { profiles: [], activeProfileId: null };
      +  }
      +}
      Also found in 1 other location(s)

      apps/mobile/src/App.tsx:273

      The useEffect hook triggers loadBackendState() inside an async IIFE without a try/catch block or .catch() handler. If loadBackendState rejects (e.g. due to AsyncStorage failure or JSON.parse throwing on corrupted data in parseStoredProfiles), the rejection is unhandled. In React Native environments, unhandled promise rejections can cause the application to crash, leading to a persistent crash loop on startup if the locally stored data is invalid.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/mobile/src/backendProfiles.ts around lines 139-149:
      
      If `AsyncStorage.getItem` fails, the error propagates uncaught to `App.tsx`, leaving `loadingProfiles` stuck as `true` and the app on the loading screen. Consider wrapping the calls in try/catch and returning a default empty state on failure.
      
      Evidence trail:
      apps/mobile/src/backendProfiles.ts lines 139-152 (loadBackendState with no try/catch around AsyncStorage.getItem)
      apps/mobile/src/App.tsx line 120 (loadingProfiles initialized as true)
      apps/mobile/src/App.tsx lines 270-281 (useEffect calling loadBackendState without try/catch, setLoadingProfiles(false) only called on success)
      apps/mobile/src/App.tsx lines 303-308 (loading screen shown when loadingProfiles is true)
      
      Also found in 1 other location(s):
      - apps/mobile/src/App.tsx:273 -- The `useEffect` hook triggers `loadBackendState()` inside an async IIFE without a `try/catch` block or `.catch()` handler. If `loadBackendState` rejects (e.g. due to `AsyncStorage` failure or `JSON.parse` throwing on corrupted data in `parseStoredProfiles`), the rejection is unhandled. In React Native environments, unhandled promise rejections can cause the application to crash, leading to a persistent crash loop on startup if the locally stored data is invalid.
      
      @@ -0,0 +207,21 @@
      207+ return;
      208+ }
      209+
      210+ pending.resolve(message.result);
      211+ }
      212+
      213+ private send(message: WsRequestEnvelope): void {
      214+ if (this.ws?.readyState === WebSocket.OPEN) {
      215+ this.ws.send(JSON.stringify(message));
      216+ return;
      217+ }
      218+
      219+ const check = setInterval(() => {
      220+ if (this.disposed) {
      221+ clearInterval(check);
      222+ return;
      223+ }
      224+
      225+ if (this.ws?.readyState === WebSocket.OPEN) {
      226+ clearInterval(check);
      227+ this.ws.send(JSON.stringify(message));
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/wsTransport.ts:225

      send lacks error handling. JSON.stringify and ws.send can throw; failures can lose the message and leave the request hanging, and the interval may not be cleared. Suggest wrapping both paths (immediate and retry) in try/catch, clearing the interval on success/failure, and rejecting the pending request (by id) on failure.

      -      if (this.ws?.readyState === WebSocket.OPEN) {
      -        clearInterval(check);
      -        this.ws.send(JSON.stringify(message));
      +      if (this.ws?.readyState === WebSocket.OPEN) {
      +        this.ws.send(JSON.stringify(message));
      +        clearInterval(check);
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/mobile/src/wsTransport.ts around lines 225-227:
      
      `send` lacks error handling. `JSON.stringify` and `ws.send` can throw; failures can lose the message and leave the request hanging, and the interval may not be cleared. Suggest wrapping both paths (immediate and retry) in try/catch, clearing the interval on success/failure, and rejecting the pending request (by `id`) on failure.
      
      Evidence trail:
      apps/mobile/src/wsTransport.ts lines 213-234 (REVIEWED_COMMIT): `send` method with no try/catch around `JSON.stringify` or `ws.send`; lines 219-229 show the interval retry logic where exceptions in the callback would be unhandled; lines 64-87 show `request()` method where `this.send(message)` is called inside Promise executor - synchronous throws are caught but async throws from the interval are not; line 26 shows REQUEST_TIMEOUT_MS = 20_000ms which is how long a failed retry request would hang.
    3. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      Bugbot Autofix is ON, but it could not run because the spend limit has been reached. To enable Bugbot Autofix, raise your spend limit in the [Cursor dashboard](https://www.cursor.com/dashboard?tab=spending).
      @@ -0,0 +187,21 @@
      187+ void queryClient.invalidateQueries({ queryKey: ["orchestration.snapshot", profile.id] });
      188+ });
      189+
      190+ cleanupRef.current = () => {
      191+ unsubscribeWelcome();
      192+ unsubscribeDomainEvents();
      193+ nextClient.dispose();
      194+ };
      195+
      196+ setClient(nextClient);
      197+ setActiveProfileId(profile.id);
      198+ await setActiveBackendProfileId(profile.id);
      199+
      200+ const now = new Date().toISOString();
      201+ setProfiles((current) => {
      202+ const nextProfiles = current.map((candidate) =>
      203+ candidate.id === profile.id ? { ...candidate, lastConnectedAt: now } : candidate,
      204+ );
      205+ void saveBackendProfiles(nextProfiles);
      206+ return nextProfiles;
      207+ });
      cursor[bot](GitHub profile, opens in a new tab)commented

      Async side effect inside React state setter function

      Medium Severity

      The setProfiles functional updater in connectToProfile calls saveBackendProfiles(nextProfiles) as a side effect inside the state setter callback. React state updaters must be pure functions — React may invoke them multiple times (e.g., in Strict Mode with React 19, which this project uses) or discard their results in concurrent rendering. This can cause saveBackendProfiles to write to AsyncStorage redundantly or even persist data from a discarded render.

      Fix in Cursor Fix in Web

      @@ -0,0 +237,21 @@
      237+
      238+ const nextProfiles = existing
      239+ ? profiles.map((candidate) => (candidate.id === existing.id ? profile : candidate))
      240+ : [profile, ...profiles];
      241+
      242+ setProfiles(nextProfiles);
      243+ await saveBackendProfiles(nextProfiles);
      244+ await connectToProfile(profile);
      245+
      246+ setWsUrlInput("");
      247+ setAuthTokenInput("");
      248+ } catch (error) {
      249+ setUiError(error instanceof Error ? error.message : "Unable to save backend profile.");
      250+ }
      251+ }, [authTokenInput, connectToProfile, profiles, wsUrlInput]);
      252+
      253+ const removeProfile = useCallback(
      254+ async (profileId: string) => {
      255+ const nextProfiles = profiles.filter((profile) => profile.id !== profileId);
      256+ setProfiles(nextProfiles);
      257+ await saveBackendProfiles(nextProfiles);
      cursor[bot](GitHub profile, opens in a new tab)commented

      Non-functional state update risks overwriting concurrent profile changes

      Low Severity

      removeProfile reads profiles from its closure and calls setProfiles(nextProfiles) directly, instead of using the functional updater form setProfiles(current => current.filter(...)). saveAndConnectProfile has the same pattern. Since connectToProfile correctly uses the functional updater for setProfiles, a rapid sequence of connect-then-delete could cause the direct setter in removeProfile to overwrite the lastConnectedAt update from connectToProfile.

      Additional Locations (1)

      Fix in Cursor Fix in Web

    4. @@ -0,0 +25,21 @@
      25+
      26+const REQUEST_TIMEOUT_MS = 20_000;
      27+const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
      28+const decodeWsResponseFromJson = Schema.decodeUnknownExit(Schema.fromJsonString(WsResponse));
      29+const isWsPushEnvelope = Schema.is(WsPush);
      30+const isWebSocketResponseEnvelope = Schema.is(WebSocketResponse);
      31+
      32+function websocketRawToString(raw: unknown): string | null {
      33+ if (typeof raw === "string") {
      34+ return raw;
      35+ }
      36+
      37+ if (raw instanceof ArrayBuffer) {
      38+ return new TextDecoder().decode(raw);
      39+ }
      40+
      41+ if (ArrayBuffer.isView(raw)) {
      42+ return new TextDecoder().decode(raw);
      43+ }
      44+
      45+ return null;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/wsTransport.ts:45

      Binary frames may arrive as Blob (default WebSocket#binaryType), so websocketRawToString drops them. Suggest setting ws.binaryType = "arraybuffer" in connect() or adding a Blob case.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/mobile/src/wsTransport.ts around line 45:
      
      Binary frames may arrive as `Blob` (default `WebSocket#binaryType`), so `websocketRawToString` drops them. Suggest setting `ws.binaryType = "arraybuffer"` in `connect()` or adding a `Blob` case.
      
      Evidence trail:
      apps/mobile/src/wsTransport.ts lines 31-44 (`websocketRawToString` function - no Blob handling, returns null for unrecognized types), lines 120-149 (`connect()` method - no `binaryType` setting), lines 151-154 (`handleMessage` - silently returns on null messageText). WebSocket default binaryType is "blob" per MDN/spec.
    5. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    6. juliusmarminge closed this

Sign in to join this conversation.