fix(server): bundle Bun platform packages so one effect instance serves CORS #9118
main fromrefs/pull/9118/head·opened View on GitHubSince 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.
Note
Bundle @effect/platform-bun and @effect/sql-sqlite-bun instead of externalizing them#
- Removes
@effect/platform-bunand@effect/sql-sqlite-bunfrom CLI external prefixes in cli-external-packages.ts so they are bundled rather than left external. Bun runtime modules (bun,bun:*) remain external. - Adds
findEagerBunRuntimeImportsto walk the emitted chunks' static import graph from entry chunks and report any reachable Bun runtime module imports. - Adds
assertNoEagerBunImportsto the build command in cli.ts, which fails the build withServerCliEagerBunImportErrorif 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:
isExternalCliDependencynow bundles@effect/platform-bunand@effect/sql-sqlite-bun; if any code statically imports Bun runtime modules through these packages, the build will fail viaassertNoEagerBunImportsrather 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:
ServerCliEagerBunImportErroralso reports violations for the bare specifierbun(as exercised by the new scanner test), but its message always says the failure isERR_UNSUPPORTED_ESM_URL_SCHEMEfor abun:URL. A static barebunimport is package resolution and Node reportsERR_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
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
@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 upstreammainat04efa7907with the samemainplus 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-dirper run, server bound to0.0.0.0so the auth policy reportsremote-reachable, and a fresh credential fromnode bin.mjs auth pairing createfor each pairing run.Build Runtime GET /.well-known/t3/environmentwithOriginGET /withaccept-encoding: gzipPOST /api/auth/browser-sessionmainNode Access-Control-Allow-Origin: *Content-Encoding: gzip,Vary: Accept-Encoding200,authenticated: true,Set-CookiepresentmainBun header absent both headers absent 200,authenticated: true,Set-Cookieabsentmain+ PRNode Access-Control-Allow-Origin: *Content-Encoding: gzip,Vary: Accept-Encoding200,authenticated: true,Set-Cookiepresentmain+ PRBun Access-Control-Allow-Origin: *Content-Encoding: gzip,Vary: Accept-Encoding200,authenticated: true,Set-CookiepresentThe
main/Bun pairing response is the #7756 shape exactly:200withauthenticated: trueand noSet-Cookie(Cache-ControlandPragmaare missing from that response too). Replaying the issued cookie againstGET /api/auth/sessionauthenticated 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 annpm packinstall of the published package, and not in-repo regression coverage.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 onmainatbfef973d9at the CORS assertion and passes withbff7b06plus this commit. The commit is based onbff7b06and can be cherry-picked if useful.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.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (3)
.github/workflows/ci.ymlapps/server/package.jsonscripts/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.tsBun 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.tsThe 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.ymlThe 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 directorySuggested reviewers:
juliusmarmingeMerge Risk: ⚪ Minimal · up to
0029eThe 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 name Status Explanation Title check ✅ Passed The title clearly describes the primary change: bundling Bun platform packages so the server uses one Effect instance for CORS handling. Description check ✅ Passed The 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 ✅ Passed Issue #8878requiresAccess-Control-Allow-Originon 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 ✅ Passed The 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 ✅ Passed Docstring 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.Note: GPT-6 on behalf of shivam (@shivamhwp).
The smoke script needs to remove
T3_SERVICE_LAUNCHER_CONTEXTfrom its child environment too. A command started inside a launcher-managed T3 session inherits that variable, and the current filter only removesT3CODE_*andVITE_DEV_SERVER_URL. The standalone Bun child then exits inServiceLauncherClient.resolveStartupwith a version mismatch, or an unavailable IPC channel when versions match, before checking CORS or cookies. ExcludeT3_SERVICE_LAUNCHER_CONTEXTwhen constructingenv; this child has no launcher IPC connection.Confirmed. The launcher spawns its child with that variable set (
apps/server/src/serviceLauncher.ts:406),resolveStartupinapps/server/src/cloud/serviceLauncherClient.ts:119-133fails on it withversion-mismatchoripc-unavailable, andServerEnvironment.ts:194runs that check during everyservestartup, 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. Addingkey !== "T3_SERVICE_LAUNCHER_CONTEXT"to the filter atscripts/server-runtime-smoke.ts:89covers it.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.
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
--versioncheck pass. Also merged current upstream main and regenerated the lockfile, retaining the new platform-node-shared runtime dependency.juliusmarminge added labelsmacroscope-review
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.
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
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).