Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): bundle Bun platform packages so one effect instance serves CORS #9118

Closedlnieuwenhuis(GitHub profile, opens in a new tab)wants to merge 5 commits intomain fromrefs/pull/9118/headopened View on GitHub

Since the CLI bundling change in #5877, dist/bin.mjs inlines effect but kept @effect/platform-bun and @effect/sql-sqlite-bun external. A Bun-hosted server therefore loaded a second effect from node_modules. Effect attaches CORS, compression, and auth headers to real responses through a pre-response handler stored in a module-level WeakMap, so the bundled copy wrote handlers the platform server's copy never read. OPTIONS preflight still worked because it is answered inline, but every actual response lost Access-Control-Allow-Origin and gzip, which is why the desktop app could not connect to a remote Bun-run environment on a separate origin.

The fix externalizes only Bun's own module namespace (bun, bun:*) and bundles both platform packages, so one effect graph serves the whole server. The two packages move to devDependencies. Because correctness now depends on rolldown keeping bun:sqlite in a chunk reached only through import(), the server build gains a post-build check that walks the emitted chunk graph from both entries along static edges and fails if any eagerly loaded chunk imports a Bun module. Rolldown only warns on that merge and exits 0, so the check reads the artifact instead of trusting the bundler.

Verification: in the built artifact the single pre-response-handler WeakMap lives in the shared chunk that both bin.mjs and the BunHttpServer chunk import, and no bare @effect/*-bun runtime import remains. A probe bundled with the repo's own build predicates and run under Bun showed Access-Control-Allow-Origin: * and Content-Encoding: gzip restored on GET, and the real CLI under Node shows no regression. Bundle size grows by about 0.5%. The full server cannot run under Bun on Windows (the Bun PTY adapter is unsupported there), and the freshly built CLI has now passed the Linux Bun runtime smoke described below. A negative control confirmed the new build check rejects a bundle where bun:sqlite is hoisted into bin.mjs, which otherwise fails at load under Node.

Closes #8878

Claude Fable 5.1 via Claude Code

Fresh verification (2026-09-06): built the server/web artifacts and passed the isolated Linux Bun 1.4.0 runtime smoke for CORS, gzip body equivalence, pairing Set-Cookie, and authenticated cookie replay. The smoke is now wired into CI. 20 focused packaging tests passed. Published-package installation was not exercised; Windows Bun startup still has the existing unsupported PTY limitation.


Note

Medium Risk Changes core server CLI bundling and build-time validation; a mistaken static import of Bun adapters would fail builds or break Node entrypoints, but the new eager-import scan is meant to catch that before release.

Overview Fixes missing CORS, gzip, and auth on Bun-hosted servers when the desktop app talks to a remote environment on another origin. External @effect/platform-bun and @effect/sql-sqlite-bun had been loading a second effect beside the bundle, so pre-response handlers (WeakMap-keyed) never applied to real responses.

Bundling policy in cli-external-packages.ts now inlines those two packages and only keeps bun / bun:* external. They move from dependencies to devDependencies in apps/server/package.json. Inlining pulls bun:sqlite into the artifact, which must stay behind dynamic import() so node bin.mjs still works.

A post-bundle guard runs in the server CLI build step: findEagerBunRuntimeImports walks static edges from bin.mjs and service-launcher.mjs and fails with ServerCliEagerBunImportError if any eagerly loaded chunk references a Bun runtime module (rolldown only warns). Tests cover the scanner and updated bundle expectations; desktop self-containment comments point at this check for the Bun adapters.

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

Note

Bundle @effect/platform-bun and @effect/sql-sqlite-bun instead of externalizing them

  • Removes @effect/platform-bun and @effect/sql-sqlite-bun from CLI external prefixes in cli-external-packages.ts so they are bundled rather than left external. Bun runtime modules (bun, bun:*) remain external.
  • Adds findEagerBunRuntimeImports to walk the emitted chunks' static import graph from entry chunks and report any reachable Bun runtime module imports.
  • Adds assertNoEagerBunImports to the build command in cli.ts, which fails the build with ServerCliEagerBunImportError if any eagerly loaded chunk imports a Bun runtime module.
  • Updates tests in cli-external-packages.test.ts to expect the two adapter packages bundled and to cover the new eager-import detection logic.
  • Risk: isExternalCliDependency now bundles @effect/platform-bun and @effect/sql-sqlite-bun; if any code statically imports Bun runtime modules through these packages, the build will fail via assertNoEagerBunImports rather than silently producing a broken bundle.
📊 Macroscope summarized bff7b06. 4 files reviewed, 1 issue evaluated, 1 issue filtered, 0 comments posted

🗂️ Filtered Issues

apps/server/scripts/cliErrors.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 80: ServerCliEagerBunImportError also reports violations for the bare specifier bun (as exercised by the new scanner test), but its message always says the failure is ERR_UNSUPPORTED_ESM_URL_SCHEME for a bun: URL. A static bare bun import is package resolution and Node reports ERR_MODULE_NOT_FOUND, so this build failure gives an incorrect diagnosis for one of the explicitly detected violation types. [ Out of scope (post-validation triage) ]

Summary by CodeRabbit

  • Bug Fixes

    • Improved server runtime compatibility across Node and Bun environments.
    • Prevented incompatible Bun-only modules from being loaded during server startup.
    • Improved server packaging and runtime module resolution.
    • Added validation to detect unsafe runtime imports before packaging completes.
  • Tests

    • Added automated server startup checks covering readiness, CORS, compression, authentication, error reporting, graceful shutdown, and temporary-file cleanup.
    • Expanded validation for session handling and browser-session pairing.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

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

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR changes the production server’s Node/Bun bundling boundary and adds build-time graph validation plus a substantial Bun runtime smoke test. The new smoke script also suppresses two file-level static-analysis diagnostics, so the change warrants human review.

      Notes:

      • Diff unchanged. Approvability was decided on eligibility alone.
      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. @juliusmarminge re your note on #8878 about browser-session cookie emission: here is a manual Linux check of this branch that includes it.

      Repo-built apps/server/dist, comparing upstream main at 04efa7907 with the same main plus this PR merged on top (635625d42), so the only source difference is this change. Bun 1.4.0 and Node v22.23.2, fresh --base-dir per run, server bound to 0.0.0.0 so the auth policy reports remote-reachable, and a fresh credential from node bin.mjs auth pairing create for each pairing run.

      BuildRuntimeGET /.well-known/t3/environment with OriginGET / with accept-encoding: gzipPOST /api/auth/browser-session
      mainNodeAccess-Control-Allow-Origin: *Content-Encoding: gzip, Vary: Accept-Encoding200, authenticated: true, Set-Cookie present
      mainBunheader absentboth headers absent200, authenticated: true, Set-Cookie absent
      main + PRNodeAccess-Control-Allow-Origin: *Content-Encoding: gzip, Vary: Accept-Encoding200, authenticated: true, Set-Cookie present
      main + PRBunAccess-Control-Allow-Origin: *Content-Encoding: gzip, Vary: Accept-Encoding200, authenticated: true, Set-Cookie present

      The main/Bun pairing response is the #7756 shape exactly: 200 with authenticated: true and no Set-Cookie (Cache-Control and Pragma are missing from that response too). Replaying the issued cookie against GET /api/auth/session authenticated in every run that had one. The Bun cells were repeated three times each with identical headers.

      This is symptom-level evidence from the repo build with workspace node_modules, not an npm pack install of the published package, and not in-repo regression coverage.

    4. A Bun runtime smoke for the browser-session cookie case discussed in #8878 is available here: https://github.com/derektrimm/t3code/commit/a90d0ef1186f996cb19239c92f818be4ab29a1d5. It runs the built CLI under Bun 1.4.0 in the Check job and asserts CORS, gzip, and the pairing Set-Cookie. The smoke fails on main at bfef973d9 at the CORS assertion and passes with bff7b06 plus this commit. The commit is based on bff7b06 and can be cherry-picked if useful.

    5. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review Change StackReview Change Stack

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: Path: .coderabbit.yaml

      Review profile: CHILL

      Plan: Advanced

      Run ID: 6bfac720-74ab-41f8-bade-45533101c6ce

      📥 Commits

      Reviewing files that changed from the base of the PR and between 87fabb0e5f47728a736f600083d48192ec808eeb and 0029e7468dbb85622abc8f19152a52fc0b363f43.

      ⛔ Files ignored due to path filters (1)
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (3)
      • .github/workflows/ci.yml
      • apps/server/package.json
      • scripts/server-runtime-smoke.ts

      Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


      📝 Walkthrough

      Walkthrough

      The build bundles Bun adapter packages, externalizes Bun runtime modules, validates generated chunks, and runs a Bun server smoke test in CI. The smoke test covers CORS, compression, sessions, authentication, errors, termination, and cleanup.

      Changes

      Bun runtime validation

      Layer / File(s)Summary
      Bun module externalization and graph scanning
      scripts/lib/cli-external-packages.ts, scripts/lib/cli-external-packages.test.ts
      Bun runtime specifiers are externalized directly. Bun adapter packages are bundled. Static chunk traversal detects eagerly reachable Bun imports and ignores dynamic imports.
      Server build validation and dependency wiring
      apps/server/scripts/cli.ts, apps/server/scripts/cliErrors.ts, apps/server/package.json, scripts/build-desktop-artifact.ts
      The server build validates required entry chunks and rejects eager Bun imports with ServerCliEagerBunImportError. Bun adapter packages move to development dependencies.
      Bun runtime smoke test and CI execution
      scripts/server-runtime-smoke.ts, .github/workflows/ci.yml
      The smoke test starts the built server and checks CORS, compression, sessions, authentication, errors, termination, and cleanup. CI runs it under Bun 1.4.0.

      Priority: ⬆️ High

      Estimated code review effort: 4 (Complex) | ~45 minutes

      Change: Bug fix · Severity of issue fixed: Medium

      Sequence Diagram(s)

      sequenceDiagram
        participant CI
        participant Bun
        participant BuiltServer
        participant HTTPClient
        CI->>Bun: Start server-runtime-smoke.ts
        Bun->>BuiltServer: Launch built server
        BuiltServer-->>Bun: Emit startup token
        Bun-->>HTTPClient: Serve HTTP requests
        HTTPClient->>BuiltServer: Check CORS, sessions, compression, and authentication
        BuiltServer-->>HTTPClient: Return response headers and bodies
        Bun->>BuiltServer: Terminate process
        Bun->>Bun: Remove temporary directory

      Suggested reviewers: juliusmarminge

      Merge Risk: ⚪ Minimal · up to 0029e

      The Bun build and runtime smoke coverage validate the restored server behavior without identifying an outstanding merge-blocking issue.

      🚥 Pre-merge checks | ✅ 5
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly describes the primary change: bundling Bun platform packages so the server uses one Effect instance for CORS handling.
      Description check✅ PassedThe description clearly explains the problem, implementation, verification, risks, limitations, and linked issue. It omits the explicit checklist and UI section, but these omissions are non-critical b…
      Linked Issues check✅ PassedIssue #8878 requires Access-Control-Allow-Origin on actual responses for Bun-hosted servers. The PR bundles the Bun Effect adapters into the server CLI and keeps Bun runtime modules external. The ru…
      Out of Scope Changes check✅ PassedThe CLI bundling changes, eager Bun-import validation, dependency updates, packaging tests, CI smoke test, and launcher-context filtering support reliable Bun server execution and verification for iss…
      Docstring Coverage✅ PassedDocstring coverage is 80.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 6 files. (2 skipped: 2 u…
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      Comment `@coderabbitai help` to get the list of available commands.
    6. Note: GPT-6 on behalf of shivam (@shivamhwp).

      The smoke script needs to remove T3_SERVICE_LAUNCHER_CONTEXT from its child environment too. A command started inside a launcher-managed T3 session inherits that variable, and the current filter only removes T3CODE_* and VITE_DEV_SERVER_URL. The standalone Bun child then exits in ServiceLauncherClient.resolveStartup with a version mismatch, or an unavailable IPC channel when versions match, before checking CORS or cookies. Exclude T3_SERVICE_LAUNCHER_CONTEXT when constructing env; this child has no launcher IPC connection.

    7. Confirmed. The launcher spawns its child with that variable set (apps/server/src/serviceLauncher.ts:406), resolveStartup in apps/server/src/cloud/serviceLauncherClient.ts:119-133 fails on it with version-mismatch or ipc-unavailable, and ServerEnvironment.ts:194 runs that check during every serve startup, so a smoke started from inside a launcher-managed session dies before it listens. CI runners never carry the variable, which is why the Check job passes. Adding key !== "T3_SERVICE_LAUNCHER_CONTEXT" to the filter at scripts/server-runtime-smoke.ts:89 covers it.

    8. Bugbot is paused — on-demand spend limit reached

      Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

      A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

    9. Fixed in 0029e7468. The standalone smoke child now excludes T3_SERVICE_LAUNCHER_CONTEXT. CI runs the existing Bun smoke with a synthetic inherited launcher context so this cannot silently regress on runners without launcher state.

      Verified against the rebuilt server with Bun 1.4.0: both a mismatched child version and the current version without IPC pass CORS, gzip, pairing-cookie issuance, and authenticated cookie replay. Removing the filter reproduces the reported launcher-version startup failure. The 20 packaging tests, scripts/server typechecks, targeted lint, and Node bundle --version check pass. Also merged current upstream main and regenerated the lockfile, retaining the new platform-node-shared runtime dependency.

    10. juliusmarminge added labelsmacroscope-review

    11. Note

      🤖 GPT-6 Astra responding on behalf of Theo

      We're closing this as part of a cleanup of stale PRs. Thank you for the time and care you put into this contribution.

      A local merge check found conflicts in 7 files against the current target branch. The latest implementation commit is from 2026-09-12, and there has been no contribution update in over a week.

      At this point, regenerating a focused patch against the current intended base would be easier to review and maintain than updating this PR. We appreciate the work and will keep this thread as a reference. If you revisit it, please check the current direction with us and link the fresh PR back here.

Sign in to join this conversation.