feat: multi dev branches#4023
Conversation
…ents Dev environments are now branchable. Backfill all existing non-archived DEVELOPMENT runtime environments so isBranchableEnvironment is true. TRI-8726
Extend branch support to DEVELOPMENT environments alongside PREVIEW.
- UpsertBranchRequestBody / branches API accept env "development" as well
as "preview"; the upsert service resolves the parent env by slug
("preview" or "dev") and scopes dev branches per org member.
- checkBranchLimit applies a separate "branchesDev" limit and filters dev
branches by the owning org member.
- API-key and JWT auth resolve branch child environments for both PREVIEW
and DEVELOPMENT parents; findEnvironmentByApiKey returns the dev branch
child when a non-default branch is requested.
- archiveBranch refuses to archive the default dev branch and reports the
branch type so callers can route appropriately.
- Presenters and presence are env/branch aware.
Backwards compatible with the existing CLI: requests that send
env "preview" (or no dev branch) behave exactly as before.
TRI-8726
Add the dev-branches dashboard route and make the branch UI env-aware:
- New env.$envParam.dev-branches route for creating/listing/archiving
development branches, mirroring the preview branches page.
- NewBranchPanel and the branches page take an env ("preview" |
"development") instead of a parent environment id.
- Environment selector, labels, blank-state panels and environment sort
surface dev branches.
- Presence resource route is keyed by env param (renamed from
dev.presence to env.$envParam.presence); branch archive redirects to
the correct (preview vs dev) branches path.
TRI-8726
Let the CLI target a development branch, against the updated server API.
- `trigger dev --branch <branch>` resolves a dev branch (flag or
TRIGGER_DEV_BRANCH, defaulting to "default") via getDevBranch, upserts
it on boot, and sends the x-trigger-branch header on requests.
- Per-branch dev lock files so concurrent dev sessions on different
branches don't evict each other; "default" keeps the dev.lock name.
- New `trigger dev archive` command to archive a dev branch; archive API
calls now pass the env ("preview" | "development").
- Dev output shows the active branch.
TRI-8726
…environments" This reverts commit 7e92114.
🦋 Changeset detectedLatest commit: 28314d3 The changes in this PR will be included in the next version bump. This PR includes changesets to release 27 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
WalkthroughThis pull request implements "dev branches" — the ability to run multiple isolated local dev servers simultaneously, each backed by its own child New shared utilities ( 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 OSV Scanner (2.4.0)Error: ENOENT: no such file or directory, scandir '/inmem/1294/nsjail-773a4f29-3e50-48e4-ae9c-1923dc3982f9/merged/node_modules/.pnpm/ci-info@3.8.0' 🔧 ESLint
ESLint install failed: dependency version conflict. Check your lock file or package.json. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 14
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
apps/webapp/app/routes/api.v1.projects.$projectRef.branches.archive.ts (1)
58-84: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winOrganization-token archive can target the wrong DEVELOPMENT branch when names collide
For
organizationAccessToken+env=development, Line 58 query can return multiple active rows with the samebranchNameacross different members, and Line 91 then archives the first active match arbitrarily.Suggested guard
const environments = await prisma.runtimeEnvironment.findMany({ @@ type: environmentType, branchName: branch, }, }); - if (environments.length === 0) { + if (environments.length === 0) { return json({ error: "Branch not found" }, { status: 404 }); } - const environment = environments.find((env) => env.archivedAt === null); + const activeEnvironments = environments.filter((env) => env.archivedAt === null); + + if ( + authenticationResult.type === "organizationAccessToken" && + environmentType === "DEVELOPMENT" && + activeEnvironments.length > 1 + ) { + return json( + { + error: + "Branch name is ambiguous for development environments. Use a personal access token scoped to the branch owner.", + }, + { status: 409 } + ); + } + + const environment = activeEnvironments[0]; if (!environment) { return json({ error: "Branch already archived" }, { status: 400 }); }Also applies to: 91-94
apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.presence.tsx (1)
15-26: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winScope environment lookup to the route’s organization slug.
Line 15 parses
organizationSlug, but Line 24-Line 26 only scopes byproject.slug. If a user belongs to multiple orgs with the same project/env slugs,findFirstcan resolve the wrong environment and emit incorrect presence.🔧 Suggested fix
- const { organizationSlug, projectParam, envParam } = EnvironmentParamSchema.parse(params); + const { organizationSlug, projectParam, envParam } = EnvironmentParamSchema.parse(params); const environment = await $replica.runtimeEnvironment.findFirst({ where: { type: "DEVELOPMENT", slug: envParam, orgMember: { userId, }, project: { slug: projectParam, + organization: { + slug: organizationSlug, + }, }, }, });apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx (1)
141-153: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winReturn Conform-shaped errors for purchase gating failures.
These branches return
{ ok: false, error }, but the modal reads Conform submissions (intent+ field errors), so users won’t see these errors inline after submit.💡 Proposed fix
- const currentPlan = await getCurrentPlan(project.organizationId); - const purchaseBlockReason = getSelfServePurchaseBlockReason(currentPlan); - if (purchaseBlockReason === "plan_unavailable") { - return json( - { ok: false, error: "Unable to verify billing status. Please try again." } as const, - { status: 503 } - ); - } - if (purchaseBlockReason === "managed_billing") { - return json( - { ok: false, error: "Contact us to request more branches." } as const, - { status: 403 } - ); - } - const submission = parse(formData, { schema: PurchaseSchema }); if (!submission.value || submission.intent !== "submit") { return json(submission); } + + const currentPlan = await getCurrentPlan(project.organizationId); + const purchaseBlockReason = getSelfServePurchaseBlockReason(currentPlan); + if (purchaseBlockReason === "plan_unavailable") { + submission.error.amount = ["Unable to verify billing status. Please try again."]; + return json(submission, { status: 503 }); + } + if (purchaseBlockReason === "managed_billing") { + submission.error.amount = ["Contact us to request more branches."]; + return json(submission, { status: 403 }); + }apps/webapp/app/presenters/OrganizationsPresenter.server.ts (1)
104-113: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winUse the filtered environment list for selection.
project.environmentsis now filtered to the current user's DEVELOPMENT environments, but#getEnvironmentstill receivesfullProject.environments. IfcurrentEnvironmentIdpoints at another user's dev environment, the returnedenvironmentcan bypass the new visibility filter and disagree with the rendered environment list.Suggested fix
const environment = this.#getEnvironment({ user, projectId: fullProject.id, - environments: fullProject.environments, + environments, environmentSlug, });apps/webapp/app/routes/resources.taskruns.$runParam.replay.ts (1)
143-150: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winSelect
parentEnvironmentIdin the synthetic fallback too.The changed filter depends on
parentEnvironmentId, but the fallbackorgProject.environmentsselect does not include it. In that path, PREVIEW rows haveundefined !== null, so root Preview can reappear in the replay environment list.Suggested fix
select: { id: true, type: true, slug: true, branchName: true, + parentEnvironmentId: true, orgMember: { select: { user: true } }, },Also applies to: 250-252
🧹 Nitpick comments (3)
apps/webapp/app/routes/resources.branches.create.tsx (1)
87-87: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueType assertion bypasses type checking.
The
as anyassertion onlastSubmissionbypasses TypeScript's type checking. While this pattern is common with Conform when dealing with fetcher data, consider using a more specific type if possible to maintain type safety.💡 Consider a more specific type
- lastSubmission: lastSubmission as any, + lastSubmission,Then ensure the
useFetcheris properly typed withtypeof action.apps/webapp/app/utils/branches.ts (1)
8-8: 🎯 Functional Correctness | 🔵 TrivialUse
z.coerce.number()instead ofz.preprocess()for consistency with the codebase.The current implementation using
z.preprocess((val) => Number(val), z.number())works correctly—Zod'sz.number()validates and rejectsNaNby default, so non-numeric values result in validation failure and the field becomesundefined(falling back to the defaultpage = 1in the presenter). However, this pattern is inconsistent with the codebase convention. Similar pagination filters throughout the app usez.coerce.number()(e.g.,ScheduleFilters), which is the idiomatic approach in Zod 3.x and clearer in intent.apps/webapp/test/devBranchServices.test.ts (1)
72-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMatch the assertion to the test intent (“without touching the database”).
The test currently verifies only failure. Add a before/after assertion on created DEVELOPMENT children to prove no write occurred.
🧪 Suggested assertion upgrade
postgresTest("rejects an invalid branch name without touching the database", async ({ prisma }) => { const { organization, project, user, orgMember } = await createTestOrgProjectWithMember(prisma); - await createDevRoot(prisma, project.id, organization.id, orgMember.id); + const devRoot = await createDevRoot(prisma, project.id, organization.id, orgMember.id); + const before = await prisma.runtimeEnvironment.count({ + where: { parentEnvironmentId: devRoot.id, type: "DEVELOPMENT" }, + }); const result = await new UpsertBranchService(prisma).call( { type: "userMembership", userId: user.id }, { projectId: project.id, env: "development", branchName: "bad branch name!" } ); expect(result.success).toBe(false); + const after = await prisma.runtimeEnvironment.count({ + where: { parentEnvironmentId: devRoot.id, type: "DEVELOPMENT" }, + }); + expect(after).toBe(before); });
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 12ca8624-ba3b-43e1-b186-bc17f132e009
📒 Files selected for processing (70)
.changeset/dev-branches.mdapps/webapp/app/components/BlankStatePanels.tsxapps/webapp/app/components/DevPresence.tsxapps/webapp/app/components/environments/EnvironmentLabel.tsxapps/webapp/app/components/navigation/EnvironmentSelector.tsxapps/webapp/app/models/member.server.tsapps/webapp/app/models/project.server.tsapps/webapp/app/models/runtimeEnvironment.server.tsapps/webapp/app/presenters/OrganizationsPresenter.server.tsapps/webapp/app/presenters/SelectBestEnvironmentPresenter.server.tsapps/webapp/app/presenters/v3/BranchesPresenter.server.tsapps/webapp/app/presenters/v3/DevPresence.server.tsapps/webapp/app/presenters/v3/EditSchedulePresenter.server.tsapps/webapp/app/presenters/v3/ManageConcurrencyPresenter.server.tsapps/webapp/app/presenters/v3/environmentVariablesEnvironments.server.tsapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam._index/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables.new/route.tsxapps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.tsapps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.tsapps/webapp/app/routes/api.v1.projects.$projectRef.branches.archive.tsapps/webapp/app/routes/api.v1.projects.$projectRef.branches.tsapps/webapp/app/routes/api.v1.projects.$projectRef.environments.tsapps/webapp/app/routes/engine.v1.dev.presence.tsapps/webapp/app/routes/orgs.$organizationSlug.projects.$projectParam.apikeys.tsapps/webapp/app/routes/orgs.$organizationSlug.projects.$projectParam.concurrency.tsapps/webapp/app/routes/orgs.$organizationSlug.projects.$projectParam.environment-variables.tsapps/webapp/app/routes/orgs.$organizationSlug.projects.$projectParam.settings.tsapps/webapp/app/routes/resources.branches.archive.tsxapps/webapp/app/routes/resources.branches.create.tsxapps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.presence.tsxapps/webapp/app/routes/resources.taskruns.$runParam.replay.tsapps/webapp/app/services/apiAuth.server.tsapps/webapp/app/services/archiveBranch.server.tsapps/webapp/app/services/upsertBranch.server.tsapps/webapp/app/utils/branchableEnvironment.tsapps/webapp/app/utils/branches.tsapps/webapp/app/utils/environmentSort.tsapps/webapp/app/utils/pathBuilder.tsapps/webapp/app/v3/environmentVariables/environmentVariablesRepository.server.tsapps/webapp/app/v3/featureFlags.tsapps/webapp/test/branchableEnvironment.test.tsapps/webapp/test/devBranchServices.test.tsapps/webapp/test/devPresenceRecency.test.tsapps/webapp/test/environmentSort.test.tsapps/webapp/test/findEnvironmentByApiKey.test.tsapps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/test/validateGitBranchName.test.tsdocs/deployment/dev-branches.mdxdocs/docs.jsondocs/management/authentication.mdxinternal-packages/database/prisma/schema.prismainternal-packages/rbac/src/fallback.tspackages/cli-v3/src/apiClient.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/commands/preview.tspackages/cli-v3/src/dev/devOutput.tspackages/cli-v3/src/dev/devSession.tspackages/cli-v3/src/dev/devSupervisor.tspackages/cli-v3/src/dev/lock.tspackages/cli-v3/src/mcp/schemas.tspackages/cli-v3/src/utilities/analyze.tspackages/cli-v3/src/utilities/devBranch.tspackages/cli-v3/src/utilities/tempDirectories.tspackages/core/src/v3/apiClient/getBranch.tspackages/core/src/v3/apiClient/index.tspackages/core/src/v3/apiClientManager/index.tspackages/core/src/v3/schemas/api.tspackages/core/src/v3/utils/gitBranch.ts
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/webapp/app/services/apiAuth.server.ts (1)
487-495: 🔒 Security & Privacy | 🔴 Critical | ⚡ Quick winUse
||, not&&, in the API-key environment guard.With
&&this guard only throws when both the slug and the branch mismatch. A slug-only mismatch passes: an API key bound to e.g.slug="prod"(branchName=null) used against aslug="dev"route (resolvedBranch=null) yields("prod" !== "dev") && (null !== null)→true && false→false, so the prod-scoped environment is returned for the dev request. That's a cross-environment authorization bypass. The AI summary itself describes the intended behavior as "throws on (slug mismatch OR branchName mismatch)".🔒 Proposed fix
- if (auth.result.environment.slug !== slug && auth.result.environment.branchName !== resolvedBranch) { + if (auth.result.environment.slug !== slug || auth.result.environment.branchName !== resolvedBranch) {
♻️ Duplicate comments (1)
apps/webapp/app/services/apiAuth.server.ts (1)
539-549: 🔒 Security & Privacy | 🔴 Critical | 🏗️ Heavy liftBranch lookup still unscoped to the requested env/dev owner.
These resolved-branch queries match on
branchName+type in [PREVIEW, DEVELOPMENT]only, without constraining by the routeslugor the dev rootorgMember. A/devrequest can resolve a preview branch of the same name, and the PAT path can resolve another member's dev branch. Same concern applies to the org-token query at lines 605-615.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: e6f017bf-081f-43f4-acb2-9f8323a5c185
📒 Files selected for processing (4)
apps/webapp/app/services/apiAuth.server.tsapps/webapp/app/services/upsertBranch.server.tsapps/webapp/test/rbacFallbackBranch.test.tsinternal-packages/rbac/src/fallback.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/webapp/app/services/upsertBranch.server.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (30)
- GitHub Check: internal / 🧪 Unit Tests: Internal (10, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (3, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (4, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (7, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (11, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (5, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (2, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 10)
- GitHub Check: internal / 🧪 Unit Tests: Internal (12, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (1, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (6, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (9, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (8, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 10)
- GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
- GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
- GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
- GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
- GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
- GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
- GitHub Check: typecheck / typecheck
- GitHub Check: 🛡️ E2E Auth Tests (full)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects insteadImport from
@trigger.dev/sdkwhen writing Trigger.dev tasks. Never use@trigger.dev/sdk/v3or deprecatedclient.defineJob
Files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use zod for validation in packages/core and apps/webapp
Files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use function declarations instead of default exports
**/*.{ts,tsx,js,jsx}: Prefer static imports over dynamic imports. Only use dynamicimport()when circular dependencies cannot be resolved, code splitting is needed for performance, or the module must be loaded conditionally at runtime
Import subpaths only frompackages/core(@trigger.dev/core), never import from the root
Files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
**/*.{test,spec}.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use vitest for all tests in the Trigger.dev repository
Files:
apps/webapp/test/rbacFallbackBranch.test.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)
**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries
Files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
apps/webapp/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)
apps/webapp/**/*.{ts,tsx}: Access environment variables through theenvexport ofenv.server.tsinstead of directly accessingprocess.env
Use subpath exports from@trigger.dev/corepackage instead of importing from the root@trigger.dev/corepathUse named constants for sentinel/placeholder values (e.g.
const UNSET_VALUE = '__unset__') instead of raw string literals scattered across comparisons
Files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.ts
apps/webapp/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)
Do not import
env.server.tsdirectly or indirectly into test files; instead pass environment-dependent values through options/parameters to make code testableFor testable code, never import
env.server.tsin test files. Pass configuration as options instead (e.g.,realtimeClient.server.tstakes config as constructor arg,realtimeClientGlobal.server.tscreates singleton with env config)
Files:
apps/webapp/test/rbacFallbackBranch.test.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.test.{ts,tsx}: Never mock anything in tests - use testcontainers instead
Test files should be placed next to source files (e.g.,MyService.ts->MyService.test.ts)
Files:
apps/webapp/test/rbacFallbackBranch.test.ts
**/*.{js,ts,tsx,jsx,css,json,md}
📄 CodeRabbit inference engine (AGENTS.md)
Use Prettier for code formatting and run
pnpm run formatbefore committing
Files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
**/*.test.{js,ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
**/*.test.{js,ts,tsx}: Test files should live beside the files under test and use descriptivedescribeanditblocks
Use vitest for unit testing
Tests should avoid mocks or stubs and use helpers from@internal/testcontainerswhen Redis or Postgres are needed
Files:
apps/webapp/test/rbacFallbackBranch.test.ts
apps/webapp/**/*.server.ts
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/**/*.server.ts: Never userequest.signalfor detecting client disconnects. UsegetRequestAbortSignal()fromapp/services/httpAsyncStorage.server.tsinstead, which is wired directly to Expressres.on('close')and fires reliably
Access environment variables viaenvexport fromapp/env.server.ts. Never useprocess.envdirectly
Always usefindFirstinstead offindUniquein Prisma queries.findUniquehas an implicit DataLoader that batches concurrent calls and has active bugs even in Prisma 6.x (uppercase UUIDs returning null, composite key SQL correctness issues, 5-10x worse performance).findFirstis never batched and avoids this entire class of issues
Files:
apps/webapp/app/services/apiAuth.server.ts
🧠 Learnings (17)
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
📚 Learning: 2026-05-07T12:25:18.271Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3531
File: apps/webapp/test/sentryTraceContext.server.test.ts:9-47
Timestamp: 2026-05-07T12:25:18.271Z
Learning: In the triggerdotdev/trigger.dev webapp test suite, it is acceptable to leave `createInMemoryTracing()` calls that register a global `NodeTracerProvider` without `afterEach`/`afterAll` teardown. Do not flag this as a test-ordering risk when the code follows the established pattern used across webapp tests (e.g., replication service/benchmark/backfiller tests). This is considered safe because `trace.getActiveSpan()` when called outside a `context.with(...)` block reads `AsyncLocalStorage.getStore()` (undefined when no `run()` scope exists), so it falls back to `ROOT_CONTEXT` with no attached span—regardless of which provider is registered.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.ts
📚 Learning: 2026-05-28T20:02:10.647Z
Learnt from: myftija
Repo: triggerdotdev/trigger.dev PR: 3772
File: apps/webapp/test/findOrCreateBackgroundWorker.test.ts:1-1
Timestamp: 2026-05-28T20:02:10.647Z
Learning: In the triggerdotdev/trigger.dev monorepo, for the `apps/webapp` package use the established convention of storing Vitest tests (unit, integration, and e2e) under `apps/webapp/test/` rather than colocating them next to source files. Do not flag files located in `apps/webapp/test/` as violating any rule that says to colocate tests with source.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.ts
📚 Learning: 2026-05-12T21:04:05.815Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/components/sessions/v1/SessionStatus.tsx:1-3
Timestamp: 2026-05-12T21:04:05.815Z
Learning: In this Remix + TypeScript codebase, do not flag a server/client boundary violation when a file imports only types from a module matching `*.server`.
Specifically, it’s safe to import types using `import type { Foo } from "*.server"` or `import { type Foo } from "*.server"` because TypeScript erases type-only imports at compile time and they emit no JavaScript, so they won’t cross the Remix server/client bundle boundary.
Only raise the boundary concern for value imports (e.g., `import { Foo }` without `type`, or `import Foo`), since those produce JavaScript output.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In the triggerdotdev/trigger.dev repo, the policy “Never mock anything — use testcontainers instead” should only be enforced for integration tests that interact with real external services (e.g., Redis, Postgres) via actual infrastructure. For unit tests that exercise pure in-memory logic (e.g., cache semantics) it is OK to stub collaborators such as `ApiClient` using Vitest (`vi.fn()`) to assert call counts or control behavior. Do not flag `vi.fn()`-based `ApiClient` stubs in unit tests as violations of the testcontainers policy.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.ts
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.tsapps/webapp/app/services/apiAuth.server.tsinternal-packages/rbac/src/fallback.ts
📚 Learning: 2026-06-16T09:19:47.637Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3960
File: apps/webapp/test/prismaInfrastructureErrorCapture.test.ts:0-0
Timestamp: 2026-06-16T09:19:47.637Z
Learning: In this repo’s Vitest setup, `vitest.config.ts` uses `globals: true`, so identifiers like `vi`, `describe`, `it`, and `expect` are available as globals in Vitest test files. During code review, do not flag missing `vi`/`describe`/`it`/`expect` imports as a runtime error or correctness issue when they’re used in `*.test.ts/tsx` or `*.spec.ts/tsx` files. Explicit imports are still preferred for consistency, but they’re not required for runtime behavior.
Applied to files:
apps/webapp/test/rbacFallbackBranch.test.ts
📚 Learning: 2026-03-26T09:02:07.973Z
Learnt from: myftija
Repo: triggerdotdev/trigger.dev PR: 3274
File: apps/webapp/app/services/runsReplicationService.server.ts:922-924
Timestamp: 2026-03-26T09:02:07.973Z
Learning: When parsing Trigger.dev task run annotations in server-side services, keep `TaskRun.annotations` strictly conforming to the `RunAnnotations` schema from `trigger.dev/core/v3`. If the code already uses `RunAnnotations.safeParse` (e.g., in a `#parseAnnotations` helper), treat that as intentional/necessary for atomic, schema-accurate annotation handling. Do not recommend relaxing the annotation payload schema or using a permissive “passthrough” parse path, since the annotations are expected to be written atomically in one operation and should not contain partial/legacy payloads that would require a looser parser.
Applied to files:
apps/webapp/app/services/apiAuth.server.ts
📚 Learning: 2026-05-05T09:38:02.512Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3523
File: apps/webapp/app/routes/api.v3.batches.ts:178-181
Timestamp: 2026-05-05T09:38:02.512Z
Learning: When reviewing code that catches `ServiceValidationError` in `*.server.ts` files, do not blindly forward `error.status` to HTTP responses, because SVEs may be thrown with non-default statuses (e.g., 400/500) and forwarding them can cause client-visible behavioral regressions (e.g., surfacing 500s to clients). Prefer a safe default response status of `error.status ?? 422`, but only after confirming via the reachable call graph that the caught `ServiceValidationError` instances are expected to carry those non-default statuses; otherwise, normalize to `422` to avoid unexpected client-visible 5xx behavior.
Applied to files:
apps/webapp/app/services/apiAuth.server.ts
📚 Learning: 2026-05-01T15:45:05.096Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3499
File: internal-packages/rbac/src/fallback.ts:34-107
Timestamp: 2026-05-01T15:45:05.096Z
Learning: When reviewing triggerdotdev/trigger.dev RBAC auth code, do not treat missing Personal Access Token (PAT) handling inside `authenticateBearer` as a bug. `authenticateBearer` is intentionally scoped to runtime environment API keys and Public JWTs only; PAT auth is handled via the separate PAT route builder (e.g., `createLoaderPATApiRoute`) which calls `authenticateApiRequestWithPersonalAccessToken` directly. Ensure that reviewers compare auth behavior against these distinct architectural paths (OSS fallback and cloud plugin) before flagging an issue.
Applied to files:
internal-packages/rbac/src/fallback.ts
📚 Learning: 2026-05-09T08:07:24.612Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3499
File: internal-packages/rbac/src/fallback.ts:271-277
Timestamp: 2026-05-09T08:07:24.612Z
Learning: When reviewing RBAC/auth code that looks up or validates `PersonalAccessToken` (PAT), do not flag missing `expiresAt`/expiration checks: the PAT model has no `expiresAt` column and is treated as perpetual until manually revoked via `revokedAt`. Only require/enforce expiration logic when the code is dealing with `OrganizationAccessToken`, which does have an `expiresAt` field (and should be checked accordingly).
Applied to files:
internal-packages/rbac/src/fallback.ts
🔇 Additional comments (2)
internal-packages/rbac/src/fallback.ts (1)
195-226: LGTM!apps/webapp/test/rbacFallbackBranch.test.ts (1)
143-171: LGTM!
@trigger.dev/build
trigger.dev
@trigger.dev/core
@trigger.dev/python
@trigger.dev/react-hooks
@trigger.dev/redis-worker
@trigger.dev/rsc
@trigger.dev/schema-to-json
@trigger.dev/sdk
commit: |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/webapp/app/services/apiAuth.server.ts (1)
487-487: 🔒 Security & Privacy | 🔴 CriticalSlug validation is bypassed for non-branch environments — API key accepted for wrong environment slug.
The condition at line 487 uses
&&, which allows the check to pass when the slug differs but bothbranchNamevalues are null. When nox-trigger-branchheader is sent,resolvedBranchisnull(returned bysanitizeBranchName(undefined)), and non-branch environments also havebranchNameasnull. This causesnull !== nullto evaluate tofalse, short-circuiting the check:"prod" !== "main" && null !== null = true && false = false.An API key for one environment will authenticate against a different environment slug as long as the branch header is omitted.
🔒 Proposed fix
- if (auth.result.environment.slug !== slug && auth.result.environment.branchName !== resolvedBranch) { + if ( + auth.result.environment.slug !== slug && + (resolvedBranch === null || auth.result.environment.branchName !== resolvedBranch) + ) {
♻️ Duplicate comments (1)
packages/cli-v3/src/commands/dev.ts (1)
303-313: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winBranch-upsert failure path still calls
process.exit(1), bypassing the lock cleanup added incatch.The cleanup
removeLockFile?.()was added to thestop()handler and thecatchblock, butprocess.exit(1)here (and at Line 327 for!projectClient) terminates the process synchronously before thecatchruns, so the lock file created at Line 273 is not removed — the same stale-lock scenario the earlier fix targeted. Propagating the error instead lets the existingcatchcleanup run.💡 Suggested fix
if (!upsertResult.success) { - logger.error(`Failed to use branch "${branch}": ${upsertResult.error}`); - process.exit(1); + throw new Error(`Failed to use branch "${branch}": ${upsertResult.error}`); }If
createLockFilealready registers a process-exit handler that removes the lock, this may be moot — please confirm:#!/bin/bash fd -t f 'lock.ts' packages/cli-v3/src/dev --exec cat -n {}
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: e4ca92de-41fe-4429-be55-b43f4b033f0f
📒 Files selected for processing (10)
apps/webapp/app/components/navigation/EnvironmentSelector.tsxapps/webapp/app/presenters/v3/BranchesPresenter.server.tsapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsxapps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables.new/route.tsxapps/webapp/app/services/apiAuth.server.tsapps/webapp/test/devBranchServices.test.tsapps/webapp/test/findEnvironmentByApiKey.test.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.tspackages/cli-v3/src/utilities/analyze.ts
🚧 Files skipped from review as they are similar to previous changes (7)
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables.new/route.tsx
- apps/webapp/test/findEnvironmentByApiKey.test.ts
- packages/cli-v3/src/utilities/analyze.ts
- apps/webapp/test/devBranchServices.test.ts
- apps/webapp/app/presenters/v3/BranchesPresenter.server.ts
- apps/webapp/app/components/navigation/EnvironmentSelector.tsx
- apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsx
📜 Review details
⏰ Context from checks skipped due to timeout. (28)
- GitHub Check: internal / 🧪 Unit Tests: Internal (9, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (8, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (3, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (11, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (4, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (7, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (12, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (10, 12)
- GitHub Check: internal / 🧪 Unit Tests: Internal (6, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 10)
- GitHub Check: internal / 🧪 Unit Tests: Internal (1, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 10)
- GitHub Check: internal / 🧪 Unit Tests: Internal (5, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 10)
- GitHub Check: internal / 🧪 Unit Tests: Internal (2, 12)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 10)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 10)
- GitHub Check: typecheck / typecheck
- GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
- GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
- GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
- GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
- GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects insteadImport from
@trigger.dev/sdkwhen writing Trigger.dev tasks. Never use@trigger.dev/sdk/v3or deprecatedclient.defineJob
Files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use zod for validation in packages/core and apps/webapp
Files:
apps/webapp/app/services/apiAuth.server.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use function declarations instead of default exports
**/*.{ts,tsx,js,jsx}: Prefer static imports over dynamic imports. Only use dynamicimport()when circular dependencies cannot be resolved, code splitting is needed for performance, or the module must be loaded conditionally at runtime
Import subpaths only frompackages/core(@trigger.dev/core), never import from the root
Files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)
**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries
Files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
apps/webapp/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)
apps/webapp/**/*.{ts,tsx}: Access environment variables through theenvexport ofenv.server.tsinstead of directly accessingprocess.env
Use subpath exports from@trigger.dev/corepackage instead of importing from the root@trigger.dev/corepathUse named constants for sentinel/placeholder values (e.g.
const UNSET_VALUE = '__unset__') instead of raw string literals scattered across comparisons
Files:
apps/webapp/app/services/apiAuth.server.ts
apps/webapp/**/*.server.ts
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/**/*.server.ts: Never userequest.signalfor detecting client disconnects. UsegetRequestAbortSignal()fromapp/services/httpAsyncStorage.server.tsinstead, which is wired directly to Expressres.on('close')and fires reliably
Access environment variables viaenvexport fromapp/env.server.ts. Never useprocess.envdirectly
Always usefindFirstinstead offindUniquein Prisma queries.findUniquehas an implicit DataLoader that batches concurrent calls and has active bugs even in Prisma 6.x (uppercase UUIDs returning null, composite key SQL correctness issues, 5-10x worse performance).findFirstis never batched and avoids this entire class of issues
Files:
apps/webapp/app/services/apiAuth.server.ts
**/*.{js,ts,tsx,jsx,css,json,md}
📄 CodeRabbit inference engine (AGENTS.md)
Use Prettier for code formatting and run
pnpm run formatbefore committing
Files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
packages/cli-v3/src/commands/**/*
📄 CodeRabbit inference engine (packages/cli-v3/CLAUDE.md)
CLI command definitions should be located in
src/commands/
Files:
packages/cli-v3/src/commands/dev.ts
packages/cli-v3/src/commands/dev.ts
📄 CodeRabbit inference engine (packages/cli-v3/CLAUDE.md)
Implement
dev.tscommand insrc/commands/for local development mode
Files:
packages/cli-v3/src/commands/dev.ts
packages/cli-v3/src/dev/**/*
📄 CodeRabbit inference engine (packages/cli-v3/CLAUDE.md)
Dev mode code should be located in
src/dev/and runs tasks locally in the user's Node.js process without containers
Files:
packages/cli-v3/src/dev/lock.ts
🧠 Learnings (12)
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).
Applied to files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.
Applied to files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.
Applied to files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.
Applied to files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.
Applied to files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).
Applied to files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.
Applied to files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
📚 Learning: 2026-03-26T09:02:07.973Z
Learnt from: myftija
Repo: triggerdotdev/trigger.dev PR: 3274
File: apps/webapp/app/services/runsReplicationService.server.ts:922-924
Timestamp: 2026-03-26T09:02:07.973Z
Learning: When parsing Trigger.dev task run annotations in server-side services, keep `TaskRun.annotations` strictly conforming to the `RunAnnotations` schema from `trigger.dev/core/v3`. If the code already uses `RunAnnotations.safeParse` (e.g., in a `#parseAnnotations` helper), treat that as intentional/necessary for atomic, schema-accurate annotation handling. Do not recommend relaxing the annotation payload schema or using a permissive “passthrough” parse path, since the annotations are expected to be written atomically in one operation and should not contain partial/legacy payloads that would require a looser parser.
Applied to files:
apps/webapp/app/services/apiAuth.server.ts
📚 Learning: 2026-05-05T09:38:02.512Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3523
File: apps/webapp/app/routes/api.v3.batches.ts:178-181
Timestamp: 2026-05-05T09:38:02.512Z
Learning: When reviewing code that catches `ServiceValidationError` in `*.server.ts` files, do not blindly forward `error.status` to HTTP responses, because SVEs may be thrown with non-default statuses (e.g., 400/500) and forwarding them can cause client-visible behavioral regressions (e.g., surfacing 500s to clients). Prefer a safe default response status of `error.status ?? 422`, but only after confirming via the reachable call graph that the caught `ServiceValidationError` instances are expected to carry those non-default statuses; otherwise, normalize to `422` to avoid unexpected client-visible 5xx behavior.
Applied to files:
apps/webapp/app/services/apiAuth.server.ts
📚 Learning: 2026-05-12T21:04:05.815Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/components/sessions/v1/SessionStatus.tsx:1-3
Timestamp: 2026-05-12T21:04:05.815Z
Learning: In this Remix + TypeScript codebase, do not flag a server/client boundary violation when a file imports only types from a module matching `*.server`.
Specifically, it’s safe to import types using `import type { Foo } from "*.server"` or `import { type Foo } from "*.server"` because TypeScript erases type-only imports at compile time and they emit no JavaScript, so they won’t cross the Remix server/client bundle boundary.
Only raise the boundary concern for value imports (e.g., `import { Foo }` without `type`, or `import Foo`), since those produce JavaScript output.
Applied to files:
apps/webapp/app/services/apiAuth.server.ts
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.
Applied to files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.
Applied to files:
apps/webapp/app/services/apiAuth.server.tspackages/cli-v3/src/commands/dev.tspackages/cli-v3/src/dev/lock.ts
🪛 ast-grep (0.44.0)
packages/cli-v3/src/dev/lock.ts
[warning] 20-20: Avoid SHA1 security protocol
Context: createHash("sha1")
Note: [CWE-327] Use of a Broken or Risky Cryptographic Algorithm (SHA-1).
(avoid-crypto-sha1-typescript)
[warning] 20-20: Do not use weak hash functions (MD5/SHA1)
Context: createHash("sha1")
Note: [CWE-328] Use of Weak Hash.
(insecure-hash-typescript)
🔇 Additional comments (6)
apps/webapp/app/services/apiAuth.server.ts (4)
314-340: LGTM!Also applies to: 353-362
463-469: LGTM!
516-557: LGTM!
597-621: LGTM!packages/cli-v3/src/commands/dev.ts (1)
244-244: LGTM!Also applies to: 270-273, 352-359
packages/cli-v3/src/dev/lock.ts (1)
18-23: LGTM!
Closes this feature request: https://triggerdev.featurebase.app/p/isolated-dev-sessions-for-multiple-local-trigger-dev-instances
Feature notes:
trigger devworks as beforetrigger dev --branch my-branchto create a new branch and run against it.trigger dev archive --branch my-branchto archive (or in webapp).Implementation details:
isBranchableEnvironmentcolumn is ignored for dev branches, we useparentEnvironmentId IS NULLinstead.x-trigger-branchoverloaded for preview and dev branchesTRIGGER_DEV_BRANCHenv var available locally.TRIGGER_PREVIEW_BRANCHoverloaded for child runs.Rollout
Notes
api.v1.projects.$projectRef.environments.tswill returnisBranchableEnvironment: truefor all dev environments.