Skip to content

feat: multi dev branches#4023

Draft
carderne wants to merge 29 commits into
mainfrom
feature/tri-8726-development-branches-multi-branch-dev-environments
Draft

feat: multi dev branches#4023
carderne wants to merge 29 commits into
mainfrom
feature/tri-8726-development-branches-multi-branch-dev-environments

Conversation

@carderne

@carderne carderne commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Closes this feature request: https://triggerdev.featurebase.app/p/isolated-dev-sessions-for-multiple-local-trigger-dev-instances

Feature notes:

  • CLI trigger dev works as before
  • trigger dev --branch my-branch to create a new branch and run against it.
  • trigger dev archive --branch my-branch to archive (or in webapp).
  • New webapp page to manage and archive dev branches, currently feature flagged.

Implementation details:

  • No changes to data model, no backfill. isBranchableEnvironment column is ignored for dev branches, we use parentEnvironmentId IS NULL instead.
  • x-trigger-branch overloaded for preview and dev branches
  • New TRIGGER_DEV_BRANCH env var available locally. TRIGGER_PREVIEW_BRANCH overloaded for child runs.
  • Lots of new glue code to sanitise the branch checks.

Rollout

  • Deploy webapp/API changes (all backwards compatible)
  • Manual tests on some orgs
  • Deploy docs, release CLI, flip feature flag for webapp feature

Notes

  • api.v1.projects.$projectRef.environments.ts will return isBranchableEnvironment: true for all dev environments.

carderne added 23 commits June 23, 2026 09:30
…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
@changeset-bot

changeset-bot Bot commented Jun 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 54f96ed

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 27 packages
Name Type
trigger.dev Patch
@trigger.dev/core Patch
@trigger.dev/build Patch
@trigger.dev/plugins Patch
@trigger.dev/python Patch
@trigger.dev/redis-worker Patch
@trigger.dev/schema-to-json Patch
@trigger.dev/sdk Patch
@internal/cache Patch
@internal/clickhouse Patch
@internal/llm-model-catalog Patch
@trigger.dev/rbac Patch
@internal/redis Patch
@internal/replication Patch
@internal/run-engine Patch
@internal/run-store Patch
@internal/schedule-engine Patch
@trigger.dev/sso Patch
@internal/testcontainers Patch
@internal/tracing Patch
@internal/tsql Patch
@internal/zod-worker Patch
@internal/sdk-compat-tests Patch
@trigger.dev/react-hooks Patch
@trigger.dev/rsc Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch

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

@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This pull request implements "dev branches" — the ability to run multiple isolated local dev servers simultaneously, each backed by its own child DEVELOPMENT runtime environment with separate runs and concurrency control.

New shared utilities (DEFAULT_DEV_BRANCH, isDefaultDevBranch, isBranchableEnvironment, rootEnvironmentWhere, BranchableEnvironmentToken) establish the vocabulary. API authentication is extended so x-trigger-branch resolves to either PREVIEW or DEVELOPMENT child environments, collapsing the "default" sentinel to the root. Redis-backed DevPresence gains batch presence checking (isConnectedMany) and per-user/project recency tracking via setConnected (ZSET with debounce/trimming) and getRecentBranchIds. UpsertBranchService and ArchiveBranchService are updated to find parents structurally via rootEnvironmentWhere and enforce per-user scoping for development branches. A new Remix route (dev-branches) renders the dev-branch management page with table, filters, and pagination, while a shared resource route (resources.branches.create) handles branch creation for both preview and development. The CLI dev command gains a --branch option that scopes lockfiles, temp directories, watchdog state, and API headers per branch, plus a dev archive subcommand. Documentation for x-trigger-branch is updated and a new deployment/dev-branches.mdx page is added with CLI examples and per-plan limits.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.48% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description provides feature notes, implementation details, rollout plan, and specific notes, but is missing some template sections: testing steps, changelog, screenshots, and the required checklist. Complete the description by adding testing steps, a changelog entry, the contributor checklist, and any relevant screenshots to fully align with the template.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: multi dev branches' clearly and concisely describes the main feature addition - multi-branch development environments.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/tri-8726-development-branches-multi-branch-dev-environments

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

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Organization-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 same branchName across 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 win

Scope environment lookup to the route’s organization slug.

Line 15 parses organizationSlug, but Line 24-Line 26 only scopes by project.slug. If a user belongs to multiple orgs with the same project/env slugs, findFirst can 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 win

Return 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 win

Use the filtered environment list for selection.

project.environments is now filtered to the current user's DEVELOPMENT environments, but #getEnvironment still receives fullProject.environments. If currentEnvironmentId points at another user's dev environment, the returned environment can 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 win

Select parentEnvironmentId in the synthetic fallback too.

The changed filter depends on parentEnvironmentId, but the fallback orgProject.environments select does not include it. In that path, PREVIEW rows have undefined !== 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 value

Type assertion bypasses type checking.

The as any assertion on lastSubmission bypasses 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 useFetcher is properly typed with typeof action.

apps/webapp/app/utils/branches.ts (1)

8-8: 🎯 Functional Correctness | 🔵 Trivial

Use z.coerce.number() instead of z.preprocess() for consistency with the codebase.

The current implementation using z.preprocess((val) => Number(val), z.number()) works correctly—Zod's z.number() validates and rejects NaN by default, so non-numeric values result in validation failure and the field becomes undefined (falling back to the default page = 1 in the presenter). However, this pattern is inconsistent with the codebase convention. Similar pagination filters throughout the app use z.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 win

Match 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5667461 and 7b8bdc2.

📒 Files selected for processing (70)
  • .changeset/dev-branches.md
  • apps/webapp/app/components/BlankStatePanels.tsx
  • apps/webapp/app/components/DevPresence.tsx
  • apps/webapp/app/components/environments/EnvironmentLabel.tsx
  • apps/webapp/app/components/navigation/EnvironmentSelector.tsx
  • apps/webapp/app/models/member.server.ts
  • apps/webapp/app/models/project.server.ts
  • apps/webapp/app/models/runtimeEnvironment.server.ts
  • apps/webapp/app/presenters/OrganizationsPresenter.server.ts
  • apps/webapp/app/presenters/SelectBestEnvironmentPresenter.server.ts
  • apps/webapp/app/presenters/v3/BranchesPresenter.server.ts
  • apps/webapp/app/presenters/v3/DevPresence.server.ts
  • apps/webapp/app/presenters/v3/EditSchedulePresenter.server.ts
  • apps/webapp/app/presenters/v3/ManageConcurrencyPresenter.server.ts
  • apps/webapp/app/presenters/v3/environmentVariablesEnvironments.server.ts
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam._index/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dev-branches/route.tsx
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables.new/route.tsx
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.jwt.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.$env.workers.$tagName.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.branches.archive.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.branches.ts
  • apps/webapp/app/routes/api.v1.projects.$projectRef.environments.ts
  • apps/webapp/app/routes/engine.v1.dev.presence.ts
  • apps/webapp/app/routes/orgs.$organizationSlug.projects.$projectParam.apikeys.ts
  • apps/webapp/app/routes/orgs.$organizationSlug.projects.$projectParam.concurrency.ts
  • apps/webapp/app/routes/orgs.$organizationSlug.projects.$projectParam.environment-variables.ts
  • apps/webapp/app/routes/orgs.$organizationSlug.projects.$projectParam.settings.ts
  • apps/webapp/app/routes/resources.branches.archive.tsx
  • apps/webapp/app/routes/resources.branches.create.tsx
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.presence.tsx
  • apps/webapp/app/routes/resources.taskruns.$runParam.replay.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • apps/webapp/app/services/archiveBranch.server.ts
  • apps/webapp/app/services/upsertBranch.server.ts
  • apps/webapp/app/utils/branchableEnvironment.ts
  • apps/webapp/app/utils/branches.ts
  • apps/webapp/app/utils/environmentSort.ts
  • apps/webapp/app/utils/pathBuilder.ts
  • apps/webapp/app/v3/environmentVariables/environmentVariablesRepository.server.ts
  • apps/webapp/app/v3/featureFlags.ts
  • apps/webapp/test/branchableEnvironment.test.ts
  • apps/webapp/test/devBranchServices.test.ts
  • apps/webapp/test/devPresenceRecency.test.ts
  • apps/webapp/test/environmentSort.test.ts
  • apps/webapp/test/findEnvironmentByApiKey.test.ts
  • apps/webapp/test/rbacFallbackBranch.test.ts
  • apps/webapp/test/validateGitBranchName.test.ts
  • docs/deployment/dev-branches.mdx
  • docs/docs.json
  • docs/management/authentication.mdx
  • internal-packages/database/prisma/schema.prisma
  • internal-packages/rbac/src/fallback.ts
  • packages/cli-v3/src/apiClient.ts
  • packages/cli-v3/src/commands/dev.ts
  • packages/cli-v3/src/commands/preview.ts
  • packages/cli-v3/src/dev/devOutput.ts
  • packages/cli-v3/src/dev/devSession.ts
  • packages/cli-v3/src/dev/devSupervisor.ts
  • packages/cli-v3/src/dev/lock.ts
  • packages/cli-v3/src/mcp/schemas.ts
  • packages/cli-v3/src/utilities/analyze.ts
  • packages/cli-v3/src/utilities/devBranch.ts
  • packages/cli-v3/src/utilities/tempDirectories.ts
  • packages/core/src/v3/apiClient/getBranch.ts
  • packages/core/src/v3/apiClient/index.ts
  • packages/core/src/v3/apiClientManager/index.ts
  • packages/core/src/v3/schemas/api.ts
  • packages/core/src/v3/utils/gitBranch.ts

Comment thread apps/webapp/app/components/navigation/EnvironmentSelector.tsx Outdated
Comment thread apps/webapp/app/presenters/v3/BranchesPresenter.server.ts
Comment thread packages/cli-v3/src/commands/dev.ts
Comment thread packages/cli-v3/src/commands/dev.ts Outdated
Comment thread packages/cli-v3/src/dev/lock.ts
Comment thread packages/cli-v3/src/utilities/analyze.ts Outdated
Comment thread packages/cli-v3/src/utilities/devBranch.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Use ||, 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 a slug="dev" route (resolvedBranch=null) yields ("prod" !== "dev") && (null !== null)true && falsefalse, 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 lift

Branch 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 route slug or the dev root orgMember. A /dev request 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b8bdc2 and d53fcce.

📒 Files selected for processing (4)
  • apps/webapp/app/services/apiAuth.server.ts
  • apps/webapp/app/services/upsertBranch.server.ts
  • apps/webapp/test/rbacFallbackBranch.test.ts
  • internal-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 instead

Import from @trigger.dev/sdk when writing Trigger.dev tasks. Never use @trigger.dev/sdk/v3 or deprecated client.defineJob

Files:

  • apps/webapp/test/rbacFallbackBranch.test.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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.ts
  • 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 dynamic import() when circular dependencies cannot be resolved, code splitting is needed for performance, or the module must be loaded conditionally at runtime
Import subpaths only from packages/core (@trigger.dev/core), never import from the root

Files:

  • apps/webapp/test/rbacFallbackBranch.test.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-packages/rbac/src/fallback.ts
apps/webapp/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

apps/webapp/**/*.{ts,tsx}: Access environment variables through the env export of env.server.ts instead of directly accessing process.env
Use subpath exports from @trigger.dev/core package instead of importing from the root @trigger.dev/core path

Use 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.ts
  • apps/webapp/app/services/apiAuth.server.ts
apps/webapp/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)

Do not import env.server.ts directly or indirectly into test files; instead pass environment-dependent values through options/parameters to make code testable

For testable code, never import env.server.ts in test files. Pass configuration as options instead (e.g., realtimeClient.server.ts takes config as constructor arg, realtimeClientGlobal.server.ts creates 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 format before committing

Files:

  • apps/webapp/test/rbacFallbackBranch.test.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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 descriptive describe and it blocks
Use vitest for unit testing
Tests should avoid mocks or stubs and use helpers from @internal/testcontainers when 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 use request.signal for detecting client disconnects. Use getRequestAbortSignal() from app/services/httpAsyncStorage.server.ts instead, which is wired directly to Express res.on('close') and fires reliably
Access environment variables via env export from app/env.server.ts. Never use process.env directly
Always use findFirst instead of findUnique in Prisma queries. findUnique has 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). findFirst is 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.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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.ts
  • apps/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.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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.ts
  • apps/webapp/app/services/apiAuth.server.ts
  • internal-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!

@pkg-pr-new

pkg-pr-new Bot commented Jun 23, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trigger.dev/build

npm i https://pkg.pr.new/@trigger.dev/build@54f96ed

trigger.dev

npm i https://pkg.pr.new/trigger.dev@54f96ed

@trigger.dev/core

npm i https://pkg.pr.new/@trigger.dev/core@54f96ed

@trigger.dev/python

npm i https://pkg.pr.new/@trigger.dev/python@54f96ed

@trigger.dev/react-hooks

npm i https://pkg.pr.new/@trigger.dev/react-hooks@54f96ed

@trigger.dev/redis-worker

npm i https://pkg.pr.new/@trigger.dev/redis-worker@54f96ed

@trigger.dev/rsc

npm i https://pkg.pr.new/@trigger.dev/rsc@54f96ed

@trigger.dev/schema-to-json

npm i https://pkg.pr.new/@trigger.dev/schema-to-json@54f96ed

@trigger.dev/sdk

npm i https://pkg.pr.new/@trigger.dev/sdk@54f96ed

commit: 54f96ed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant