Skip to content

Conversation

@brkalow
Copy link
Member

@brkalow brkalow commented Nov 5, 2025

When a session already exists during sign-in, complete the sign-in and redirect instead of only rendering an error.

Changes

  • Added SESSION_EXISTS error code constant
  • Modified SignInStart to detect session_exists error and call clerk.setActive() with redirect
  • Modified SignInSocialButtons to handle session_exists error in OAuth flows
  • Added comprehensive test coverage for both regular and OAuth sign-in flows

Tests

  • Added 3 new tests in SignInStart.test.tsx:
    • Regular sign-in with session_exists error
    • Navigation after setting session active
    • OAuth sign-in with session_exists error
  • All 65 tests passing ✅

Related

Fixes the user experience when a session already exists, allowing seamless continuation instead of showing an error.

Summary by CodeRabbit

  • Bug Fixes

    • Sign-in flows now detect an already-active session and activate it, then redirect to the post-sign-in destination instead of showing an error.
    • Social/OAuth sign-in error handling improved to complete sign-in and redirect when an existing session is detected.
  • Tests

    • Added unit and integration tests covering OAuth and password sign-in when a session exists.
  • Chores

    • Prepared a minor release changeset.

@changeset-bot
Copy link

changeset-bot bot commented Nov 5, 2025

🦋 Changeset detected

Latest commit: e8c45d9

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

This PR includes changesets to release 3 packages
Name Type
@clerk/clerk-js Minor
@clerk/chrome-extension Patch
@clerk/clerk-expo 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

@vercel
Copy link

vercel bot commented Nov 5, 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 5, 2025 6:09pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 5, 2025

Walkthrough

Adds a SESSION_EXISTS error code and recovery: sign-in flows detect an existing session error, call clerk.setActive(lastActiveSessionId), and navigate to the after-sign-in URL instead of surfacing an error.

Changes

Cohort / File(s) Change Summary
Changeset & Constants
.changeset/chubby-memes-kiss.md, packages/clerk-js/src/core/constants.ts
Adds a changeset for a minor release and introduces SESSION_EXISTS: 'session_exists' to ERROR_CODES.
Import source updates
packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx, packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx
Replaces isClerkAPIResponseError import source from @/index.headless to @clerk/shared/error.
SignIn UI — popup/redirect error handling
packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx
Adds a handleError wrapper that detects SESSION_EXISTS, calls setActive(lastActiveSessionId), then navigates to afterSignInUrl; integrates ClerkAPIError, isClerkAPIResponseError, and ERROR_CODES.
SignIn flow control
packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx
Detects session_exists error in sign-in recovery path, calls clerk.setActive(lastActiveSessionId) and triggers navigation via navigateOnSetActive before existing already-signed-in handling.
SignIn tests & integration
packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx, integration/tests/oauth-flows.test.ts, integration/tests/sign-in-flow.test.ts
Adds unit and integration tests covering SESSION_EXISTS behavior for OAuth and password/instant-password flows, verifying setActive is called and navigation occurs (including OAuth redirect case).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SignInUI as SignIn UI
    participant ClerkAPI
    participant Session
    participant Router

    User->>SignInUI: Start sign-in (credentials or OAuth)
    SignInUI->>ClerkAPI: Submit sign-in request
    ClerkAPI-->>SignInUI: 422 response (session_exists)

    rect rgba(232,243,255,0.9)
      Note over SignInUI: SESSION_EXISTS recovery
      SignInUI->>SignInUI: detect SESSION_EXISTS error
      SignInUI->>Session: setActive(lastActiveSessionId)
      Session-->>SignInUI: activation confirmed
      SignInUI->>Router: navigate to afterSignInUrl
    end

    Router-->>User: Redirect complete

    alt Previous behavior
      SignInUI->>User: Render sign-in error
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

  • Focus review on:
    • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx — ordering and conditions for session_exists vs already-signed-in handling.
    • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx — correctness of handleError, async setActive then navigation across popup vs redirect flows.
    • Tests and integration specs — ensure mocks for setActive and navigation reflect async behavior and redirect assertions.

Poem

🐰 I sniffed an old session beneath the pine,
A whisper of tokens, "This one is mine."
I wake it with a twitch, set it to play,
Then hop you gently to your signed-in day.
Tiny paws — smooth redirects all the way. 🎉

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately describes the main change: introducing redirect behavior when a session exists during sign-in, which is the core objective of the changeset.
✨ 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 brk.feat/redirect-on-session-exists

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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 5, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: e8c45d9

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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx (1)

435-454: Add null-check before activating session on SESSION_EXISTS error in both SignInStart and SignInSocialButtons.

The code passes clerk.client.lastActiveSessionId directly to setActive() without validation. The property is typed as string | null and defaults to null. While setActive() handles null gracefully, the established codebase pattern validates this property first (e.g., clerk.ts:2755, router machines). Both locations need fixing:

  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx:450 - wrap session assignment with null-check or add guard condition
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx:44 - same pattern needs validation

Additionally, compare with alreadySignedInError handling (SignInStart.tsx:454-463), which explicitly validates error.meta.sessionId before use. Apply consistent validation here.

🧹 Nitpick comments (3)
.changeset/chubby-memes-kiss.md (1)

5-5: Hyphenate compound nouns for clarity.

The phrase "sign in" appears twice as a noun and should be hyphenated: "sign-in". This improves readability and follows standard English grammar for compound nouns used as modifiers or objects.

Apply this diff:

-When a session already exists on sign in, complete the sign in and redirect instead of only rendering an error.
+When a session already exists on sign-in, complete the sign-in and redirect instead of only rendering an error.
packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx (2)

36-53: Extract duplicated SESSION_EXISTS handling to a shared utility.

This error handling logic is duplicated in SignInStart.tsx (lines 435-454). Consider extracting it to a shared utility function to maintain DRY principles and ensure consistent behavior across sign-in flows.

Example shared utility:

// In a shared error handling file
export const handleSessionExistsError = async (
  err: any,
  clerk: ClerkInstance,
  navigateOnSetActive: (params: {session: any, redirectUrl: string}) => Promise<void>,
  afterSignInUrl: string
) => {
  if (!isClerkAPIResponseError(err)) {
    return false;
  }
  
  const sessionAlreadyExistsError = err.errors.find(
    (e: ClerkAPIError) => e.code === ERROR_CODES.SESSION_EXISTS,
  );
  
  if (sessionAlreadyExistsError) {
    await clerk.setActive({
      session: clerk.client.lastActiveSessionId,
      navigate: async ({ session }) => {
        await navigateOnSetActive({ session, redirectUrl: afterSignInUrl });
      },
    });
    return true;
  }
  
  return false;
};

58-58: Unrelated refactor: prop shorthand.

The change from explicit showLastAuthenticationStrategy={true} to shorthand showLastAuthenticationStrategy is correct but appears unrelated to the SESSION_EXISTS feature. Consider including such changes in a separate commit for clearer history.

📜 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 5536429 and 2eb6101.

📒 Files selected for processing (7)
  • .changeset/chubby-memes-kiss.md (1 hunks)
  • packages/clerk-js/src/core/constants.ts (1 hunks)
  • packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx (1 hunks)
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx (3 hunks)
  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (14)
**/*.{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/constants.ts
  • packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx
**/*.{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/constants.ts
  • packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/constants.ts
  • packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx
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/constants.ts
  • packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx
**/*.{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/constants.ts
  • packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx
**/*.{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/constants.ts
  • packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx
**/*.{jsx,tsx}

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

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx
**/*.tsx

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

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx
  • packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx
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/ui/components/SignIn/__tests__/SignInStart.test.tsx
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/ui/components/SignIn/__tests__/SignInStart.test.tsx
**/*.test.{jsx,tsx}

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

**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure

Files:

  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx
**/__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/ui/components/SignIn/__tests__/SignInStart.test.tsx
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/chubby-memes-kiss.md
🧬 Code graph analysis (3)
packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx (3)
packages/clerk-js/src/index.ts (1)
  • ClerkAPIResponseError (7-7)
packages/clerk-js/src/index.headless.ts (1)
  • ClerkAPIResponseError (6-6)
packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx (1)
  • SignInStart (711-713)
packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx (3)
packages/clerk-js/src/ui/utils/errorHandler.ts (1)
  • handleError (64-86)
packages/clerk-js/src/core/constants.ts (1)
  • ERROR_CODES (18-44)
packages/clerk-js/src/ui/elements/SocialButtons.tsx (1)
  • SocialButtons (55-214)
packages/clerk-js/src/ui/components/SignIn/SignInStart.tsx (1)
packages/clerk-js/src/core/constants.ts (1)
  • ERROR_CODES (18-44)
🪛 LanguageTool
.changeset/chubby-memes-kiss.md

[grammar] ~5-~5: Use a hyphen to join words.
Context: ...- When a session already exists on sign in, complete the sign in and redirect in...

(QB_NEW_EN_HYPHEN)


[grammar] ~5-~5: Use a hyphen to join words.
Context: ...ady exists on sign in, complete the sign in and redirect instead of only renderin...

(QB_NEW_EN_HYPHEN)

⏰ 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). (4)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx (1)

1-1: LGTM! Import path refactor improves modularity.

The migration of isClerkAPIResponseError to @clerk/shared/error consolidates error handling utilities into a shared module, improving code organization without changing behavior.

packages/clerk-js/src/ui/components/SignUp/SignUpStart.tsx (1)

2-2: LGTM! Consistent with the module consolidation pattern.

This import path update aligns with the broader refactor to centralize error utilities in @clerk/shared/error, maintaining consistency across the codebase.

packages/clerk-js/src/ui/components/SignIn/__tests__/SignInStart.test.tsx (2)

256-286: LGTM! Comprehensive OAuth session_exists test coverage.

The test properly validates that when a session_exists error occurs during OAuth sign-in, the system activates the existing session and provides a navigate callback.


558-626: LGTM! Thorough validation of session activation and navigation flow.

The tests cover both the setActive call and the subsequent navigation behavior when session_exists occurs during standard sign-in. The second test properly mocks the navigate callback invocation to ensure the full flow completes.

packages/clerk-js/src/core/constants.ts (1)

30-30: LGTM! Error code constant follows established patterns.

The new SESSION_EXISTS constant is properly named and positioned, enabling consistent error handling across the sign-in flows.

packages/clerk-js/src/ui/components/SignIn/SignInSocialButtons.tsx (1)

75-80: LGTM! Error handling properly integrated into OAuth flows.

The new handleError wrapper is correctly applied to both popup and redirect OAuth flows, ensuring consistent SESSION_EXISTS handling across authentication methods.

Copy link
Member

@jacekradko jacekradko left a comment

Choose a reason for hiding this comment

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

This could really use an integration spec

@brkalow brkalow changed the title Redirect on session exists during sign-in feat(clerk-js): Redirect on session exists during sign-in Nov 5, 2025
- Add tests in sign-in-flow.test.ts for regular sign-in with existing session
- Add test in oauth-flows.test.ts for OAuth sign-in with existing session
- Verify users are redirected and remain signed in instead of seeing errors
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: 0

🧹 Nitpick comments (3)
integration/tests/oauth-flows.test.ts (1)

260-279: Verify test placement and strengthen assertions.

This test is placed within the "oauth flows with legal consent" describe block but doesn't interact with the legal consent flow. Consider moving it to the first describe block (line 10) that doesn't require legal consent, or explicitly handle legal consent if it's required on the second sign-in attempt.

Additionally, the test could be more robust:

  • After clicking the OAuth button the second time (line 275), add an explicit assertion or wait for the redirect/navigation to complete before checking the signed-in state
  • Verify that the user is redirected to the expected URL (e.g., afterSignInUrl)
  • Consider asserting that no error message is displayed

Example enhancement:

   // Now attempt to sign in again via OAuth while already signed in
   await u.po.signIn.goTo();
   await u.page.getByRole('button', { name: 'E2E OAuth Provider' }).click();

+  // Wait for and verify redirect occurs
+  await u.page.waitForURL(/SignedIn|\//, { timeout: 5000 });
+  
   // Should redirect and remain signed in instead of showing an error
   await u.po.expect.toBeSignedIn();
integration/tests/sign-in-flow.test.ts (2)

154-170: Consider strengthening test assertions.

The test correctly verifies that the user remains signed in, but could be more comprehensive:

  • Verify the user is redirected to the expected URL after navigating to the sign-in page (line 166)
  • Assert that no error message is displayed during the redirect

Example enhancement:

   // Now attempt to go to sign-in page again while already signed in
   await u.po.signIn.goTo();

+  // Verify redirect occurred to expected URL
+  await u.page.waitForURL(/SignedIn|\//, { timeout: 5000 });
+  
   // User should be redirected and remain signed in instead of seeing an error
   await u.po.expect.toBeSignedIn();

172-193: Clarify intermediate navigation purpose and strengthen assertions.

The navigation to '/' at line 184 followed by a signed-in verification seems unnecessary since the user is already signed in after line 181. If this step is required to reset some state or test a specific scenario, please add a comment explaining its purpose. Otherwise, consider removing lines 184-185.

Additionally, similar to the previous test, consider adding assertions to:

  • Verify the redirect URL after the second sign-in attempt (line 189)
  • Assert that no error message is displayed

If the intermediate navigation is needed:

   // Clear the page to go back to sign-in
   await u.page.goToRelative('/');
   await u.po.expect.toBeSignedIn();

Could become:

   // Navigate away to test re-entry to sign-in flow
   await u.page.goToRelative('/');
   await u.po.expect.toBeSignedIn();

Or if it's unnecessary, remove it entirely and add URL verification:

   await u.po.expect.toBeSignedIn();

-  // Clear the page to go back to sign-in
-  await u.page.goToRelative('/');
-  await u.po.expect.toBeSignedIn();
-
   // Attempt to sign in again with instant password
   await u.po.signIn.goTo();
   await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });

+  // Verify redirect occurred
+  await u.page.waitForURL(/SignedIn|\//, { timeout: 5000 });
+  
   // Should redirect and remain signed in without error
   await u.po.expect.toBeSignedIn();
📜 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 2eb6101 and 15e0643.

📒 Files selected for processing (2)
  • integration/tests/oauth-flows.test.ts (1 hunks)
  • integration/tests/sign-in-flow.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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:

  • integration/tests/oauth-flows.test.ts
  • integration/tests/sign-in-flow.test.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:

  • integration/tests/oauth-flows.test.ts
  • integration/tests/sign-in-flow.test.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:

  • integration/tests/oauth-flows.test.ts
  • integration/tests/sign-in-flow.test.ts
integration/**

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

Framework integration templates and E2E tests should be placed under the integration/ directory

Files:

  • integration/tests/oauth-flows.test.ts
  • integration/tests/sign-in-flow.test.ts
integration/**/*

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

End-to-end tests and integration templates must be located in the 'integration/' directory.

Files:

  • integration/tests/oauth-flows.test.ts
  • integration/tests/sign-in-flow.test.ts
integration/**/*.{test,spec}.{js,ts}

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

Integration tests should use Playwright.

Files:

  • integration/tests/oauth-flows.test.ts
  • integration/tests/sign-in-flow.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:

  • integration/tests/oauth-flows.test.ts
  • integration/tests/sign-in-flow.test.ts
🧬 Code graph analysis (2)
integration/tests/oauth-flows.test.ts (1)
integration/testUtils/index.ts (1)
  • createTestUtils (24-86)
integration/tests/sign-in-flow.test.ts (1)
integration/testUtils/index.ts (1)
  • createTestUtils (24-86)
⏰ 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). (4)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan

@blacksmith-sh
Copy link

blacksmith-sh bot commented Nov 5, 2025

Found 1 test failure on Blacksmith runners:

Test View Logs
[chrome] › integration/tests/
sign-in-flow.test.ts:154:7 › sign in flow @generic @nextjs › long-running--react.vite.w
ithEmailCodes › redirects when attempting to sign in with existing session in another t
ab
View Logs


Fix in Cursor

- Use runInNewTab to properly test session_exists scenario
- First tab signs in, second tab attempts to sign in with same user
- This triggers the session_exists error that the code handles
- Without separate tabs, SignIn component would auto-redirect on mount
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: 0

🧹 Nitpick comments (3)
integration/tests/oauth-flows.test.ts (1)

260-289: Test logic is correct, but browser parameter appears unused.

The test correctly validates multi-tab OAuth sign-in behavior with existing sessions. However, the browser parameter is passed to createTestUtils but never used—runInNewTab relies on context to create the new tab.

Consider removing the browser parameter since runInNewTab only requires context:

-    test('redirects when attempting OAuth sign in with existing session in another tab', async ({
-      page,
-      context,
-      browser,
-    }) => {
-      const u = createTestUtils({ app, page, context, browser });
+    test('redirects when attempting OAuth sign in with existing session in another tab', async ({ page, context }) => {
+      const u = createTestUtils({ app, page, context });

Additionally, consider adding explicit verification that no error is shown in the second tab before asserting toBeSignedIn(), to strengthen the test's validation of SESSION_EXISTS handling.

integration/tests/sign-in-flow.test.ts (2)

154-180: Test is correct, but browser parameter is unused.

The test properly validates multi-tab sign-in behavior with password authentication when a session exists. However, like the OAuth test, the browser parameter is unnecessary since runInNewTab only uses context.

Apply this diff to remove the unused parameter:

-  test('redirects when attempting to sign in with existing session in another tab', async ({
-    page,
-    context,
-    browser,
-  }) => {
-    const u = createTestUtils({ app, page, context, browser });
+  test('redirects when attempting to sign in with existing session in another tab', async ({ page, context }) => {
+    const u = createTestUtils({ app, page, context });

182-202: Test is sound, but has duplication and unused parameter.

This test correctly validates instant password sign-in with an existing session across tabs. However, it shares the same issues as the previous test: unused browser parameter and significant code duplication.

  1. Remove the unused browser parameter:
-  test('redirects when attempting to sign in again with instant password in another tab', async ({
-    page,
-    context,
-    browser,
-  }) => {
-    const u = createTestUtils({ app, page, context, browser });
+  test('redirects when attempting to sign in again with instant password in another tab', async ({ page, context }) => {
+    const u = createTestUtils({ app, page, context });
  1. Consider extracting a helper function to reduce duplication between lines 154-180 and 182-202. The tests follow an identical pattern—only the sign-in method differs. A parameterized helper would improve maintainability:
async function testMultiTabSignIn(
  signInMethod: (u: TestUtils) => Promise<void>,
  testName: string
) {
  test(testName, async ({ page, context }) => {
    const u = createTestUtils({ app, page, context });
    
    // Sign in on first tab
    await signInMethod(u);
    await u.po.expect.toBeSignedIn();
    
    // Open new tab and sign in again
    await u.tabs.runInNewTab(async u2 => {
      await signInMethod(u2);
      await u2.po.expect.toBeSignedIn();
    });
  });
}
📜 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 15e0643 and a57c28d.

📒 Files selected for processing (2)
  • integration/tests/oauth-flows.test.ts (1 hunks)
  • integration/tests/sign-in-flow.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.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:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.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:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.ts
integration/**

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

Framework integration templates and E2E tests should be placed under the integration/ directory

Files:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.ts
integration/**/*

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

End-to-end tests and integration templates must be located in the 'integration/' directory.

Files:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.ts
integration/**/*.{test,spec}.{js,ts}

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

Integration tests should use Playwright.

Files:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.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:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.ts
🧬 Code graph analysis (2)
integration/tests/sign-in-flow.test.ts (1)
integration/testUtils/index.ts (1)
  • createTestUtils (24-86)
integration/tests/oauth-flows.test.ts (1)
integration/testUtils/index.ts (1)
  • createTestUtils (24-86)
⏰ 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). (30)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (localhost, 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: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

- Update tests to open sign-in in multiple tabs before signing in
- This properly tests the session_exists error scenario where the sign-in component is already mounted
- Sign in on one tab, then attempt to sign in on the other tab
- Prevents component from redirecting on mount before API call is made
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: 3

📜 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 a57c28d and e8c45d9.

📒 Files selected for processing (2)
  • integration/tests/oauth-flows.test.ts (1 hunks)
  • integration/tests/sign-in-flow.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.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:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.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:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.ts
integration/**

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

Framework integration templates and E2E tests should be placed under the integration/ directory

Files:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.ts
integration/**/*

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

End-to-end tests and integration templates must be located in the 'integration/' directory.

Files:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.ts
integration/**/*.{test,spec}.{js,ts}

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

Integration tests should use Playwright.

Files:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.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:

  • integration/tests/sign-in-flow.test.ts
  • integration/tests/oauth-flows.test.ts
🧬 Code graph analysis (2)
integration/tests/sign-in-flow.test.ts (1)
integration/testUtils/index.ts (1)
  • createTestUtils (24-86)
integration/tests/oauth-flows.test.ts (1)
integration/testUtils/index.ts (1)
  • createTestUtils (24-86)
⏰ 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). (4)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan

Comment on lines +260 to +290
test('redirects when attempting OAuth sign in with existing session in another tab', async ({
page,
context,
browser,
}) => {
const u = createTestUtils({ app, page, context, browser });

// Open sign-in page in both tabs before signing in
await u.po.signIn.goTo();

let secondTabUtils: any;
await u.tabs.runInNewTab(async u2 => {
secondTabUtils = u2;
await u2.po.signIn.goTo();
});

// Sign in via OAuth on the first tab
await u.page.getByRole('button', { name: 'E2E OAuth Provider' }).click();
await u.page.getByText('Sign in to oauth-provider').waitFor();
await u.po.signIn.setIdentifier(fakeUser.email);
await u.po.signIn.continue();
await u.po.signIn.enterTestOtpCode();
await u.page.getByText('SignedIn').waitFor();
await u.po.expect.toBeSignedIn();

// Attempt to sign in via OAuth on the second tab (which already has sign-in mounted)
await secondTabUtils.page.getByRole('button', { name: 'E2E OAuth Provider' }).click();

// Should redirect and be signed in without error
await secondTabUtils.po.expect.toBeSignedIn();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Avoid any type for secondTabUtils.

Line 270 declares secondTabUtils with any type, which violates the TypeScript coding guidelines. The return type of createTestUtils is complex but can be properly typed.

Apply this diff to properly type the variable:

-    let secondTabUtils: any;
+    let secondTabUtils: Awaited<ReturnType<typeof u.tabs.runInNewTab>>;
     await u.tabs.runInNewTab(async u2 => {
       secondTabUtils = u2;
       await u2.po.signIn.goTo();
     });

As per coding guidelines.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In integration/tests/oauth-flows.test.ts around lines 260 to 290, the variable
secondTabUtils is declared as any on line 270; replace this with a proper type
by using the factory return type: declare it as let secondTabUtils!:
ReturnType<typeof createTestUtils>; (or let secondTabUtils: ReturnType<typeof
createTestUtils> | null = null and add a null-check) and remove any usage of any
so the value assigned inside u.tabs.runInNewTab has the correct typed shape and
the later accesses (secondTabUtils.page, secondTabUtils.po, etc.) are type-safe.

Comment on lines +154 to +185
test('redirects when attempting to sign in with existing session in another tab', async ({
page,
context,
browser,
}) => {
const u = createTestUtils({ app, page, context, browser });

// Open sign-in page in both tabs before signing in
await u.po.signIn.goTo();

let secondTabUtils: any;
await u.tabs.runInNewTab(async u2 => {
secondTabUtils = u2;
await u2.po.signIn.goTo();
});

// Sign in on the first tab
await u.po.signIn.setIdentifier(fakeUser.email);
await u.po.signIn.continue();
await u.po.signIn.setPassword(fakeUser.password);
await u.po.signIn.continue();
await u.po.expect.toBeSignedIn();

// Attempt to sign in on the second tab (which already has sign-in mounted)
await secondTabUtils.po.signIn.setIdentifier(fakeUser.email);
await secondTabUtils.po.signIn.continue();
await secondTabUtils.po.signIn.setPassword(fakeUser.password);
await secondTabUtils.po.signIn.continue();

// Should redirect and be signed in without error
await secondTabUtils.po.expect.toBeSignedIn();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Avoid any type for secondTabUtils.

Line 164 declares secondTabUtils with any type, which violates the TypeScript coding guidelines.

Apply this diff to properly type the variable:

-    let secondTabUtils: any;
+    let secondTabUtils: Awaited<ReturnType<typeof u.tabs.runInNewTab>>;
     await u.tabs.runInNewTab(async u2 => {
       secondTabUtils = u2;
       await u2.po.signIn.goTo();
     });

As per coding guidelines.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
test('redirects when attempting to sign in with existing session in another tab', async ({
page,
context,
browser,
}) => {
const u = createTestUtils({ app, page, context, browser });
// Open sign-in page in both tabs before signing in
await u.po.signIn.goTo();
let secondTabUtils: any;
await u.tabs.runInNewTab(async u2 => {
secondTabUtils = u2;
await u2.po.signIn.goTo();
});
// Sign in on the first tab
await u.po.signIn.setIdentifier(fakeUser.email);
await u.po.signIn.continue();
await u.po.signIn.setPassword(fakeUser.password);
await u.po.signIn.continue();
await u.po.expect.toBeSignedIn();
// Attempt to sign in on the second tab (which already has sign-in mounted)
await secondTabUtils.po.signIn.setIdentifier(fakeUser.email);
await secondTabUtils.po.signIn.continue();
await secondTabUtils.po.signIn.setPassword(fakeUser.password);
await secondTabUtils.po.signIn.continue();
// Should redirect and be signed in without error
await secondTabUtils.po.expect.toBeSignedIn();
});
test('redirects when attempting to sign in with existing session in another tab', async ({
page,
context,
browser,
}) => {
const u = createTestUtils({ app, page, context, browser });
// Open sign-in page in both tabs before signing in
await u.po.signIn.goTo();
let secondTabUtils: Awaited<ReturnType<typeof u.tabs.runInNewTab>>;
await u.tabs.runInNewTab(async u2 => {
secondTabUtils = u2;
await u2.po.signIn.goTo();
});
// Sign in on the first tab
await u.po.signIn.setIdentifier(fakeUser.email);
await u.po.signIn.continue();
await u.po.signIn.setPassword(fakeUser.password);
await u.po.signIn.continue();
await u.po.expect.toBeSignedIn();
// Attempt to sign in on the second tab (which already has sign-in mounted)
await secondTabUtils.po.signIn.setIdentifier(fakeUser.email);
await secondTabUtils.po.signIn.continue();
await secondTabUtils.po.signIn.setPassword(fakeUser.password);
await secondTabUtils.po.signIn.continue();
// Should redirect and be signed in without error
await secondTabUtils.po.expect.toBeSignedIn();
});
🤖 Prompt for AI Agents
In integration/tests/sign-in-flow.test.ts around lines 154 to 185,
secondTabUtils is currently declared with the `any` type (line 164); change it
to the concrete TestUtils type instead of `any` — type it the same as `u` (e.g.,
use `typeof u` or `ReturnType<typeof createTestUtils>`), ensuring any necessary
types are imported or inferred so the variable is strongly typed for the
runInNewTab callback.

Comment on lines +187 to +215
test('redirects when attempting to sign in with instant password and existing session in another tab', async ({
page,
context,
browser,
}) => {
const u = createTestUtils({ app, page, context, browser });

// Open sign-in page in both tabs before signing in
await u.po.signIn.goTo();

let secondTabUtils: any;
await u.tabs.runInNewTab(async u2 => {
secondTabUtils = u2;
await u2.po.signIn.goTo();
});

// Sign in with instant password on the first tab
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.expect.toBeSignedIn();

// Attempt to sign in with instant password on the second tab
await secondTabUtils.po.signIn.signInWithEmailAndInstantPassword({
email: fakeUser.email,
password: fakeUser.password,
});

// Should redirect and be signed in without error
await secondTabUtils.po.expect.toBeSignedIn();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Avoid any type for secondTabUtils.

Line 197 declares secondTabUtils with any type, which violates the TypeScript coding guidelines.

Apply this diff to properly type the variable:

-    let secondTabUtils: any;
+    let secondTabUtils: Awaited<ReturnType<typeof u.tabs.runInNewTab>>;
     await u.tabs.runInNewTab(async u2 => {
       secondTabUtils = u2;
       await u2.po.signIn.goTo();
     });

As per coding guidelines.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
integration/tests/sign-in-flow.test.ts around lines 187 to 215: the variable
secondTabUtils is declared as any on line 197; replace the any with the concrete
test-utils type (same as the local u) — e.g. declare secondTabUtils as
ReturnType<typeof createTestUtils> or typeof u so it has proper typing, and
ensure it is non-null when used (initialize to undefined with that type or
narrow/check before using) to satisfy TypeScript rules and the project coding
guidelines.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants