Skip to content
Source
Sign inSign up
pingdotgg/t3code

[codex] Rewrite client connection architecture #2978

Mergedjuliusmarmingemerged 16 commits intomain fromcodex/connection-state-auditmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Summary

Replace the independent web and mobile connection implementations with a shared Effect-based client runtime.

  • introduce environment descriptors, connection drivers, resolution, supervision, authorization, relay discovery, RPC sessions, and lifecycle ownership in @t3tools/client-runtime
  • move runtime state to explicit environment-scoped modules for auth, connections, projects, threads, shell, terminal, filesystem, source control, review, and presentation
  • migrate web, desktop, and mobile integrations to explicit client-runtime subpath exports
  • add persisted connection catalogs for web, mobile, and desktop, including encrypted desktop storage and mobile legacy migration
  • centralize retry/backoff, connectivity wakeups, credential refresh, account-transition cleanup, session ownership, subscription recovery, and mobile outbox draining
  • preserve scoped relay tracing across the rewritten runtime and release configuration
  • harden local relay startup and agent-activity credential reconciliation

Scope

The native mobile composer, markdown renderer, Clerk sheet routing, turn-fold presentation, and Pierre icons were reviewed separately in #3101 and are now part of main. This PR contains the client connection/runtime rearchitecture on top of that merged base.

Validation

  • node scripts/release-smoke.ts
  • vp check
  • vp run typecheck
  • vp run lint:mobile
  • 96 changed test files passed, covering 741 tests including every changed backend test

Note

High Risk Touches encrypted credential persistence, legacy migrations, and breaking desktop IPC channels while reshaping mobile connection lifecycle and cloud account transitions—errors in migration or catalog reads can strand users' environments.

Overview Desktop drops the saved-environment registry IPC surface in favor of get / set / clear connection catalog handlers backed by a new DesktopConnectionCatalogStore: Electron safe-storage encryption, atomic writes, one-time migration from legacy relay/SSH/bearer records, and read errors for corrupt or undecryptable catalogs instead of silent empty state. DesktopSavedEnvironments now propagates ReadError for malformed registry JSON (used only for migration). Minor fixes: cloud auth header typing, SSH imports split to client-runtime subpaths.

Mobile adds a full connection stack (connectionPlatformLayer, secure catalog + legacy migration, shell/thread snapshot caches, pairing onboarding commands, environmentCatalog atoms) and rewires the app to useWorkspaceState, useConnectionController, and useAtomCommand for environments, pairing, settings, and favicons via useAssetUrl. Cloud settings/environments UI gains status dots, switches, trace IDs, and serialized account cleanup on Clerk sign-in/out (activateCloudRelayAccount / deactivateCloudRelayAccount). Agent-awareness relay device registration is queued and coalesced; settings/async flows use settleAsyncResult. Adds expo-network, iOS modular CocoaPods for App Check deps, and EAS push prompt tweak.

CI removes the dedicated Playwright browser test job from ci.yml.

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

Note

Replace client connection architecture with atom-based environment-scoped state

  • Introduces a layered connection subsystem (ConnectionRegistry, ConnectionDriver, ConnectionResolver, EnvironmentSupervisor) that manages environment lifecycle with retry/backoff, network awareness, and tracing, replacing the previous WebSocket RPC client approach.
  • Replaces Zustand stores and React Query throughout web and mobile with atom families scoped per environment (shell state, thread detail, VCS, terminal, preview, server config, assets, auth).
  • Introduces a typed ConnectionCatalogDocument (targets, profiles, credentials) backed by IndexedDB on web, secure storage on mobile, and encrypted desktop storage, replacing the legacy saved environment registry and secrets APIs.
  • Adds a mobile thread outbox with durable per-message JSON persistence and an automatic drain hook (useThreadOutboxDrain) that retries on transient failures.
  • @t3tools/client-runtime now requires explicit subpath imports (e.g. @t3tools/client-runtime/state/shell); the root export is removed and a lint rule enforces subpath usage.
  • Desktop IPC channels switch from saved-environment registry/secret methods to getConnectionCatalog, setConnectionCatalog, and clearConnectionCatalog.
  • Risk: Breaking change — any code importing from the @t3tools/client-runtime root or calling removed APIs (syncProjects, syncThreads, connectSavedEnvironment, useRemoteEnvironmentBootstrap, etc.) will fail at compile or runtime.
Macroscope summarized 1551f69.
    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

      Run ID: 95e29028-8ce5-4832-9923-acff2a69a2d3

      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
      • Commit unit tests in branch `codex/connection-state-audit`

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

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

      🚀 Expo continuous deployment is ready!

      • Project → t3-code
      • Platforms → android, ios
      • Scheme → t3code-preview
       🤖 Android🍎 iOS
      Fingerprintb0da31fdd85a1becc2a86a825c791b045a5afa58eb056ff68ca484dcf1b32e25342b2824e89824cc
      Build DetailsBuild Permalink
      DetailsDistribution: INTERNAL
      Build profile: preview:dev
      Runtime version: b0da31fdd85a1becc2a86a825c791b045a5afa58
      App version: 0.1.0
      Git commit: 332763aebc5ea21c488142ee4a8a3a0bf4c15eae
      Build Permalink
      DetailsDistribution: INTERNAL
      Build profile: preview:dev
      Runtime version: eb056ff68ca484dcf1b32e25342b2824e89824cc
      App version: 0.1.0
      Git commit: 5c744a980761a8e18b4c7a78c1b3bd7ed0e9e6c7
      Update DetailsUpdate Permalink
      DetailsBranch: pr-2978
      Runtime version: b0da31fdd85a1becc2a86a825c791b045a5afa58
      Git commit: 332763aebc5ea21c488142ee4a8a3a0bf4c15eae
      Update Permalink
      DetailsBranch: pr-2978
      Runtime version: eb056ff68ca484dcf1b32e25342b2824e89824cc
      Git commit: 332763aebc5ea21c488142ee4a8a3a0bf4c15eae
      Update QR
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low connection/webAppQueries.ts:259

      When environmentId or cwd change but query stays the same, isPending incorrectly returns false during the 120ms debounce window. The hook shows stale results from the previous directory/environment while the new search is still pending. Consider also checking if environmentId or cwd differ between normalizedTarget and debouncedTarget.

      No longer relevant as of 296f8f66c1c87caac58d5ac0a557eb904f9ad70a

      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High

      https://github.com/pingdotgg/t3code/blob/f25933291813e15177621cf10e861af483adc5b1/apps/mobile/src/app/settings/environments.tsx#L95

      onUpdateEnvironment is a no-op () => undefined, so when users edit a local environment's label or URL and press Save, ConnectionEnvironmentRow calls it and the changes are silently discarded. The row collapses suggesting success, but the edit is not persisted. Consider implementing the update handler or removing the UI affordance if updates are not yet supported.

      No longer relevant as of 296f8f66c1c87caac58d5ac0a557eb904f9ad70a

      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low connection/brokers.ts:98

      At line 98, when a credential exists but is not a BearerConnectionCredential, the code calls credentialMissingError() which reports "Connection credential ... is unavailable." This is incorrect — the credential exists but has the wrong type. The error message should indicate a type mismatch like the analogous check for profiles at lines 77-82, which uses a specific "is not a bearer connection" message.

      No longer relevant as of 033bade3ef149117423179fb465440ac74bfc57b

    5. juliusmarminge changed the title

    6. @@ -0,0 +93,21 @@
      93+ return;
      94+ }
      95+ const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
      96+ request.addEventListener("upgradeneeded", () => {
      97+ if (!request.result.objectStoreNames.contains(CATALOG_STORE_NAME)) {
      98+ request.result.createObjectStore(CATALOG_STORE_NAME);
      99+ }
      100+ if (!request.result.objectStoreNames.contains(SHELL_STORE_NAME)) {
      101+ request.result.createObjectStore(SHELL_STORE_NAME);
      102+ }
      103+ if (!request.result.objectStoreNames.contains(THREAD_STORE_NAME)) {
      104+ request.result.createObjectStore(THREAD_STORE_NAME);
      105+ }
      106+ });
      107+ request.addEventListener("error", () => {
      108+ resume(Effect.fail(catalogError("open", request.error ?? "Unknown IndexedDB error")));
      109+ });
      110+ request.addEventListener("success", () => {
      111+ resume(Effect.succeed(request.result));
      112+ });
      113+ });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium connection/webConnectionStorage.ts:87

      When indexedDB.open() needs to upgrade the schema but another tab holds an older version, the blocked event fires and the Effect never completes — neither success nor error handlers execute until the blocking tab closes. If that tab never closes, openDatabase hangs indefinitely. Consider handling the blocked event by resuming with a descriptive error or triggering a retry with timeout.

      +    request.addEventListener("blocked", () => {
      +      resume(Effect.fail(catalogError("open", "Database upgrade blocked by another tab")));
      +    });
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/connection/webConnectionStorage.ts around lines 87-113:
      
      When `indexedDB.open()` needs to upgrade the schema but another tab holds an older version, the `blocked` event fires and the Effect never completes — neither `success` nor `error` handlers execute until the blocking tab closes. If that tab never closes, `openDatabase` hangs indefinitely. Consider handling the `blocked` event by resuming with a descriptive error or triggering a retry with timeout.
      
      Evidence trail:
      apps/web/src/connection/webConnectionStorage.ts lines 87-114 at REVIEWED_COMMIT: `openDatabase` registers handlers for `upgradeneeded` (line 96), `error` (line 107), and `success` (line 110), but not for `blocked`. IndexedDB spec: https://w3c.github.io/IndexedDB/#request-api — the `blocked` event fires on IDBOpenDBRequest when the open operation is blocked by existing connections, and `success`/`error` don't fire until the block is resolved.
    7. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium cloud/managedAuth.tsx:59

      On first render when signed out, previousAccount is undefined, so undefined !== null evaluates to true and queueAccountCleanup() runs unnecessarily. This triggers removeRelayEnvironments() and relay client token cache reset even though no account was ever established. Change the condition to if (previousAccount) so cleanup only happens when transitioning from an actual signed-in state.

      -      if (previousAccount !== null) {
      +      if (previousAccount) {
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/cloud/managedAuth.tsx around line 59:
      
      On first render when signed out, `previousAccount` is `undefined`, so `undefined !== null` evaluates to `true` and `queueAccountCleanup()` runs unnecessarily. This triggers `removeRelayEnvironments()` and relay client token cache reset even though no account was ever established. Change the condition to `if (previousAccount)` so cleanup only happens when transitioning from an actual signed-in state.
      
      Evidence trail:
      apps/web/src/cloud/managedAuth.tsx lines 26, 35, 37, 57-61, 63 at REVIEWED_COMMIT. Line 26: ref initialized to `undefined`. Line 35: `previousAccount = observedAccountRef.current` (undefined on first render). Line 59: condition `previousAccount !== null` doesn't account for `undefined`. Line 63: correctly checks all three states (`!== undefined && !== null && !== userId`).
      @@ -1071,19 +1115,5 @@
      1071- return retainThreadDetailSubscription(environmentId, threadId);
      1072- }, [environmentId, routeKind, threadId]);
      1073-
      10741115 // Compute the list of environments this logical project spans, used to
      10751116 // drive the environment picker in BranchToolbar.
      10761117 const allProjects = useStore(useShallow(selectProjectsAcrossEnvironments));
      1077- const primaryEnvironmentId = usePrimaryEnvironmentId();
      1078- const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId);
      1079- const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId);
      1080- const activeSavedEnvironmentRecord =
      1081- activeThread && activeThread.environmentId !== primaryEnvironmentId
      1082- ? (savedEnvironmentRegistry[activeThread.environmentId] ?? null)
      1083- : null;
      1084- const activeSavedEnvironmentRuntime = activeSavedEnvironmentRecord
      1085- ? (savedEnvironmentRuntimeById[activeSavedEnvironmentRecord.environmentId] ?? null)
      1086- : null;
      1087- const activeSavedEnvironmentConnectionState = activeSavedEnvironmentRecord
      1088- ? (activeSavedEnvironmentRuntime?.connectionState ?? "disconnected")
      1089- : "connected";
      1118+ const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
      1119+ const activeEnvironment =
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/ChatView.tsx:1119

      The refactored code removed the guard that excluded the primary environment from unavailability checks. Now activeEnvironmentUnavailable is computed for all environments including the primary, so if the primary's connection.phase is temporarily "connecting" or "available" during startup, the UI shows an unavailable banner and blocks message dispatch — behavior that never occurred before.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/components/ChatView.tsx around line 1119:
      
      The refactored code removed the guard that excluded the primary environment from unavailability checks. Now `activeEnvironmentUnavailable` is computed for all environments including the primary, so if the primary's `connection.phase` is temporarily `"connecting"` or `"available"` during startup, the UI shows an unavailable banner and blocks message dispatch — behavior that never occurred before.
      
      Evidence trail:
      Old guard at MERGE_BASE in ChatView.tsx: `activeThread.environmentId !== primaryEnvironmentId` check in `activeSavedEnvironmentRecord` assignment; new code at REVIEWED_COMMIT ChatView.tsx lines 1119-1123 with no primary guard; `AVAILABLE_CONNECTION_STATE` defined at packages/client-runtime/src/connection/model.ts:148-154 with `phase: "available"`; `activeEnvironmentUnavailable` used to block sends at ChatView.tsx:2806, ChatView.tsx:3427; used to block revert at ChatView.tsx:2746; used for banner at ChatView.tsx:1353; `isConnecting` always false at ChatView.tsx:904 (`_setIsConnecting` unused).
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/17cc80bda61a698b284d76c0098603896bb68510/apps/web/src/components/ProviderUpdateLaunchNotification.tsx#L186

      When the toast is created while primaryEnvironment is loading (null), clicking "Update" silently does nothing because runUpdates captures the stale null value in its closure. The effect re-runs when primaryEnvironment resolves, but it early-returns at line 174 because activeToastRef.current is already set, so the callback is never recreated with the resolved environment value.

      No longer relevant as of a71ceefafc90fed8010dea39ef18e4ffc67dc18c

    8. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/e36194df8f1812f72d17fd41aec5a89d8df92184/apps/mobile/src/features/threads/new-task-flow-provider.tsx#L388

      The loadBranches callback no longer handles errors from branchState.refresh(). If the branch query fails, setPendingConnectionError is never called and users receive no feedback about the failure. Consider wrapping branchState.refresh() in a try-catch and calling setPendingConnectionError on error, or verify that branchState surfaces errors through a different mechanism that renders this handling unnecessary.

      No longer relevant as of f32e94b95ad43398c36e93baf29d18d5e6602713

      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/ChatView.tsx:1808

      The envLocked check at line 1808 only excludes status !== "stopped", but the new session model has two additional terminal states "interrupted" and "error". Threads with these statuses will incorrectly have envLocked = true, blocking users from changing branch/env-mode settings on effectively terminated threads. Consider updating the condition to also exclude "interrupted" and "error".

      No longer relevant as of a2ed9bbb4fd52eedb96fb204a60287d06c0425df

    9. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      Autofix Details

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: Wrong empty state during sync
        • Added a check for hasPendingShellSnapshot && !hasLoadedShellSnapshot before the final fallthrough, returning a loading state instead of the false 'No projects found' message when shell data is still synchronizing on a connected environment.
      • ✅ Fixed: Session activates after failed cleanup
        • Changed queueAccountCleanup to return a Promise<boolean> indicating success (while keeping the transition chain alive via a separate void promise), and gated activateSession on the boolean so it only runs when all cleanup operations succeeded.

      Create PR

      Or push these changes by commenting:

      @cursor push 98b896a5eb
      Preview (pingdotgg/t3code@98b896a5eb)
      diff --git a/apps/mobile/src/app/new/index.tsx b/apps/mobile/src/app/new/index.tsx
      --- a/apps/mobile/src/app/new/index.tsx
      +++ b/apps/mobile/src/app/new/index.tsx
      @@ -62,6 +62,14 @@
           };
         }
       
      +  if (catalogState.hasPendingShellSnapshot && !catalogState.hasLoadedShellSnapshot) {
      +    return {
      +      title: "Loading projects",
      +      detail: "Synchronizing shell data from the connected environment.",
      +      loading: true,
      +    };
      +  }
      +
         return {
           title: "No projects found",
           detail: "The connected environment did not report any projects.",
      
      diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      @@ -48,8 +48,8 @@
               readonly userId: string;
               readonly provider: () => Promise<string | null>;
             } | null,
      -    ) => {
      -      accountTransitionRef.current = accountTransitionRef.current.then(async () => {
      +    ): Promise<boolean> => {
      +      const transition = accountTransitionRef.current.then(async () => {
               const cleanup = [
                 resetManagedRelayTokenCache(),
                 removeRelayEnvironments(),
      @@ -58,13 +58,17 @@
                   : []),
               ];
               const results = await Promise.allSettled(cleanup);
      +        let succeeded = true;
               for (const result of results) {
                 if (result.status === "rejected") {
                   console.warn("[t3-cloud] cloud account cleanup failed", result.reason);
      +            succeeded = false;
                 }
               }
      +        return succeeded;
             });
      -      return accountTransitionRef.current;
      +      accountTransitionRef.current = transition.then(() => {});
      +      return transition;
           };
       
           if (!isSignedIn || !userId) {
      @@ -102,7 +106,9 @@
             previousTokenProviderRef.current = null;
             setAgentAwarenessRelayTokenProvider(null);
             setManagedRelaySession(appAtomRegistry, null);
      -      void queueAccountCleanup(previous).then(activateSession);
      +      void queueAccountCleanup(previous).then((succeeded) => {
      +        if (succeeded) activateSession();
      +      });
           } else {
             void accountTransitionRef.current.then(activateSession);
           }
      You can send follow-ups to the cloud agent here.
    10. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      8 blocking correctness issues found. Diff is too large for automated approval analysis. A human reviewer should evaluate this PR.

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

      There are 3 total unresolved issues (including 1 from previous review).

      Autofix Details

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: Corrupt catalog skips legacy fallback
        • Changed decodeCatalog error handling to use Effect.option and fall through to the legacy migration path instead of immediately returning EMPTY_CONNECTION_CATALOG_DOCUMENT.
      • ✅ Fixed: Cloud switch blocks error retry
        • Changed switch value from connectionState !== "available" to only be true for "connected", "connecting", or "reconnecting" states, allowing users to toggle ON from error/offline states to trigger reconnect.

      Create PR

      Or push these changes by commenting:

      @cursor push 0369ca79fd
      Preview (pingdotgg/t3code@0369ca79fd)
      diff --git a/apps/mobile/src/app/settings/environments.tsx b/apps/mobile/src/app/settings/environments.tsx
      --- a/apps/mobile/src/app/settings/environments.tsx
      +++ b/apps/mobile/src/app/settings/environments.tsx
      @@ -259,7 +259,11 @@
               props.onDisconnect();
             }}
             onToggleError={props.onToggleError}
      -      value={props.environment.connectionState !== "available"}
      +      value={
      +        props.environment.connectionState === "connected" ||
      +        props.environment.connectionState === "connecting" ||
      +        props.environment.connectionState === "reconnecting"
      +      }
           />
         );
       }
      
      diff --git a/apps/mobile/src/connection/catalog-store.ts b/apps/mobile/src/connection/catalog-store.ts
      --- a/apps/mobile/src/connection/catalog-store.ts
      +++ b/apps/mobile/src/connection/catalog-store.ts
      @@ -66,17 +66,25 @@
             return cached.value;
           }
           const raw = yield* storage.getItem(CONNECTION_CATALOG_KEY);
      -    let catalog: ConnectionCatalogDocumentType;
      +    let catalog: ConnectionCatalogDocumentType = EMPTY_CONNECTION_CATALOG_DOCUMENT;
      +    let catalogLoaded = false;
           if (raw !== null && raw.trim() !== "") {
      -      catalog = yield* decodeCatalog(raw).pipe(
      -        Effect.catch((error) =>
      -          Effect.logWarning("Discarding corrupt mobile connection catalog", error).pipe(
      -            Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
      -            Effect.as(EMPTY_CONNECTION_CATALOG_DOCUMENT),
      -          ),
      +      const decoded = yield* decodeCatalog(raw).pipe(
      +        Effect.option,
      +        Effect.tap((result) =>
      +          Option.isNone(result)
      +            ? Effect.logWarning("Discarding corrupt mobile connection catalog").pipe(
      +                Effect.andThen(storage.deleteItem(CONNECTION_CATALOG_KEY)),
      +              )
      +            : Effect.void,
               ),
             );
      -    } else {
      +      if (Option.isSome(decoded)) {
      +        catalog = decoded.value;
      +        catalogLoaded = true;
      +      }
      +    }
      +    if (!catalogLoaded) {
             const legacyRaw = yield* storage.getItem(LEGACY_CONNECTIONS_KEY);
             catalog =
               legacyRaw === null || legacyRaw.trim() === ""
      You can send follow-ups to the cloud agent here.
    12. Cursor Bugbot has reviewed your changes and found 3 potential issues.

      There are 6 total unresolved issues (including 3 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared fixes for all 3 issues found in the latest run.

      • ✅ Fixed: Sign-out skips device unregister
        • Added a fallback token provider using getToken and previousObservedAccount when previousTokenProviderRef is null during sign-out, ensuring unregister is attempted even if activateSession hasn't run yet.
      • ✅ Fixed: Refresh bypasses registration queue
        • Changed refreshAgentAwarenessRegistration to route through enqueueDeviceRegistration instead of calling registerDeviceForCurrentUser directly, ensuring serialized access to the relay endpoint.
      • ✅ Fixed: Paused envs show unavailable
        • Removed 'available' from the connectionState guard in deriveProjectEmptyState so that idle/paused saved connections are no longer conflated with offline or error states.

      Create PR

      Or push these changes by commenting:

      @cursor push 6e632f9d69
      Preview (pingdotgg/t3code@6e632f9d69)
      diff --git a/apps/mobile/src/app/new/index.tsx b/apps/mobile/src/app/new/index.tsx
      --- a/apps/mobile/src/app/new/index.tsx
      +++ b/apps/mobile/src/app/new/index.tsx
      @@ -36,9 +36,7 @@
         }
       
         if (
      -    (catalogState.connectionState === "available" ||
      -      catalogState.connectionState === "offline" ||
      -      catalogState.connectionState === "error") &&
      +    (catalogState.connectionState === "offline" || catalogState.connectionState === "error") &&
           !catalogState.hasLoadedShellSnapshot
         ) {
           return {
      
      diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
      --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
      +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
      @@ -313,6 +313,7 @@
             vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
       
             yield* refreshAgentAwarenessRegistration();
      +      yield* runBackgroundOperations();
       
             expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
           }).pipe(Effect.provide(relayTestLayer));
      
      diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts
      --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts
      +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts
      @@ -474,13 +474,9 @@
         never,
         ManagedRelayClient
       > {
      -  return registerDeviceForCurrentUser().pipe(
      -    Effect.catch((error) =>
      -      Effect.sync(() => {
      -        logRegistrationError("device registration refresh failed", error);
      -      }),
      -    ),
      -  );
      +  return Effect.sync(() => {
      +    enqueueDeviceRegistration({}, "device registration refresh failed");
      +  });
       }
       
       export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
      
      diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      @@ -73,7 +73,15 @@
             setAgentAwarenessRelayTokenProvider(null);
             setManagedRelaySession(appAtomRegistry, null);
             if (previousObservedAccount !== null) {
      -        void queueAccountCleanup(previous);
      +        void queueAccountCleanup(
      +          previous ??
      +            (typeof previousObservedAccount === "string"
      +              ? {
      +                  userId: previousObservedAccount,
      +                  provider: () => getToken(resolveRelayClerkTokenOptions()),
      +                }
      +              : null),
      +        );
             }
             return;
           }
      You can send follow-ups to the cloud agent here.
    13. @@ -14,3 +83,19 @@
      1483 menu.style.top = `${top}px`;
      1584 }
      1685
      86+function isNodeWithinMenuStack(target: EventTarget | null, menuStack: readonly HTMLDivElement[]) {
      87+ if (typeof Node !== "undefined" && target instanceof Node) {
      88+ return menuStack.some((menu) => menu.contains(target));
      89+ }
      90+ if (!target || typeof target !== "object") {
      91+ return false;
      92+ }
      93+
      94+ let current: unknown = target;
      95+ while (current && typeof current === "object") {
      96+ if (menuStack.includes(current as HTMLDivElement)) {
      97+ return true;
      98+ }
      99+ current = (current as { parent?: unknown }).parent;
      100+ }
      101+ return false;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/contextMenuFallback.ts:94

      The fallback traversal in isNodeWithinMenuStack uses .parent (line 99), but DOM nodes expose parentNode or parentElement, not parent. When instanceof Node fails (e.g., cross-frame elements), the traversal climbs via .parent which is always undefined on real DOM nodes, so menuStack.includes never matches and clicks inside submenus incorrectly dismiss the menu.

      +    let current: Node | null = target as Node;
      +    while (current) {
      +      if (menuStack.includes(current as HTMLDivElement)) {
      +        return true;
      +      }
      +      current = current.parentNode;
      +    }
      +    return false;
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/contextMenuFallback.ts around lines 94-101:
      
      The fallback traversal in `isNodeWithinMenuStack` uses `.parent` (line 99), but DOM nodes expose `parentNode` or `parentElement`, not `parent`. When `instanceof Node` fails (e.g., cross-frame elements), the traversal climbs via `.parent` which is always `undefined` on real DOM nodes, so `menuStack.includes` never matches and clicks inside submenus incorrectly dismiss the menu.
      
      Evidence trail:
      apps/web/src/contextMenuFallback.ts lines 86-102 (function `isNodeWithinMenuStack`, fallback path with `.parent` at line 99). git_grep for `parentNode|parentElement` in contextMenuFallback.ts returns no results. Menu elements are standard `HTMLDivElement` created at line 167 via `document.createElement('div')`. DOM `Node` interface specifies `parentNode` and `parentElement`, not `parent`.
      @@ -0,0 +93,21 @@
      93+ if (Array.isArray(answer)) {
      94+ return answer.flatMap((entry) => {
      95+ const text = typeof entry === "string" ? trimmed(entry) : undefined;
      96+ return text ? [text] : [];
      97+ });
      98+ }
      99+ const text = typeof answer === "string" ? trimmed(answer) : undefined;
      100+ return text ? [text] : [];
      101+}
      102+
      103+function normalizeAnswerForXAi(
      104+ question: XAiAskUserQuestionRequestParams["questions"][number],
      105+ answer: unknown,
      106+): NormalizedXAiAnswer | undefined {
      107+ const values = answerValues(answer);
      108+ if (values.length === 0) {
      109+ return undefined;
      110+ }
      111+
      112+ const optionByLabel = new Map(question.options.map((option) => [option.label, option]));
      113+ const resolvedValues = values.map((value) => ({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low acp/XAiAcpExtension.ts:112

      When question.options is empty, extractXAiAskUserQuestions shows the user a synthetic "OK" option, but normalizeAnswerForXAi only validates against the original empty question.options. When the user selects "OK", it doesn't match any option, gets treated as freeform text in notes, and selectedLabels incorrectly falls back to ["Other"] instead of ["OK"]. Consider using the same synthetic default logic in normalizeAnswerForXAi so the answer validation matches the displayed options.

      -  const optionByLabel = new Map(question.options.map((option) => [option.label, option]));
      +  const effectiveOptions =
      +    question.options.length > 0
      +      ? question.options
      +      : [{ label: "OK", description: "Continue", preview: undefined }];
      +  const optionByLabel = new Map(effectiveOptions.map((option) => [option.label, option]));
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/provider/acp/XAiAcpExtension.ts around lines 112-113:
      
      When `question.options` is empty, `extractXAiAskUserQuestions` shows the user a synthetic "OK" option, but `normalizeAnswerForXAi` only validates against the original empty `question.options`. When the user selects "OK", it doesn't match any option, gets treated as freeform text in `notes`, and `selectedLabels` incorrectly falls back to `["Other"]` instead of `["OK"]`. Consider using the same synthetic default logic in `normalizeAnswerForXAi` so the answer validation matches the displayed options.
      
      Evidence trail:
      apps/server/src/provider/acp/XAiAcpExtension.ts lines 49-65 (`extractXAiAskUserQuestions` with synthetic "OK" option at line 63), lines 103-137 (`normalizeAnswerForXAi` validates against original empty `question.options` at line 112, falls back to `["Other"]` at line 134), lines 147-153 (`makeXAiAskUserQuestionResponse` passes original question to `normalizeAnswerForXAi`).
    14. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Spurious relay cleanup on load
        • Added previousObservedAccount !== undefined guard to the signed-out branch to match the account-switch branch, preventing cleanup when no user was ever observed as signed in.

      Create PR

      Or push these changes by commenting:

      @cursor push 0d6918a8b3
      Preview (pingdotgg/t3code@0d6918a8b3)
      diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      @@ -72,7 +72,7 @@
             previousTokenProviderRef.current = null;
             setAgentAwarenessRelayTokenProvider(null);
             setManagedRelaySession(appAtomRegistry, null);
      -      if (previousObservedAccount !== null) {
      +      if (previousObservedAccount !== undefined && previousObservedAccount !== null) {
               void queueAccountCleanup(previous);
             }
             return;
      You can send follow-ups to the cloud agent here.
    15. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Stale tokens break selection mapping
        • Extracted a currentValidTokens() helper that filters tokens against the current value string, and used it in displayOffset(forSourceOffset:) so stale tokens no longer participate in offset calculations.

      Create PR

      Or push these changes by commenting:

      @cursor push b5abc57d3c
      Preview (pingdotgg/t3code@b5abc57d3c)
      diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
      --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
      +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
      @@ -464,12 +464,7 @@
           let result = NSMutableAttributedString()
           let source = value as NSString
           var cursor = 0
      -    let validTokens = tokens.filter {
      -      $0.start >= cursor &&
      -        $0.end > $0.start &&
      -        $0.end <= source.length &&
      -        source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
      -    }
      +    let validTokens = currentValidTokens()
       
           for token in validTokens {
             if token.start < cursor {
      @@ -678,11 +673,12 @@
       
         private func displayOffset(forSourceOffset sourceOffset: Int) -> Int {
           let boundedOffset = max(0, min((value as NSString).length, sourceOffset))
      +    let active = currentValidTokens()
           var collapsedLength = 0
      -    for token in tokens where token.end <= boundedOffset {
      +    for token in active where token.end <= boundedOffset {
             collapsedLength += max(0, token.end - token.start - 1)
           }
      -    if let token = tokens.first(where: { $0.start < boundedOffset && boundedOffset < $0.end }) {
      +    if let token = active.first(where: { $0.start < boundedOffset && boundedOffset < $0.end }) {
             return token.start - collapsedLength + 1
           }
           return boundedOffset - collapsedLength
      @@ -723,9 +719,9 @@
           return try? JSONDecoder().decode(type, from: data)
         }
       
      -  private func tokensMatchCurrentValue() -> Bool {
      +  private func currentValidTokens() -> [ComposerTokenPayload] {
           let source = value as NSString
      -    return tokens.allSatisfy {
      +    return tokens.filter {
             $0.start >= 0 &&
               $0.end > $0.start &&
               $0.end <= source.length &&
      @@ -733,19 +729,12 @@
           }
         }
       
      +  private func tokensMatchCurrentValue() -> Bool {
      +    currentValidTokens().count == tokens.count
      +  }
      +
         private func documentMatchesExpectedTokens() -> Bool {
      -    let source = value as NSString
      -    let expectedSources = tokens.compactMap { token -> String? in
      -      guard token.start >= 0,
      -            token.end > token.start,
      -            token.end <= source.length,
      -            source.substring(
      -              with: NSRange(location: token.start, length: token.end - token.start)
      -            ) == token.source else {
      -        return nil
      -      }
      -      return token.source
      -    }
      +    let expectedSources = currentValidTokens().map(\.source)
           var renderedSources: [String] = []
           textView.attributedText.enumerateAttribute(
             .attachment,
      You can send follow-ups to the cloud agent here.
    16. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      There are 2 total unresolved issues (including 1 from previous review).

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Recording lock survives tab close
        • Added a check in closeTab to clear recordingTabIdRef when the closed tab matches the currently recording tab, preventing the stale lock from blocking future recordings.

      Create PR

      Or push these changes by commenting:

      @cursor push 49b0b52408
      Preview (pingdotgg/t3code@49b0b52408)
      diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts
      --- a/apps/desktop/src/preview/Manager.ts
      +++ b/apps/desktop/src/preview/Manager.ts
      @@ -1130,6 +1130,10 @@
           const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
           if (!tab) return;
           yield* cancelPickElement(tabId);
      +    const recordingTabId = yield* Ref.get(recordingTabIdRef);
      +    if (Option.isSome(recordingTabId) && recordingTabId.value === tabId) {
      +      yield* Ref.set(recordingTabIdRef, Option.none());
      +    }
           if (tab.webContentsId != null) {
             yield* Effect.all(
               [detachControlSession(tab.webContentsId), detachListeners(tab.webContentsId)],
      You can send follow-ups to the cloud agent here.
    17. @@ -400,4 +310,17 @@
      400- }),
      401- );
      402- });
      403- },
      310+ toastManager.add(
      311+ stackedThreadToast({
      312+ type: "warning",
      313+ title: "Invalid keybindings configuration",
      314+ description: decision.message,
      315+ actionVariant: "outline",
      316+ actionProps: {
      317+ children: "Open keybindings.json",
      318+ onClick: () => {
      319+ if (!serverConfig || !primaryEnvironment) {
      320+ return;
      321+ }
      322+
      323+ const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
      324+ if (!editor) {
      325+ return;
      326+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low routes/__root.tsx:323

      When resolveAndPersistPreferredEditor returns null, the onClick handler returns silently at line 325 without showing any feedback to the user. Previously this threw new Error("No available editors found.") which was caught and displayed in an error toast. Now the button appears to do nothing when no editor is available.

                  if (!editor) {
      +              toastManager.add(
      +                stackedThreadToast({
      +                  type: "error",
      +                  title: "Unable to open keybindings file",
      +                  description: "No available editors found.",
      +                }),
      +              );
                    return;
                  }
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/routes/__root.tsx around lines 323-326:
      
      When `resolveAndPersistPreferredEditor` returns `null`, the `onClick` handler returns silently at line 325 without showing any feedback to the user. Previously this threw `new Error("No available editors found.")` which was caught and displayed in an error toast. Now the button appears to do nothing when no editor is available.
      
      Evidence trail:
      apps/web/src/routes/__root.tsx lines 319-342 at REVIEWED_COMMIT (new code with silent return). git_diff base=MERGE_BASE head=REVIEWED_COMMIT path=apps/web/src/routes/__root.tsx shows old code had `throw new Error("No available editors found.")` inside a `.then()` caught by `.catch()` that displayed an error toast. Commit a01d712751f8 introduced `resolveAndPersistPreferredEditor` with the same throw pattern in the previous iteration.
      @@ -423,2 +438,2 @@
      423438 const userImages = row.message.attachments ?? [];
      424439 const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High chat/MessagesTimeline.tsx:439

      Line 449 calls extractTrailingElementContexts(visibleText) on text that has already had element contexts stripped by deriveDisplayedUserMessageState on line 439, so elementContextState.contexts is always empty. The element contexts are actually stored in displayedUserMessage.elementContexts, but the code ignores them and renders an empty chip list instead. Use displayedUserMessage.elementContexts instead of elementContextState.contexts on lines 497-505.

      Also found in 1 other location(s)

      apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift:679

      The displayOffset(forSourceOffset:) method calculates collapsed lengths using the raw tokens array, but makeAttributedDocument() filters tokens for validity (checking source substring matches). If any token in tokens has an invalid/mismatched source, displayOffset will include its collapsed length in calculations while the actual attributed document won&#39;t contain that attachment. This causes incorrect cursor/selection positioning. For example, if value=&#34;hello world&#34; and tokens contains a token with source=&#34;wrong&#34; (not matching the actual substring), the selection conversion will be off.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/components/chat/MessagesTimeline.tsx around line 439:
      
      Line 449 calls `extractTrailingElementContexts(visibleText)` on text that has already had element contexts stripped by `deriveDisplayedUserMessageState` on line 439, so `elementContextState.contexts` is always empty. The element contexts are actually stored in `displayedUserMessage.elementContexts`, but the code ignores them and renders an empty chip list instead. Use `displayedUserMessage.elementContexts` instead of `elementContextState.contexts` on lines 497-505.
      
      Evidence trail:
      apps/web/src/components/chat/MessagesTimeline.tsx lines 436-510 (REVIEWED_COMMIT) — UserTimelineRow component showing the double extraction. apps/web/src/lib/terminalContext.ts lines 248-262 (REVIEWED_COMMIT) — deriveDisplayedUserMessageState calls extractTrailingElementContexts internally and stores results in elementContexts, returning visibleText with element contexts already stripped.
      
      Also found in 1 other location(s):
      - apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift:679 -- The `displayOffset(forSourceOffset:)` method calculates collapsed lengths using the raw `tokens` array, but `makeAttributedDocument()` filters tokens for validity (checking `source` substring matches). If any token in `tokens` has an invalid/mismatched `source`, `displayOffset` will include its collapsed length in calculations while the actual attributed document won't contain that attachment. This causes incorrect cursor/selection positioning. For example, if `value="hello world"` and `tokens` contains a token with `source="wrong"` (not matching the actual substring), the selection conversion will be off.
      
      @@ -0,0 +145,21 @@
      145+ for (const [requestId, entry] of pending) {
      146+ if (entry.clientId === clientId) {
      147+ pending.delete(requestId);
      148+ disconnected.push(entry);
      149+ }
      150+ }
      151+ return [disconnected, { ...current, clients, owners, pending }] as const;
      152+ });
      153+ yield* Effect.forEach(
      154+ toFail,
      155+ ({ deferred }) =>
      156+ Deferred.fail(
      157+ deferred,
      158+ new PreviewAutomationUnavailableError({
      159+ message: "The preview automation client disconnected.",
      160+ }),
      161+ ),
      162+ { discard: true },
      163+ );
      164+ yield* Queue.shutdown(queue);
      165+ });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High mcp/PreviewAutomationBroker.ts:131

      When a client reconnects with the same clientId, disconnect is called with the old queue but checks against the new queue stored in state, causing the equality check at line 136 to fail. The function returns early without shutting down the old queue or failing its pending requests, leaving them hanging indefinitely and leaking the queue.

        const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
          clientId: string,
          queue: ClientConnection["queue"],
        ) {
          const toFail = yield* SynchronizedRef.modify(state, (current) => {
      -      if (current.clients.get(clientId)?.queue !== queue) {
      +      const stored = current.clients.get(clientId);
      +      // Only skip if this exact connection is still registered
      +      if (stored?.queue === queue) {
               return [[] as ReadonlyArray<PendingRequest>, current] as const;
             }
             const clients = new Map(current.clients);
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/mcp/PreviewAutomationBroker.ts around lines 131-165:
      
      When a client reconnects with the same `clientId`, `disconnect` is called with the old queue but checks against the new queue stored in state, causing the equality check at line 136 to fail. The function returns early without shutting down the old queue or failing its pending requests, leaving them hanging indefinitely and leaking the queue.
    18. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      There are 3 total unresolved issues (including 1 from previous review).

      Autofix Details

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: Markdown links ignore taps
        • Changed getTouchChild to iterate _view.subviews (the Fabric contentView where T3MarkdownTextRun children are mounted) instead of self.subviews, which only contained _textView and the empty content container.
      • ✅ Fixed: Catalog reads empty without encryption
        • Replaced the silent Option.none() return with a dedicated DesktopConnectionCatalogStoreEncryptionUnavailableError when an encrypted catalog file exists on disk but safe-storage encryption is unavailable, so the client correctly surfaces the error instead of treating saved connections as missing.

      Create PR

      Or push these changes by commenting:

      @cursor push 10af3a0dce
      Preview (pingdotgg/t3code@10af3a0dce)
      diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts
      --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts
      +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts
      @@ -88,11 +88,20 @@
         }
       }
       
      +export class DesktopConnectionCatalogStoreEncryptionUnavailableError extends Data.TaggedError(
      +  "DesktopConnectionCatalogStoreEncryptionUnavailableError",
      +)<{}> {
      +  override get message() {
      +    return "Cannot read the encrypted connection catalog because encryption is unavailable.";
      +  }
      +}
      +
       export interface DesktopConnectionCatalogStoreShape {
         readonly get: Effect.Effect<
           Option.Option<string>,
           | DesktopConnectionCatalogStoreReadError
           | DesktopConnectionCatalogStoreDecodeError
      +    | DesktopConnectionCatalogStoreEncryptionUnavailableError
           | DesktopConnectionCatalogStoreMigrationError
           | ElectronSafeStorage.ElectronSafeStorageAvailabilityError
           | ElectronSafeStorage.ElectronSafeStorageDecryptError
      @@ -300,7 +309,7 @@
                 return yield* migrateLegacyCatalog;
               }
               if (!(yield* safeStorage.isEncryptionAvailable)) {
      -          return Option.none<string>();
      +          return yield* new DesktopConnectionCatalogStoreEncryptionUnavailableError();
               }
               const decrypted = yield* decodeSecretBytes(document.value.encryptedCatalog).pipe(
                 Effect.flatMap(safeStorage.decryptString),
      
      diff --git a/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownText.mm b/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownText.mm
      --- a/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownText.mm
      +++ b/apps/mobile/modules/t3-markdown-text/ios/T3MarkdownText.mm
      @@ -616,7 +616,7 @@
         ];
       
         int currIndex = -1;
      -  for (UIView* child in self.subviews) {
      +  for (UIView* child in _view.subviews) {
           if (![child isKindOfClass:[T3MarkdownTextRun class]]) {
             continue;
           }
      You can send follow-ups to the cloud agent here.
    19. @@ -0,0 +228,21 @@
      228+ await Promise.all(
      229+ removed.map(async (message) => {
      230+ try {
      231+ const file = await getMessageFile(message.messageId);
      232+ if (file.exists) {
      233+ file.delete();
      234+ }
      235+ } catch (error) {
      236+ console.warn("[thread-outbox] failed to clear persisted message", error);
      237+ }
      238+ }),
      239+ );
      240+
      241+ appAtomRegistry.set(
      242+ queuedMessagesByThreadKeyAtom,
      243+ groupQueuedThreadMessages(
      244+ allMessages.filter((message) => message.environmentId !== environmentId),
      245+ ),
      246+ );
      247+ });
      248+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/thread-outbox.ts:218

      clearThreadOutboxEnvironment can race with the pending loadPromise from ensureThreadOutboxLoaded. If loading is in progress, this function deletes files and clears the atom, but then the pending disk read (which captured the old file contents before deletion) completes and adds those cleared messages back into the atom. This causes messages for the cleared environment to reappear in-memory after the function returns, until the next app restart.

      Consider awaiting loadPromise before proceeding, or ensuring the load operation respects concurrent deletions.

      export async function clearThreadOutboxEnvironment(environmentId: EnvironmentId): Promise<void> {
      +  if (loadPromise !== null) {
      +    await loadPromise;
      +  }
         await serializeThreadOutboxMutation(async () => {
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/mobile/src/state/thread-outbox.ts around lines 218-248:
      
      `clearThreadOutboxEnvironment` can race with the pending `loadPromise` from `ensureThreadOutboxLoaded`. If loading is in progress, this function deletes files and clears the atom, but then the pending disk read (which captured the old file contents before deletion) completes and adds those cleared messages back into the atom. This causes messages for the cleared environment to reappear in-memory after the function returns, until the next app restart.
      
      Consider awaiting `loadPromise` before proceeding, or ensuring the load operation respects concurrent deletions.
      
      Evidence trail:
      apps/mobile/src/state/thread-outbox.ts lines 55-65 (mutationQueue and serializeThreadOutboxMutation), lines 164-182 (ensureThreadOutboxLoaded - loadPersistedMessages resolves first, THEN queues the mutation via .then), lines 218-248 (clearThreadOutboxEnvironment - immediately queues mutation). The race: load starts disk I/O → clear queues and runs mutation → disk I/O resolves → load queues mutation AFTER clear → load re-adds cleared messages from stale persistedMessages.
    20. @@ -0,0 +78,21 @@
      78+ style={[flattenedStyle]}
      79+ // @ts-expect-error Weirdness
      80+ onPress={undefined}
      81+ onLongPress={undefined}
      82+ >
      83+ {nativeChildren}
      84+ </T3MarkdownTextNativeComponent>
      85+ </TextAncestorContext.Provider>
      86+ );
      87+ }
      88+
      89+ return <>{nativeChildren}</>;
      90+}
      91+
      92+function MarkdownTextPrimitiveInner(props: MarkdownTextPrimitiveProps) {
      93+ const [isAncestor] = useTextAncestorContext();
      94+
      95+ // Even if the uiTextView prop is set, we can still default to using
      96+ // normal selection (i.e. base RN text) if the text doesn't need to be
      97+ // selectable
      98+ if ((!props.selectable || !props.uiTextView) && !isAncestor) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/MarkdownTextPrimitive.tsx:98

      MarkdownTextPrimitiveInner checks !props.selectable on line 98, but selectable defaults to true via textDefaults. When a caller sets uiTextView={true} without explicitly passing selectable, the component incorrectly returns RNText instead of MarkdownTextPrimitiveChild because undefined is treated as falsy. Consider checking props.selectable === false to respect the intended default behavior.

      -  if ((!props.selectable || !props.uiTextView) && !isAncestor) {
      +  if ((props.selectable === false || !props.uiTextView) && !isAncestor) {
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/mobile/modules/t3-markdown-text/src/MarkdownTextPrimitive.tsx around line 98:
      
      `MarkdownTextPrimitiveInner` checks `!props.selectable` on line 98, but `selectable` defaults to `true` via `textDefaults`. When a caller sets `uiTextView={true}` without explicitly passing `selectable`, the component incorrectly returns `RNText` instead of `MarkdownTextPrimitiveChild` because `undefined` is treated as falsy. Consider checking `props.selectable === false` to respect the intended default behavior.
    21. packages/client-runtime/src/state/vcs.ts line 29Resolvedby juliusmarminge
    22. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/c1281076e628cd6825ddf11befeb6a0df8b52468/apps/web/src/components/ChatView.tsx#L3390

      The rightPanel.toggle keyboard shortcut handler was removed from the global keydown event listener at line 3493, but the UI still displays the shortcut label in PanelLayoutControls and ChatHeader. Users pressing the configured keyboard shortcut get no response because the handler case for command === "rightPanel.toggle" is missing.

      ✅ Resolved in 344fca1edcbba0c123acf2f2bd1a91ed9e6b2436

    23. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/4a06d7753204de5145406271acf32c508fcb2595/apps/web/src/components/ChatView.tsx#L2576

      saveProjectScript and updateProjectScript delete the previewUrl and autoOpenPreview fields when constructing ProjectScript objects, so these settings are silently dropped when users save scripts. Additionally, runProjectScript no longer checks script.autoOpenPreview to automatically open the preview panel, so the feature is completely disabled. If this removal is intentional, consider documenting the breaking change; otherwise, restore the field propagation and auto-open logic.

      No longer relevant as of ed0b6119c24e9f450c812b0a01f64d90c5967a13

    24. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Stale relay session on auth reload
        • Added deactivation calls in the early !isLoaded return path of both web and mobile auth bridge effects so the relay session is cleared when Clerk transitions through a not-loaded state.

      Create PR

      Or push these changes by commenting:

      @cursor push f44548f2d4
      Preview (pingdotgg/t3code@f44548f2d4)
      diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx
      @@ -59,6 +59,7 @@
         useEffect(() => {
           let cancelled = false;
           if (!isLoaded) {
      +      deactivateCloudRelayAccount();
             return;
           }
       
      
      diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsx
      --- a/apps/web/src/cloud/managedAuth.tsx
      +++ b/apps/web/src/cloud/managedAuth.tsx
      @@ -49,6 +49,7 @@
       
         useEffect(() => {
           if (!isLoaded) {
      +      deactivateManagedRelayAuthentication();
             return;
           }
      You can send follow-ups to the cloud agent here.
    25. @@ -49,7 +51,5 @@
      4951 this.saving = true;
      5052 const contents = this.latestContents;
      5153 const revision = this.latestRevision;
      52- let succeeded = false;
      53- try {
      54- await this.options.persist(contents);
      55- succeeded = true;
      54+ const result = await this.options.persist(contents);
      55+ const succeeded = result._tag === "Success";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium files/fileSaveCoordinator.ts:54

      When persist throws an unexpected exception (e.g. network error or AbortController signal), the promise rejection is not caught and this.saving remains true forever. This prevents all subsequent save attempts because persistLatest returns early when this.saving is true, causing data loss. The removed catch block previously ensured this.saving = false always executed.

      -    const result = await this.options.persist(contents);
      +    let result: AtomCommandResult<A, E>;
      +    try {
      +      result = await this.options.persist(contents);
      +    } catch {
      +      result = { _tag: "Error", error: {} as E };
      +    }
           const succeeded = result._tag === "Success";
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/components/files/fileSaveCoordinator.ts around lines 54-55:
      
      When `persist` throws an unexpected exception (e.g. network error or AbortController signal), the promise rejection is not caught and `this.saving` remains `true` forever. This prevents all subsequent save attempts because `persistLatest` returns early when `this.saving` is true, causing data loss. The removed `catch` block previously ensured `this.saving = false` always executed.
      
      Evidence trail:
      apps/web/src/components/files/fileSaveCoordinator.ts lines 48-75 (REVIEWED_COMMIT): persistLatest() has no try-catch around line 54's await. `this.saving = false` on line 60 is unreachable if persist throws. Line 49 early-returns when `this.saving` is true. Lines 31, 38, 71 show callers use `void this.persistLatest()` discarding rejections. git_diff MERGE_BASE..REVIEWED_COMMIT shows removal of `try { ... } catch {}` block. apps/web/src/components/files/FilePreviewPanel.tsx lines 101-105 show the persist callback calls writeFile which wraps a network call.
    26. pr-roaster(GitHub profile, opens in a new tab)commented

      Theo gg roasted this PR

      So sorry @juliusmarminge, you (and/or your agent) deserved the roast.

      Median pull request: six files, clean and tight. Then "connection-state-audit" showed up one night. You went in just to look — a careful little tour — five hundred fifty-three files later, you'd gutted the core.

      https://github.com/user-attachments/assets/54457884-81e7-4c6d-b520-5a5cea33f20e

      Want one in your own voice? Make songs with custom personas at mozartai.com

    27. @@ -1229,10 +1216,10 @@
      12291216 instanceId: ProviderInstanceId.make("codex"),
      12301217 model: DEFAULT_MODEL,
      12311218 },
      1232- localDraftError,
      12331219 )
      12341220 : undefined,
      1235- [draftThread, fallbackDraftProject?.defaultModelSelection, localDraftError, threadId],
      1221+ [draftThread, fallbackDraftProject?.defaultModelSelection, threadId],
      12361222 );
      1237- const isServerThread = routeKind === "server" && serverThread !== undefined;
      1223+ const isServerThread = routeKind === "server" && serverThread !== null;
      12381224 const activeThread = isServerThread ? serverThread : localDraftThread;
      1225+ const threadError = isServerThread
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/ChatView.tsx:1225

      Dismissing the ThreadErrorBanner for a server thread sets localServerErrorsByThreadKey[routeThreadKey] to null, but threadError is derived as localServerError ?? serverThread?.session?.lastError ?? null. Since null is nullish, null ?? serverThread?.session?.lastError evaluates to serverThread.session.lastError, so the banner immediately reappears when the server session carries a persistent lastError. The dismiss button is effectively non-functional in that scenario.

      The root cause is that localServerError (line 1208) coalesces undefined to null via ?? null, making it impossible to distinguish "no local override" from "explicitly dismissed". Fix both: (1) drop ?? null from line 1208 so localServerError is undefined when unset, and (2) replace localServerError ?? on line 1226 with an explicit localServerError !== undefined ? check so a null dismissal stops the fallthrough.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/components/ChatView.tsx around line 1225:
      
      Dismissing the `ThreadErrorBanner` for a server thread sets `localServerErrorsByThreadKey[routeThreadKey]` to `null`, but `threadError` is derived as `localServerError ?? serverThread?.session?.lastError ?? null`. Since `null` is nullish, `null ?? serverThread?.session?.lastError` evaluates to `serverThread.session.lastError`, so the banner immediately reappears when the server session carries a persistent `lastError`. The dismiss button is effectively non-functional in that scenario.
      
      The root cause is that `localServerError` (line 1208) coalesces `undefined` to `null` via `?? null`, making it impossible to distinguish "no local override" from "explicitly dismissed". Fix both: (1) drop `?? null` from line 1208 so `localServerError` is `undefined` when unset, and (2) replace `localServerError ??` on line 1226 with an explicit `localServerError !== undefined ?` check so a `null` dismissal stops the fallthrough.
      
      Evidence trail:
      apps/web/src/components/ChatView.tsx lines 1116-1118 (state type: Record<string, string | null>), line 1208 (localServerError = ... ?? null), lines 1225-1227 (threadError derivation with ?? chain), line 4790 (onDismiss calls setThreadError with null), lines 2224-2240 (setThreadError implementation), packages/client-runtime/src/errors/transport.ts line 37-38 (sanitizeThreadErrorMessage returns null for null input), packages/client-runtime/src/errors/transport.test.ts line 69 (confirms sanitizeThreadErrorMessage(null) returns null).
    28. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      Autofix Details

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: Shell cache not flushed
        • Added Effect.addFinalizer to makeEnvironmentShellState that persists the current snapshot when the scope tears down, matching the existing pattern in makeEnvironmentThreadState.
      • ✅ Fixed: Materialized draft not finalized
        • Replaced markPromotedDraftThreadByRef with finalizePromotedDraftThreadByRef so that when a draft's thread is already materialized in the shell, the draft is fully removed instead of lingering in a promoting state.

      Create PR

      Or push these changes by commenting:

      @cursor push 95dd1f4c87
      Preview (pingdotgg/t3code@95dd1f4c87)
      diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts
      --- a/apps/web/src/hooks/useHandleNewThread.ts
      +++ b/apps/web/src/hooks/useHandleNewThread.ts
      @@ -7,7 +7,7 @@
       import { useParams, useRouter } from "@tanstack/react-router";
       import { useCallback, useMemo } from "react";
       import {
      -  markPromotedDraftThreadByRef,
      +  finalizePromotedDraftThreadByRef,
         type DraftThreadEnvMode,
         type DraftThreadState,
         useComposerDraftStore,
      @@ -71,7 +71,7 @@
                 ? null
                 : storedDraftThread;
             if (storedDraftThreadRef && reusableStoredDraftThread === null) {
      -        markPromotedDraftThreadByRef(storedDraftThreadRef);
      +        finalizePromotedDraftThreadByRef(storedDraftThreadRef);
             }
             const latestActiveDraftThread: DraftThreadState | null = currentRouteTarget
               ? currentRouteTarget.kind === "server"
      
      diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts
      --- a/packages/client-runtime/src/state/shell.ts
      +++ b/packages/client-runtime/src/state/shell.ts
      @@ -163,6 +163,17 @@
           Effect.forkScoped,
         );
       
      +  yield* Effect.addFinalizer(() =>
      +    SubscriptionRef.get(state).pipe(
      +      Effect.flatMap((current) =>
      +        Option.match(current.snapshot, {
      +          onNone: () => Effect.void,
      +          onSome: persist,
      +        }),
      +      ),
      +    ),
      +  );
      +
         return state;
       });
      You can send follow-ups to the cloud agent here.
    29. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      There are 3 total unresolved issues (including 1 from previous review).

      Autofix Details

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: Environment rows ignore prop updates
        • Added a key prop derived from the environment data to ProviderEnvironmentSection so React remounts it when props change, keeping draft rows in sync with external updates.
      • ✅ Fixed: Drawer height ignores prop updates
        • Added setDrawerHeightState synchronization in the existing controlledDrawerHeight/threadId effect so that prop-driven height changes update the local drawer height state.

      Create PR

      Or push these changes by commenting:

      @cursor push 673bd5bcce
      Preview (pingdotgg/t3code@673bd5bcce)
      diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
      --- a/apps/web/src/components/ThreadTerminalDrawer.tsx
      +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
      @@ -1106,6 +1106,11 @@
       
         useEffect(() => {
           lastSyncedHeightRef.current = controlledDrawerHeight;
      +    setDrawerHeightState((current) =>
      +      current.threadId === threadId && current.height === controlledDrawerHeight
      +        ? current
      +        : { threadId, height: controlledDrawerHeight },
      +    );
         }, [controlledDrawerHeight, threadId]);
       
         const handleResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
      
      diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx
      --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx
      +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx
      @@ -77,6 +77,19 @@
         };
       }
       
      +function getProviderEnvironmentSectionKey(
      +  environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
      +): string {
      +  return JSON.stringify(
      +    environment.map((variable) => [
      +      variable.name,
      +      variable.value,
      +      variable.sensitive,
      +      variable.valueRedacted ?? null,
      +    ]),
      +  );
      +}
      +
       /**
        * Read a string[] at `key` from the opaque config blob, filtering out
        * non-string entries. Used for `customModels`, which is always typed as
      @@ -444,6 +457,8 @@
           : null;
       
         const customModels = readConfigStringArray(instance.config, "customModels");
      +  const environment = instance.environment ?? [];
      +  const environmentSectionKey = getProviderEnvironmentSectionKey(environment);
         // Server-returned models may lag behind settings writes. Treat probe
         // models as the source for built-ins only; custom rows come directly
         // from the current instance config so add/remove reflects immediately.
      @@ -759,7 +774,8 @@
       
                   <div className="border-t border-border/60 px-4 py-3 sm:px-5">
                     <ProviderEnvironmentSection
      -                environment={instance.environment ?? []}
      +                key={environmentSectionKey}
      +                environment={environment}
                       onChange={updateEnvironment}
                     />
                   </div>
      You can send follow-ups to the cloud agent here.

Sign in to join this conversation.