Skip to content

Conversation

@jescalan
Copy link
Contributor

@jescalan jescalan commented Nov 3, 2025

This pull request contains changes generated by a Cursor Cloud Agent

Open in Cursor Open in Web

Summary by CodeRabbit

  • Bug Fixes
    • Improved validation when selecting an active organization: providing an invalid organization slug now returns a clear, specific error indicating the organization wasn't found or the user isn't a member, preventing silent failures and improving feedback during organization switches.

@cursor
Copy link

cursor bot commented Nov 3, 2025

Cursor Agent can help with this pull request. Just @cursor in comments and I'll start working on changes in this branch.
Learn more about Cursor Agents

@changeset-bot
Copy link

changeset-bot bot commented Nov 3, 2025

⚠️ No Changeset found

Latest commit: 022593d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel
Copy link

vercel bot commented Nov 3, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Nov 3, 2025 4:24pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 3, 2025

Walkthrough

Adds explicit validation in Clerk.setActive to throw a ClerkRuntimeError when an organization slug is provided but no matching organization exists for the user. Also adds test coverage for the invalid-slug rejection (with a duplicate test instance added).

Changes

Cohort / File(s) Summary
Core logic — setActive validation
packages/clerk-js/src/core/clerk.ts
Inserts a validation path in Clerk.setActive that checks for an explicitly provided organization slug and throws a ClerkRuntimeError with a descriptive message and specific error code if no matching organization is found. Executes before existing forceOrganizationSelection and last-active updates.
Tests — invalid slug behavior
packages/clerk-js/src/core/__tests__/clerk.test.ts
Adds a test asserting setActive rejects with the exact error message when given an invalid organization slug. The invalid-slug test appears twice (duplicated) within the same describe block.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant Clerk.setActive
    participant OrgStore
    participant Error

    Caller->>Clerk.setActive: setActive({ organization: "invalid-org-slug" })
    Clerk.setActive->>OrgStore: lookup organization by slug
    OrgStore-->>Clerk.setActive: not found

    rect rgb(255, 230, 230)
    Note over Clerk.setActive,Error: NEW validation path
    Clerk.setActive->>Error: throw ClerkRuntimeError("Unable to find organization with slug \"invalid-org-slug\"...")
    Error-->>Caller: reject with error
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Localized changes in two files; logic is a single validation branch and matching tests.
  • Areas needing extra attention:
    • Exact error message and code consistency in clerk.ts.
    • Removal or consolidation of the duplicated test in clerk.test.ts.

Poem

🐇 A slug once lost in hush and fog,
Now hops aloud through code and log.
"Not found!" it cries with rhyming cheer,
No silence left — the path is clear.
🥕

Pre-merge checks and finishing touches

✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'fix(clerk-js): Fix silent failure with setActive org slug' directly and clearly summarizes the main change. It identifies the package (clerk-js), the type of change (fix), and the specific issue being addressed (silent failure with setActive org slug). The title is concise and specific enough for teammates to understand the primary change when scanning history.
Linked Issues check ✅ Passed The code changes directly address the requirements specified in linked issue USER-3777. The PR adds validation in clerk.ts that throws a ClerkRuntimeError when an invalid org_slug is provided to setActive, and adds test cases in clerk.test.ts to verify this error handling. This transforms the previously silent failure into an explicit error comparable to the org_id case, which matches the stated objective of ensuring consistent error behavior.
Out of Scope Changes check ✅ Passed All changes in this pull request are directly related to fixing the silent failure issue with setActive and org_slug validation. The modifications to clerk.ts implement the error handling logic, and the test additions in clerk.test.ts validate this behavior. There are no unrelated changes or alterations to other functionality outside the scope of addressing the silent failure.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cursor/USER-3777-fix-silent-failure-with-setactive-org-slug-fe0b

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1e7a51d and 022593d.

📒 Files selected for processing (2)
  • packages/clerk-js/src/core/__tests__/clerk.test.ts (1 hunks)
  • packages/clerk-js/src/core/clerk.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/clerk-js/src/core/tests/clerk.test.ts
  • packages/clerk-js/src/core/clerk.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (28)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

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

@jescalan jescalan changed the title Fix silent failure with setActive org slug fix(clerk-js): Fix silent failure with setActive org slug Nov 3, 2025
@jescalan jescalan marked this pull request as ready for review November 3, 2025 16:08
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/core/__tests__/clerk.test.ts (1)

381-406: Consider adding edge case coverage for the new validation.

The test correctly validates the error path for invalid slugs. To ensure robust coverage and prevent regressions, consider adding tests for:

  1. Valid behavior with null - should switch to personal workspace without throwing
  2. Behavior with empty string - currently won't throw due to truthiness check in the implementation
  3. Behavior with undefined - should preserve current organization

Example additional test cases:

it('switches to personal workspace when organization is set to null', async () => {
  const mockSession2 = {
    id: '1',
    status,
    user: {
      organizationMemberships: [
        {
          id: 'orgmem_id',
          organization: {
            id: 'org_id',
            slug: 'valid-org-slug',
          },
        },
      ],
    },
    touch: vi.fn(),
    getToken: vi.fn(),
  };
  mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession2] }));
  const sut = new Clerk(productionPublishableKey);
  await sut.load();

  mockSession2.touch.mockImplementationOnce(() => {
    sut.session = mockSession2 as any;
    return Promise.resolve();
  });
  mockSession2.getToken.mockImplementation(() => 'mocked-token');

  // Should not throw, should set to personal workspace
  await sut.setActive({ organization: null });

  await waitFor(() => {
    expect((mockSession2 as any as ActiveSessionResource)?.lastActiveOrganizationId).toBeNull();
  });
});

it('does not throw when organization is set to empty string', async () => {
  const mockSession2 = {
    id: '1',
    status,
    user: {
      organizationMemberships: [
        {
          id: 'orgmem_id',
          organization: {
            id: 'org_id',
            slug: 'valid-org-slug',
          },
        },
      ],
    },
    touch: vi.fn(),
    getToken: vi.fn(),
  };
  mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession2] }));
  const sut = new Clerk(productionPublishableKey);
  await sut.load();

  mockSession2.touch.mockImplementationOnce(() => {
    sut.session = mockSession2 as any;
    return Promise.resolve();
  });
  mockSession2.getToken.mockImplementation(() => 'mocked-token');

  // Empty string is falsy, should switch to personal workspace without throwing
  await expect(sut.setActive({ organization: '' })).resolves.not.toThrow();
});
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5b85ea9 and 1e7a51d.

📒 Files selected for processing (2)
  • packages/clerk-js/src/core/__tests__/clerk.test.ts (1 hunks)
  • packages/clerk-js/src/core/clerk.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.ts
  • packages/clerk-js/src/core/clerk.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

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

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.ts
  • packages/clerk-js/src/core/clerk.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.ts
  • packages/clerk-js/src/core/clerk.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.ts
  • packages/clerk-js/src/core/clerk.ts
**/*.{ts,tsx}

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

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.ts
  • packages/clerk-js/src/core/clerk.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

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

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

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

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.ts
**/*.{js,ts,tsx,jsx}

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

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.ts
  • packages/clerk-js/src/core/clerk.ts
**/__tests__/**/*.{ts,tsx}

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

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/__tests__/clerk.test.ts (1)
packages/clerk-js/src/core/clerk.ts (1)
  • Clerk (197-3012)

cursoragent and others added 2 commits November 3, 2025 11:23
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@jescalan jescalan force-pushed the cursor/USER-3777-fix-silent-failure-with-setactive-org-slug-fe0b branch from 261ed3d to 022593d Compare November 3, 2025 16:23
@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 3, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@7132

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@7132

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@7132

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@7132

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@7132

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@7132

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@7132

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@7132

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@7132

@clerk/express

npm i https://pkg.pr.new/@clerk/express@7132

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@7132

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@7132

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@7132

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@7132

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@7132

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@7132

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@7132

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@7132

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@7132

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@7132

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@7132

@clerk/types

npm i https://pkg.pr.new/@clerk/types@7132

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@7132

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@7132

commit: 022593d

@blacksmith-sh
Copy link

blacksmith-sh bot commented Nov 3, 2025

Found 18 test failures on Blacksmith runners:

Test View Logs
[chrome] › integration/tests/
components.test.ts:102:9 › component smoke tests @generic › long-running--react.vite.wi
thEmailCodes › CreateOrganization supports fallback
View Logs
[chrome] › integration/tests/elements/
next-sign-in.test.ts:134:7 › Next.js Sign-In Flow @elements › long-running--elements.ne
xt.appRouter › can reset password
View Logs
[chrome] › integration/tests/elements/
otp.test.ts:196:9 › OTP @elements › long-running--elements.next.appRouter › Type: segme
nted-otp › should forward-delete char when pressing delete
View Logs
[chrome] › integration/tests/
handshake.test.ts:863:7 › Client handshake @generic › External visit - new devbrowser
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:221:7 › pricing table @billing › long-running--withBilling.next.a
ppRouter › user is prompted to add email before checkout
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:588:9 › pricing table @billing › long-running--withBilling.next.a
ppRouter › in UserProfile › adds payment method via checkout and resets stripe setup in
tent after failed payment
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:625:9 › pricing table @billing › long-running--withBilling.next.a
ppRouter › in UserProfile › displays notice then plan cannot change
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:658:9 › pricing table @billing › long-running--withBilling.next.a
ppRouter › in UserProfile › adds two payment methods and sets the last as default
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:80:9 › pricing table @billing › long-running--withBilling.vue.vit
e › when signed in flow › when signed in, clicking get started button opens checkout dr
awer and shows free plan as active
View Logs
[chrome] › integration/tests/
sign-in-flow.test.ts:101:7 › sign in flow @generic @nextjs › long-running--next.appRout
er.withEmailCodes › can reset password
View Logs
[chrome] › integration/tests/
sign-in-flow.test.ts:101:7 › sign in flow @generic @nextjs › long-running--next.appRout
er.withEmailCodes › can reset password
View Logs
[chrome] › integration/tests/
sign-in-flow.test.ts:101:7 › sign in flow @generic @nextjs › long-running--next.appRout
er.withEmailCodes › can reset password
View Logs
[chrome] › integration/tests/
sign-in-flow.test.ts:101:7 › sign in flow @generic @nextjs › long-running--next.appRout
er.withEmailCodes › can reset password
View Logs
[chrome] › integration/tests/
sign-in-flow.test.ts:101:7 › sign in flow @generic @nextjs › long-running--react.vite.w
ithEmailCodes › can reset password
View Logs
[chrome] › integration/tests/
sign-in-or-up-flow.test.ts:115:9 › sign-in-or-up flow @nextjs › long-running--next.appR
outer.withSignInOrUpFlow › sign-in › can reset password
View Logs
[chrome] › integration/tests/
sign-in-or-up-flow.test.ts:115:9 › sign-in-or-up flow @nextjs › long-running--next.appR
outer.withSignInOrUpFlow › sign-in › can reset password
View Logs
[chrome] › integration/tests/
sign-in-or-up-flow.test.ts:115:9 › sign-in-or-up flow @nextjs › long-running--next.appR
outer.withSignInOrUpFlow › sign-in › can reset password
View Logs
[setup] › integration/tests/
global.setup.ts:7:6 › start long running apps ─────────────────────
View Logs


Fix in Cursor

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants