Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix: prod builds loads asset files with relative file urls, not from the backend over http #22

Closedjuliusmarmingewants to merge 2 commits intomain fromcodething/25389242opened View on GitHub

juliusmarmingecommented

Summary

  • Replace production window startup from static index.html loading to backend HTTP URL loading on loopback.
  • Add backend readiness polling before creating the window in production, with timeout and retry delays to avoid race conditions.
  • Centralize loopback host usage and improve bootstrap error handling by logging failures and quitting cleanly.
  • Extend desktop smoke test fatal pattern detection to include ERR_FILE_NOT_FOUND.

Testing

  • Not run (tests were not executed in this environment).
  • Smoke test coverage updated to fail on ERR_FILE_NOT_FOUND in apps/desktop/scripts/smoke-test.mjs.

Open with Devin

Summary by CodeRabbit

  • Refactor

    • Consolidated multi-line code structures into single-line expressions across multiple modules for improved consistency and readability.
  • Chores

    • Enhanced backend initialization and readiness coordination for improved reliability.
    • Adjusted project dependency ordering and environment variable configuration.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Walkthrough

      PR primarily applies formatting refactors across multiple files (converting multi-line signatures and literals to single-line forms) while introducing backend readiness coordination in the Electron main process via loopback-based health checks and port resolution. Additionally moves VITE environment variables from global to dev-task scope in build configuration.

      Changes

      Cohort / File(s)Summary
      Desktop Backend Readiness
      apps/desktop/src/main.ts, apps/desktop/scripts/smoke-test.mjs
      Introduces backend readiness polling via waitForBackendReady(), replaces port reservation with resolveBackendPort() validation, adds backendHttpUrl() and canConnectToBackendPort() helpers, updates window loading to use dynamic backend URL, and adds ERR_FILE_NOT_FOUND to fatal patterns.
      Server Formatting Refactors
      apps/server/src/codexAppServerManager.test.ts, apps/server/src/codexAppServerManager.ts, apps/server/src/coreServices.ts, apps/server/src/git.test.ts, apps/server/src/git.ts, apps/server/src/gitManager.test.ts, apps/server/src/gitManager.ts, apps/server/src/processRunner.test.ts, apps/server/src/processRunner.ts, apps/server/src/ptyAdapter.ts, apps/server/src/terminalManager.test.ts, apps/server/src/terminalManager.ts, apps/server/src/wsServer.test.ts
      Consolidates multi-line function signatures, type annotations, and array literals into single-line forms across test and implementation files with no semantic or control flow changes.
      Web Formatting Refactors
      apps/web/src/components/ChatView.tsx, apps/web/src/components/ThreadTerminalDrawer.tsx, apps/web/src/persistenceSchema.test.ts, apps/web/src/persistenceSchema.ts, apps/web/src/store.test.ts, apps/web/src/store.ts, apps/web/src/terminal-links.test.ts, apps/web/src/terminal-shortcuts.test.ts, apps/web/src/terminal-shortcuts.ts
      Converts multi-line expressions, conditions, and array literals to single-line forms; refactors terminal hydration logic with functionally equivalent restructuring but simplified formatting.
      Contracts Formatting Refactors
      packages/contracts/src/git.test.ts, packages/contracts/src/git.ts, packages/contracts/src/ipc.ts, packages/contracts/src/terminal.ts
      Reformats enum declarations, method signatures, and array literals from multi-line to single-line with no semantic changes.
      Web Dependency Reordering
      apps/web/package.json
      Reorders @xterm/addon-fit and @xterm/xterm entries in dependency block with no version changes.
      Build Configuration
      turbo.json
      Moves VITE_WS_URL and VITE_DEV_SERVER_URL environment variables from globalEnv to the dev task's environment configuration.

      Sequence Diagram(s)

      sequenceDiagram
          participant ElectronMain as Electron Main
          participant Bootstrap as Bootstrap Process
          participant BackendService as Backend Service
          participant LoopbackPort as Loopback Port (localhost)
          participant BrowserWindow as Browser Window
      
          ElectronMain->>Bootstrap: invoke bootstrap()
          Bootstrap->>Bootstrap: resolveBackendPort(T3CODE_PORT)
          Bootstrap->>BackendService: start backend service
          activate BackendService
          Bootstrap->>ElectronMain: return parsed port
          
          ElectronMain->>LoopbackPort: waitForBackendReady()
          loop Health Check Retry
              LoopbackPort->>BackendService: canConnectToBackendPort(port)
              alt Backend Ready
                  BackendService-->>LoopbackPort: connected
                  LoopbackPort-->>ElectronMain: backend ready
              else Retry
                  LoopbackPort->>LoopbackPort: wait BACKEND_READY_RETRY_DELAY_MS
              end
          end
          deactivate BackendService
          
          ElectronMain->>BrowserWindow: createWindow()
          ElectronMain->>BrowserWindow: loadURL(backendHttpUrl())
          BrowserWindow->>LoopbackPort: request app from backend
          LoopbackPort-->>BrowserWindow: serve app

      Estimated code review effort

      🎯 3 (Moderate) | ⏱️ ~25 minutes

      🚥 Pre-merge checks | ✅ 2 | ❌ 2
      ❌ Failed checks (2 warnings)
      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 5.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      Merge Conflict Detection⚠️ Warning❌ Merge conflicts detected (30 files):

      ⚔️ apps/desktop/scripts/smoke-test.mjs (content)
      ⚔️ apps/desktop/src/main.ts (content)
      ⚔️ apps/server/src/codexAppServerManager.test.ts (content)
      ⚔️ apps/server/src/codexAppServerManager.ts (content)
      ⚔️ apps/server/src/coreServices.ts (content)
      ⚔️ apps/server/src/git.test.ts (content)
      ⚔️ apps/server/src/git.ts (content)
      ⚔️ apps/server/src/gitManager.test.ts (content)
      ⚔️ apps/server/src/gitManager.ts (content)
      ⚔️ apps/server/src/processRunner.test.ts (content)
      ⚔️ apps/server/src/processRunner.ts (content)
      ⚔️ apps/server/src/ptyAdapter.ts (content)
      ⚔️ apps/server/src/terminalManager.test.ts (content)
      ⚔️ apps/server/src/terminalManager.ts (content)
      ⚔️ apps/server/src/wsServer.test.ts (content)
      ⚔️ apps/web/package.json (content)
      ⚔️ apps/web/src/components/ChatView.tsx (content)
      ⚔️ apps/web/src/components/ThreadTerminalDrawer.tsx (content)
      ⚔️ apps/web/src/persistenceSchema.test.ts (content)
      ⚔️ apps/web/src/persistenceSchema.ts (content)
      ⚔️ apps/web/src/store.test.ts (content)
      ⚔️ apps/web/src/store.ts (content)
      ⚔️ apps/web/src/terminal-links.test.ts (content)
      ⚔️ apps/web/src/terminal-shortcuts.test.ts (content)
      ⚔️ apps/web/src/terminal-shortcuts.ts (content)
      ⚔️ packages/contracts/src/git.test.ts (content)
      ⚔️ packages/contracts/src/git.ts (content)
      ⚔️ packages/contracts/src/ipc.ts (content)
      ⚔️ packages/contracts/src/terminal.ts (content)
      ⚔️ turbo.json (content)

      These conflicts must be resolved before merging into main.
      Resolve conflicts locally and push changes to this branch.
      ✅ Passed checks (2 passed)
      Check nameStatusExplanation
      Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
      Title check✅ PassedThe PR title accurately describes the main change: updating production builds to load asset files with relative URLs instead of from the backend over HTTP, which aligns with the primary objective of the backend readiness coordination and window loading changes.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing touches
      • 📝 Generate docstrings
        🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `codething/25389242`
      ⚔️ Resolve merge conflicts (beta)
      • Auto-commit resolved conflicts to branch `codething/25389242`
      • Create stacked PR with resolved conflicts
      • Post resolved changes as copyable diffs in a comment

      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Wait for desktop backend readiness and load production window from apps/desktop/src/main.ts:createWindow, using a fixed T3CODE_PORT default of 3773 and a 10s readiness timeout

      Introduce deterministic backend port resolution, poll for backend TCP readiness before creating the production window, and switch production loading to the backend HTTP server; apply formatting-only changes elsewhere.

      📍Where to Start

      Start with the startup flow in bootstrap and window creation in apps/desktop/src/main.ts.


      Macroscope summarized 0a0f436.
    3. Greptile Overview

      Greptile Summary

      Replaced static index.html loading with HTTP URL loading from the backend server to eliminate race conditions where the window would attempt to load files before the backend was ready to serve them. Added backend readiness polling with a 10-second timeout and 100ms retry intervals to ensure the HTTP server is accepting connections before creating the window. Centralized the loopback host constant (127.0.0.1) and improved error handling by logging bootstrap failures and quitting cleanly. Extended smoke test coverage to detect ERR_FILE_NOT_FOUND errors.

      Key changes:

      • Production window now loads from http://127.0.0.1:${backendPort} instead of directly from apps/web/dist/index.html
      • Added waitForBackendReady() function that polls port connectivity before window creation (production only)
      • Improved bootstrap error handling with catch block that logs and quits
      • Added ERR_FILE_NOT_FOUND to smoke test fatal patterns

      Confidence Score: 4/5

      • Safe to merge with minimal risk; addresses race condition properly
      • Implementation correctly solves the race condition between window loading and backend startup. The polling mechanism with timeout and retry logic is sound. macOS app reactivation scenario is handled correctly since backend persists between window closures. One minor concern about the macOS activate handler potentially creating a window when backend isn't ready, though in practice the backend should already be running from initial bootstrap.
      • No files require special attention

      Important Files Changed

      FilenameOverview
      apps/desktop/scripts/smoke-test.mjsAdded ERR_FILE_NOT_FOUND to fatal patterns list to catch file loading errors
      apps/desktop/src/main.tsAdded backend readiness polling with timeout, centralized loopback host constant, switched from static file loading to HTTP URL loading, improved error handling

      Sequence Diagram

      sequenceDiagram
          participant App as Electron App
          participant Backend as Node Backend
          participant Window as Browser Window
          
          App->>App: whenReady()
          App->>App: bootstrap()
          App->>App: reserveLoopbackPort()
          App->>App: registerIpcHandlers()
          App->>Backend: startBackend() (spawn child process)
          Backend->>Backend: Initialize HTTP server
          Backend->>Backend: Bind to loopback port
          
          alt Production Mode
              App->>Backend: canConnectToBackendPort() (poll)
              Backend-->>App: Connection refused
              App->>App: Wait 100ms
              App->>Backend: canConnectToBackendPort() (retry)
              Backend-->>App: Connected ✓
              App->>App: Backend ready
          end
          
          App->>Window: createWindow()
          
          alt Development Mode
              Window->>Window: loadURL(VITE_DEV_SERVER_URL)
          else Production Mode
              Window->>Backend: loadURL(http://127.0.0.1:port)
              Backend-->>Window: Serve static HTML/assets
          end
          
          Window->>Window: ready-to-show
          Window->>Window: show()
      Last reviewed commit: cbfbc36
    4. 2 files reviewed, 1 comment [Edit Code Review Agent Settings](https://app.greptile.com/review/github) | [Greptile](https://greptile.com?utm_source=greptile_expert&utm_medium=github&utm_campaign=code_reviews)
    5. Additional Comments (1)

      apps/desktop/src/main.ts macOS reactivation bypasses backend readiness check

      When user clicks dock icon after closing all windows, createWindow() is called directly without checking if backend is ready. In production mode, this will load from backendHttpUrl() before the backend is guaranteed to be listening.

        app.on("activate", () => {
          if (BrowserWindow.getAllWindows().length === 0 && mainWindow === null) {
            mainWindow = createWindow();
          }
        });
    6. @@ -214,7 +286,4 @@
      214286 void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
      215287 window.webContents.openDevTools({ mode: "detach" });
      216288 } else {
      217- if (!fs.existsSync(WEB_ENTRY)) {
      218- throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
      219- }
      220- void window.loadFile(WEB_ENTRY);
      289+ void window.loadURL(backendHttpUrl());
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      src/main.ts:289 activate may create a window before the backend is ready, causing a bad load and a duplicate window when bootstrap() finishes. Suggest guarding with a bootstrapping/ready flag (and mainWindow/backendPort) and waiting for waitForBackendReady() before calling createWindow().

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/desktop/src/main.ts around line 289:
      
      `activate` may create a window before the backend is ready, causing a bad load and a duplicate window when `bootstrap()` finishes. Suggest guarding with a bootstrapping/ready flag (and `mainWindow`/`backendPort`) and waiting for `waitForBackendReady()` before calling `createWindow()`.
    7. juliusmarminge changed the title

    8. juliusmarminge closed this

    9. 💡 Codex Review

      Here are some automated review suggestions for this pull request.

      Reviewed commit: 0a0f436ce2

      ℹ️ About Codex in GitHub

      Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

      • Open a pull request for review
      • Mark a draft as ready
      • Comment "@codex review".

      If Codex has suggestions, it will comment; otherwise it will react with 👍.

      Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

      @@ -33,17 +36,5 @@
      3336
      34-async function reserveLoopbackPort(): Promise<number> {
      35- return new Promise((resolve, reject) => {
      36- const probe = net.createServer();
      37- probe.listen(0, "127.0.0.1", () => {
      38- const address = probe.address();
      39- const port = typeof address === "object" && address !== null ? address.port : 0;
      40- probe.close(() => {
      41- if (port > 0) {
      42- resolve(port);
      43- return;
      44- }
      45- reject(new Error("Failed to reserve backend port"));
      46- });
      47- });
      48- probe.on("error", reject);
      49- });
      37+function resolveBackendPort(raw: string | undefined): number {
      38+ if (!raw || raw.trim().length === 0) {
      39+ return DEFAULT_BACKEND_PORT;
      40+ }

      P1 Badge Preserve dynamic allocation for the desktop backend port

      When T3CODE_PORT is unset, every production instance now uses port 3773 even though there is no single-instance lock. If another desktop instance or unrelated local service already owns that port, the spawned backend exits with EADDRINUSE; the readiness probe may then accept the existing listener and load its page, leaving the app connected with the wrong authentication token or displaying unrelated content. Retain the previous ephemeral-port allocation when no explicit port is configured.

      AGENTS.md reference: AGENTS.md:L12-L15

      Useful? React with 👍 / 👎.

      @@ -131,0 +165,21 @@
      165+ if (isQuitting) {
      166+ stop();
      167+ reject(new Error("Backend startup cancelled while app is quitting"));
      168+ return;
      169+ }
      170+
      171+ if (Date.now() - startedAt >= BACKEND_READY_TIMEOUT_MS) {
      172+ stop();
      173+ reject(
      174+ new Error(
      175+ `Backend did not start listening on ${LOOPBACK_HOST}:${backendPort} within ${BACKEND_READY_TIMEOUT_MS}ms`,
      176+ ),
      177+ );
      178+ return;
      179+ }
      180+
      181+ void canConnectToBackendPort(backendPort)
      182+ .then((connected) => {
      183+ if (connected) {
      184+ stop();
      185+ resolve();

      P2 Badge Verify HTTP application readiness instead of TCP connectivity

      In a production build where the server entry exists but the web bundle is missing or unreadable, the backend still listens and explicitly serves a 503/404 response, so this TCP-only check resolves successfully and loadURL opens an error page; the updated smoke test also treats that launch as successful. Poll the root URL and require the expected successful application response before creating the window.

      AGENTS.md reference: AGENTS.md:L12-L15

      Useful? React with 👍 / 👎.

Sign in to join this conversation.