Skip to content

fix(clerk-js): Add error handling for setActive with stale organization data #6550

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

LauraBeatris
Copy link
Member

@LauraBeatris LauraBeatris commented Aug 14, 2025

Description

This PR introduces error handling for /touch and /tokens error within setActive when the organization doesn't exist. This can happen when the client has stale organization data.

We're applying fixes to both OrganizationList and TaskChooseOrganization

CleanShot.2025-08-15.at.10.30.08.mp4

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling when selecting/activating organizations; errors are displayed in-flow and cleared appropriately.
    • Enhanced error visibility in organization list and choose/create flows with alerts.
  • Refactor

    • Replaced HOC-based card state with hook-based state across organization choose/create screens and previews.
  • Localization

    • Added a new error key for “organization not found or unauthorized” across locales; translations included for en-US and pt-BR, placeholders elsewhere.
  • Chores

    • Added a changeset to publish patch releases.

@LauraBeatris LauraBeatris self-assigned this Aug 14, 2025
Copy link

changeset-bot bot commented Aug 14, 2025

🦋 Changeset detected

Latest commit: 6ff3f76

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

This PR includes changesets to release 19 packages
Name Type
@clerk/clerk-js Patch
@clerk/shared Patch
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/vue 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

Copy link

vercel bot commented Aug 14, 2025

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

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Preview Comment Aug 15, 2025 2:20pm

Comment on lines 49 to 56
// Revalidates organization memberships from client piggybacking
// TODO (add linear ticket): Introduce architecture to invalidate SWR queries based on client piggybacking
useEffect(() => {
const hasUpdatedOnClient = (user?.organizationMemberships?.length ?? 0) !== (userMemberships.count ?? 0);
if (!hasUpdatedOnClient || !userMemberships) return;

void userMemberships.revalidate?.();
}, [userMemberships, user?.organizationMemberships?.length]);
Copy link
Member Author

Choose a reason for hiding this comment

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

We're applying a fix scoped to the TaskChooseOrganization component only for now to unblock after-auth flows.

This issue could also happen with OrganizationList standalone usage, where stale memberships could be rendered even if a user got deprovisioned from an organization.

The proper solution here would be to revalidate the data based on events, but we don't have the time/effort to introduce it now.

@LauraBeatris LauraBeatris changed the title fix(clerk-js): Revalidate org memberships on client update fix(clerk-js): Avoid displaying duplicated organization invitation Aug 14, 2025
@LauraBeatris LauraBeatris changed the title fix(clerk-js): Avoid displaying duplicated organization invitation fix(clerk-js): Apply revalidation of memberships for task component Aug 14, 2025
@LauraBeatris LauraBeatris force-pushed the laura/fix-orgs-data-revalidation branch from e4c6b4c to 213092f Compare August 14, 2025 22:24
@@ -323,7 +323,6 @@ export function useOrganizationList<T extends UseOrganizationListParams>(params?
{
type: 'userMemberships',
userId: user?.id,
memberships: user?.organizationMemberships.length ?? 0,
Copy link
Member Author

Choose a reason for hiding this comment

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

This created a fresh new entry in the client cache, causing the entire component to re-render. It also affected the OrganizationList component, so we want to minimize the side effects for the task component only due to the after-auth flow.

@LauraBeatris LauraBeatris marked this pull request as ready for review August 14, 2025 22:28
@LauraBeatris LauraBeatris requested a review from a team August 14, 2025 22:28
Copy link
Contributor

coderabbitai bot commented Aug 14, 2025

📝 Walkthrough

Walkthrough

  • Adds changeset marking patch releases for @clerk/clerk-js and @clerk/shared.
  • Refactors ChooseOrganizationScreen, MembershipPreview, InvitationPreview, CreateOrganizationScreen, and OrganizationList components to remove withCardStateProvider, use useCardState, and display Card.Alert.
  • Introduces try/catch error handling around organization activation and routes errors via handleError/card.setError.
  • Updates OrganizationList flows to manage and clear errors locally.
  • Adjusts useOrganizationList to remove memberships option in userMemberships pagination.
  • Adds organization_not_found_or_unauthorized localization key across locales (translations in en-US and pt-BR; placeholders elsewhere).
  • Extends UnstableErrors type with organization_not_found_or_unauthorized.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • 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 0658be8 and 6ff3f76.

📒 Files selected for processing (2)
  • packages/localizations/src/en-US.ts (1 hunks)
  • packages/localizations/src/pt-BR.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/localizations/src/en-US.ts
  • packages/localizations/src/pt-BR.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). (4)
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

♻️ Duplicate comments (1)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (1)

160-168: Dedup guard is pragmatic; document and ensure it works with revalidation timing.

The early return avoids duplicated Invitation/Membership UI. Given the client-side revalidation added in index.tsx, this should converge quickly. Keep the TODO and ensure this is removed when SWR invalidation by events (ORGS-784) lands.

🧹 Nitpick comments (3)
.changeset/tall-ears-worry.md (1)

1-7: Changelog is clear; consider scoping note and ticket link.

The note accurately reflects the user-facing change. For traceability, please include that this is scoped to TaskChooseOrganization (not OrganizationList generally) and reference ORGS-784 in the summary body.

packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (2)

133-139: State and refs: minor type nit and naming clarity.

  • acceptedInvitation state is a clearer name. Good.
  • Consider typing the ref explicitly and initializing with null for clarity.

Example:

-const organizationId = useRef('');
+const organizationId = useRef<string | null>(null);

This better communicates “unset” versus “empty string”.


56-66: Harden optional chaining on pagination flags and pass only required props.

Two opportunistic cleanups to prevent runtime surprises and improve typing:

  • Optional chaining on hasNextPage flags (these may be undefined while lists load):

    • Prefer !(userMemberships?.hasNextPage) and !(userInvitations?.hasNextPage).
  • When rendering memberships, pass only the required prop to MembershipPreview to avoid accidental extra prop leakage:

    • Change <MembershipPreview key={m.id} {...m} /> to <MembershipPreview key={m.id} organization={m.organization} />.

If you want, I can raise a small follow-up PR with these adjustments.

Also applies to: 76-79

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • 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 cd9f96b and 22f6d7a.

📒 Files selected for processing (4)
  • .changeset/tall-ears-worry.md (1 hunks)
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx (3 hunks)
  • packages/shared/src/react/hooks/useOrganizationList.tsx (0 hunks)
💤 Files with no reviewable changes (1)
  • packages/shared/src/react/hooks/useOrganizationList.tsx
🧰 Additional context used
📓 Path-based instructions (11)
.changeset/**

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/tall-ears-worry.md
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/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx
**/*.{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/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx
🧬 Code Graph Analysis (1)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx (1)
packages/react/src/isomorphicClerk.ts (1)
  • user (680-686)
⏰ 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). (2)
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx (2)

1-2: Switch to useUserContext is appropriate here.

Import changes look good. This aligns with the component’s needs and avoids extra object allocations from useUser().


17-17: Using useUserContext() is preferable here.

Nice swap; it reduces indirection versus useUser() and plays well with the Task guards.

packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (1)

7-7: Importing useRef is needed; all good.

The new import is used and keeps the file self-contained.

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

♻️ Duplicate comments (1)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx (1)

35-45: Fix potential crash and false positives: guard userMemberships.count with optional chaining.

If userMemberships is undefined initially, accessing .count will throw. Also, normalizing both sides avoids spurious mismatches while data is loading.

Apply this diff:

-  const hasUpdatedOnClient = user?.organizationMemberships?.length !== userMemberships.count;
+  const hasUpdatedOnClient =
+    (user?.organizationMemberships?.length ?? 0) !== (userMemberships?.count ?? 0);
🧹 Nitpick comments (1)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx (1)

35-45: Add test coverage for the membership revalidation path.

No tests were added in this PR. Please add tests verifying that a client-side change in user.organizationMemberships triggers a single revalidation of userMemberships and that the UI flow switches accordingly once counts match.

I can help scaffold a React Testing Library test that simulates an accepted invitation updating user.organizationMemberships and asserts revalidation is called. Do you want me to draft it?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • 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 22f6d7a and 3a8505b.

📒 Files selected for processing (2)
  • .changeset/tall-ears-worry.md (1 hunks)
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .changeset/tall-ears-worry.md
🧰 Additional context used
📓 Path-based instructions (10)
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/SessionTasks/tasks/TaskChooseOrganization/index.tsx
**/*.{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/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/SessionTasks/tasks/TaskChooseOrganization/index.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.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/SessionTasks/tasks/TaskChooseOrganization/index.tsx
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx
🧬 Code Graph Analysis (1)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx (1)
packages/react/src/isomorphicClerk.ts (1)
  • user (680-686)
⏰ 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: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx (2)

1-2: Imports change looks good.

Switching to useUserContext and adding useEffect is appropriate for the new client revalidation path.


17-17: Switch to useUserContext is appropriate.

This aligns with consuming the user directly from shared context and matches the isomorphicClerk getter behavior.

Copy link

pkg-pr-new bot commented Aug 14, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6ff3f76

@LauraBeatris
Copy link
Member Author

Seems something broke in one of the unit tests - I'll take a look into it tomorrow!

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

♻️ Duplicate comments (1)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (1)

145-155: Use the stored organizationId when fetching the Organization resource.

After accept, you store the canonical id in organizationId.current. Use it in getOrganization to avoid drift.

-          const organization = await getOrganization(props.publicOrganizationData.id);
+          const organization = await getOrganization(organizationId.current || props.publicOrganizationData.id);
🧹 Nitpick comments (8)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx (2)

20-23: Add explicit return type and brief JSDoc on the exported component.

We’ve removed the HOC and now export a plain component; per our TS guidelines, add an explicit return type and brief JSDoc.

-export const CreateOrganizationScreen = (props: CreateOrganizationScreenProps) => {
+/**
+ * Screen to create an organization within the TaskChooseOrganization flow.
+ */
+export const CreateOrganizationScreen = (props: CreateOrganizationScreenProps): JSX.Element => {

77-79: Consider using card.runAsync for submit to drive loading state and prevent double submits.

Right now onSubmit doesn’t set card loading, and the submit button isn’t disabled on loading. Using card.runAsync standardizes state handling and improves UX.

Implementation sketch (outside this hunk):

// Use runAsync
const onSubmit = async (e: React.FormEvent) => {
  e.preventDefault();
  if (!isLoaded) return;

  await card.runAsync(async () => {
    try {
      const organization = await createOrganization({ name: nameField.value, slug: slugField.value });
      await setActive({ organization, redirectUrl: redirectUrlComplete });
    } catch (err) {
      handleError(err, [nameField, slugField], card.setError);
    }
  });
};

// Also include loading state in the button and consider slug value in disabled checks:
const isSubmitButtonDisabled = !nameField.value || !slugField.value || !isLoaded || card.isLoading;
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (6)

33-39: Add explicit return type and brief JSDoc on the exported component.

Per our TS guidelines, add the explicit return type and short doc.

-export const ChooseOrganizationScreen = ({ onCreateOrganizationClick }: ChooseOrganizationScreenProps) => {
+/**
+ * Organization selection screen for the TaskChooseOrganization flow.
+ */
+export const ChooseOrganizationScreen = ({ onCreateOrganizationClick }: ChooseOrganizationScreenProps): JSX.Element => {

59-66: Pass the organization prop explicitly to MembershipPreview.

Passing the entire membership object spreads extra props and can blur intent. Passing organization explicitly tightens typing and improves readability.

-              userMemberships.data?.map(inv => {
+              userMemberships.data?.map(m => {
                 return (
                   <MembershipPreview
-                    key={inv.id}
-                    {...inv}
+                    key={m.id}
+                    organization={m.organization}
                   />
                 );
               })}

165-169: Dedup invitations vs memberships even before accept.

Using organizationId.current only works after accept. To hide duplicates when the user already has a membership, compare against props.publicOrganizationData.id.

-  const hasMembership = userMemberships.data?.some(membership => membership.organization.id === organizationId.current);
+  const hasMembership = userMemberships.data?.some(
+    membership => membership.organization.id === props.publicOrganizationData.id,
+  );

99-107: Type the component return to reflect possible null.

MembershipPreview can return null until isLoaded. Add the explicit union type.

-const MembershipPreview = (props: { organization: OrganizationResource }) => {
+const MembershipPreview = (props: { organization: OrganizationResource }): JSX.Element | null => {

135-139: Type the component return to reflect possible null.

InvitationPreview may early-return null due to the dedup guard. Add explicit union type.

-const InvitationPreview = (props: UserOrganizationInvitationResource) => {
+const InvitationPreview = (props: UserOrganizationInvitationResource): JSX.Element | null => {

145-163: Consider setting userMemberships cache after accept to avoid UI gaps.

You update invitations in-place (great). For a smoother UX after accept (and to complement the dedup), consider also pushing a synthetic membership into userMemberships cache or triggering a targeted revalidation for memberships in this scoped screen. This keeps the list consistent without waiting for the global revalidation effect.

I can sketch a small cache update helper mirroring populateCacheUpdateItem for memberships if helpful.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • 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 3a8505b and be0dcc1.

📒 Files selected for processing (2)
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (6 hunks)
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx (4 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
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/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
**/*.{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/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.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/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.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/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.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/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx
  • packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx
🧬 Code Graph Analysis (2)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx (1)
packages/clerk-js/src/ui/elements/FormContainer.tsx (1)
  • FormContainer (20-61)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (7)
packages/clerk-js/src/ui/elements/contexts/index.tsx (1)
  • useCardState (42-70)
packages/clerk-js/src/ui/hooks/useOrganizationListInView.ts (1)
  • useOrganizationListInView (9-34)
packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx (1)
  • MembershipPreview (13-39)
packages/clerk-js/src/ui/components/OrganizationList/UserInvitationList.tsx (1)
  • InvitationPreview (26-64)
packages/types/src/organization.ts (1)
  • OrganizationResource (42-79)
packages/clerk-js/src/ui/utils/errorHandler.ts (1)
  • handleError (69-91)
packages/types/src/userOrganizationInvitation.ts (1)
  • UserOrganizationInvitationResource (24-40)
⏰ 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). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/CreateOrganizationScreen.tsx (1)

77-78: Padding shift from Form.Root to FormContainer looks good.

This aligns with our Card/FormContainer layout patterns; header padding + container padding reads consistent with other screens.

packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (1)

54-55: Nice: Card.Alert surfaces card-level errors inline.

Good use of useCardState + Card.Alert with spacing, keeping error handling consistent across the flow.

@LauraBeatris LauraBeatris changed the title fix(clerk-js): Apply revalidation of memberships for task component fix(clerk-js): Add error handling for setActive with stale organization data Aug 15, 2025
@LauraBeatris LauraBeatris marked this pull request as ready for review August 15, 2025 13:34
@@ -128,6 +132,9 @@ export const OrganizationListPageList = (props: { onCreateOrganizationClick: ()
const hasNextPage = userMemberships?.hasNextPage || userInvitations?.hasNextPage || userSuggestions?.hasNextPage;

const onCreateOrganizationClick = () => {
// Clean error originated from the list when switching to form
Copy link
Member Author

Choose a reason for hiding this comment

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

Suggested change
// Clean error originated from the list when switching to form
// Clear error originated from the list when switching to form

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

♻️ Duplicate comments (3)
packages/clerk-js/src/ui/components/OrganizationList/OrganizationListPage.tsx (2)

124-137: Nice touch clearing list-originated errors when switching to the form.

The explicit card.setError(undefined) prevents stale errors leaking into the create flow.


169-171: Harden count access with optional chaining to avoid edge-case crashes.

For consistency with the rest of the codebase and past fixes, guard userMemberships.count with optional chaining and a nullish default. Same for hasNextPage checks if needed.

Apply this diff:

-            {(userMemberships.count || 0) > 0 &&
+            {(userMemberships?.count ?? 0) > 0 &&
               userMemberships.data?.map(inv => {
                 return (
                   <MembershipPreview
                     key={inv.id}
                     {...inv}
                   />
                 );
               })}
 
-            {!userMemberships.hasNextPage &&
+            {!userMemberships?.hasNextPage &&
               userInvitationsData?.map(inv => {
                 return (
                   <InvitationPreview
                     key={inv.id}
                     {...inv}
                   />
                 );
               })}
 
-            {!userMemberships.hasNextPage &&
-              !userInvitations.hasNextPage &&
+            {!userMemberships?.hasNextPage &&
+              !userInvitations?.hasNextPage &&
               userSuggestionsData?.map(inv => {
                 return (
                   <SuggestionPreview
                     key={inv.id}
                     {...inv}
                   />
                 );
               })}

Also applies to: 179-191

packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (1)

148-151: Use the server-returned organization id after accept (more robust against drift)

Rely on the updated item from accept() (source of truth) when fetching the Organization resource. This avoids any drift with stale props.

-          const updatedItem = await props.accept();
-          const organization = await getOrganization(props.publicOrganizationData.id);
+          const updatedItem = await props.accept();
+          const organizationId = updatedItem.publicOrganizationData.id || props.publicOrganizationData.id;
+          const organization = await getOrganization(organizationId);
🧹 Nitpick comments (45)
packages/localizations/src/es-MX.ts (1)

867-867: Add es-MX translation for the new error key (avoid leaving it undefined).

Provide a user-facing message consistent with en-US so users don’t see a blank. Suggested translation:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Ya no eres miembro de esta organización. Actualiza la página para intentarlo de nuevo.',
packages/localizations/src/cs-CZ.ts (1)

867-867: Add cs-CZ translation for the new error key.

Setting this to a proper string keeps UX consistent across locales:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Už nejste členem této organizace. Obnovte stránku a zkuste to znovu.',
packages/localizations/src/hr-HR.ts (1)

864-864: Add hr-HR translation for the new error key.

Suggested translation:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Više niste član ove organizacije. Osvježite stranicu i pokušajte ponovno.',
packages/localizations/src/ja-JP.ts (1)

859-859: Add ja-JP translation for the new error key.

Suggested translation:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'この組織のメンバーではなくなりました。ページを更新して、もう一度お試しください。',
packages/types/src/localization.ts (1)

1332-1332: Add tests for stale-organization error handling in setActive flows.

Given the PR intent (handling /touch and /tokens failures when org data is stale), add unit/integration tests asserting:

  • setActive propagates the new organization_not_found_or_unauthorized error.
  • UI surfaces Card.Alert (or equivalent) and recovers appropriately in OrganizationList and TaskChooseOrganization.
  • State is reset when the org no longer exists.

I can help draft test cases if useful.

packages/localizations/src/es-ES.ts (1)

862-862: Add Spanish translation instead of undefined

Prevents fallback and aligns with tone used elsewhere in es-ES.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'No se ha encontrado la organización o no tienes permiso para acceder.',
packages/localizations/src/da-DK.ts (1)

856-856: Add Danish translation instead of undefined

Keeps error messages localized for stale-organization setActive errors.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Organisationen blev ikke fundet, eller du har ikke adgang.',
packages/localizations/src/es-UY.ts (1)

870-870: Add es-UY translation using voseo (consistent with the locale)

Matches the voseo tone used across es-UY (e.g., “Ingresá”, “tenés”).

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'No se encontró la organización o no tenés permiso para acceder.',
packages/localizations/src/ru-RU.ts (1)

873-873: Add Russian translation instead of undefined

Improves error clarity for RU users without falling back to en-US.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Организация не найдена или у вас нет доступа.',
packages/localizations/src/tr-TR.ts (1)

861-862: New error key added; placeholder is fine — please queue Turkish translation

The addition of organization_not_found_or_unauthorized under unstable__errors is correct and aligns with the new typing. For a better UX, consider adding a Turkish translation in a follow-up; keeping it undefined to fall back to en-US in the meantime is acceptable if that’s the project’s policy.

If helpful, I can open a follow-up task to coordinate translations across locales and confirm fallback behavior at runtime.

packages/localizations/src/ar-SA.ts (1)

856-857: Add Arabic translation or confirm fallback policy

organization_not_found_or_unauthorized was added in the right section. Please add an Arabic translation when available. If the intended behavior is to fall back to en-US for missing strings, leaving this as undefined is fine short-term.

I can help prepare a translation handoff note and verify that UI surfaces this error via the new setActive handling.

packages/localizations/src/vi-VN.ts (1)

865-866: Missing Vietnamese translation for new error key

Good addition of organization_not_found_or_unauthorized. To complete the locale, please provide a Vietnamese translation when feasible; otherwise, confirm fallback to en-US is acceptable until localization is ready.

I can draft candidate copy and route it to a native speaker for review if that helps.

packages/localizations/src/it-IT.ts (1)

867-868: Italian translation missing for new error key

organization_not_found_or_unauthorized is correctly added. Please add the Italian copy when available, or confirm fallback to en-US until the translation is ready.

I can open a small follow-up to collect and add translations for all locales introduced in this PR.

packages/localizations/src/kk-KZ.ts (1)

848-848: Confirm type definition and namespace placement for organization_not_found_or_unauthorized

  • Ensure the UnstableErrors interface in packages/types/src/localization.ts includes this key.
  • Verify that both packages/localizations/src/en-US.ts and kk-KZ.ts nest the key under the unstable__errors block.
  • If you intend to rely on the English fallback, please confirm the UI picks up the en-US string correctly.
  • Otherwise, add the Kazakh translation:
-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Ұйым табылмады немесе қол жеткізуге рұқсат жоқ.',
packages/localizations/src/pl-PL.ts (1)

867-867: Add a proper Polish translation for organization_not_found_or_unauthorized

Avoid leaving this new key undefined; provide a localized message to improve UX and consistency with en-US.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Nie należysz już do tej organizacji. Odśwież stronę i spróbuj ponownie.',
packages/localizations/src/fr-FR.ts (1)

869-869: Translate organization_not_found_or_unauthorized for fr-FR

Provide a clear French message instead of relying on fallback.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Vous n’êtes plus membre de cette organisation. Actualisez la page pour réessayer.',
packages/localizations/src/te-IN.ts (1)

869-869: Add Telugu translation for the new error key

Improve UX by avoiding undefined and presenting a native-language message.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'మీరు ఇకపై ఈ సంస్థకు సభ్యుడు కాదు. మళ్లీ ప్రయత్నించడానికి పేజీని రిఫ్రెష్ చేయండి.',
packages/localizations/src/fi-FI.ts (1)

859-859: Fill in Finnish translation for organization_not_found_or_unauthorized

Set a concise, user-friendly message aligned with the en-US intent.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Et ole enää tämän organisaation jäsen. Päivitä sivu ja yritä uudelleen.',
packages/localizations/src/id-ID.ts (1)

868-868: Add translation for organization_not_found_or_unauthorized or explicitly rely on en-US fallback

The new key is correctly added under unstable__errors. If leaving it undefined is intentional, please confirm the fallback path and track translation follow-up. This ensures consistent UX when the stale-organization error is surfaced.

I can propose an Indonesian phrasing aligned with the en-US intent if you’d like to include it in this PR.

packages/localizations/src/sk-SK.ts (1)

865-865: Key added in the right namespace; translation pending

organization_not_found_or_unauthorized is in unstable__errors, which matches the types. Consider adding a Slovak translation now or confirm fallback to en-US until the locale is completed.

Happy to provide a suggested Slovak translation consistent with existing tone and terminology.

packages/localizations/src/hi-IN.ts (1)

868-868: Provide a Hindi translation or confirm fallback

The key is correctly placed under unstable__errors. To avoid mixed-language UI, prefer adding a Hindi string now. If not, please confirm fallback to the base locale and add this to the localization backlog.

If helpful, I can draft a Hindi string aligned with the en-US base message and your existing tone.

packages/localizations/src/sr-RS.ts (1)

858-858: Correct placement; consider adding a Serbian translation

Good placement under unstable__errors. If undefined is a temporary placeholder, ensure there’s a tracked task to add the Serbian string or rely on en-US fallback in the interim.

I can supply a Serbian phrasing consistent with the rest of this file if you want to include it now.

packages/localizations/src/bg-BG.ts (1)

856-856: Optional: provide a Bulgarian translation to avoid fallback to en-US

If you’d like to ship a translation now instead of leaving undefined, consider:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Организацията не е намерена или нямате необходимите права.',
packages/localizations/src/es-CR.ts (1)

867-867: Optional: add a Spanish (CR) translation now

Providing the translation avoids relying on base-locale fallback:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'La organización no existe o no tienes autorización.',
packages/localizations/src/ko-KR.ts (1)

852-852: Optional: add a Korean translation now

If preferred, add the translation to reduce fallback usage:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: '조직을 찾을 수 없거나 권한이 없습니다.',
packages/localizations/src/bn-IN.ts (1)

867-867: Optional: add a Bengali translation now

Suggested translation to avoid fallback:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'সংগঠনটি খুঁজে পাওয়া যায়নি বা আপনার অনুমতি নেই।',
packages/localizations/src/is-IS.ts (1)

862-862: Optional: add an Icelandic translation now

You can localize it now if desired:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Samtök fundust ekki eða þú hefur ekki heimild.',
packages/localizations/src/mn-MN.ts (1)

859-859: Provide a Mongolian translation for organization_not_found_or_unauthorized

Leaving this as undefined will fall back to the default locale. Since this error is user-facing, consider adding a localized string.

Proposed translation:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Та энэ байгууллагын гишүүн биш болсон байна. Дахин оролдохын тулд хуудсыг шинэчилнэ үү.',
packages/localizations/src/zh-CN.ts (1)

843-843: Add Simplified Chinese translation for organization_not_found_or_unauthorized

This improves UX by avoiding fallback to English for a common stale-organization error.

Suggested translation:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: '您已不再是该组织的成员。请刷新页面后重试。',
packages/localizations/src/el-GR.ts (1)

861-861: Add Greek translation for organization_not_found_or_unauthorized

Set a localized, user-friendly message instead of leaving it undefined.

Suggested translation:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Δεν είστε πλέον μέλος αυτού του οργανισμού. Ανανεώστε τη σελίδα και δοκιμάστε ξανά.',
packages/localizations/src/hu-HU.ts (1)

859-859: Add Hungarian translation for organization_not_found_or_unauthorized

Use an informal tone to match the existing locale style.

Suggested translation:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Már nem vagy tagja ennek a szervezetnek. Kérlek frissítsd az oldalt, majd próbáld újra.',
packages/localizations/src/uk-UA.ts (1)

855-855: Provide a Ukrainian translation for the newly added unstable__errors key.

A concrete translation aligns with the rest of the file and avoids English fallback.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Ви більше не є учасником цієї організації. Оновіть сторінку та спробуйте ще раз.',
packages/localizations/src/nl-NL.ts (1)

858-858: Fill in the Dutch translation for organization_not_found_or_unauthorized.

Keeps UX consistent and avoids en-US fallback at runtime.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Je bent geen lid meer van deze organisatie. Vernieuw de pagina en probeer het opnieuw.',
packages/localizations/src/zh-TW.ts (1)

843-843: Add Traditional Chinese translation for the new error key.

Replacing undefined with a localized string improves clarity for zh-TW users.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: '您已不再是此組織的成員。請重新整理頁面後再試一次。',
packages/localizations/src/he-IL.ts (1)

849-849: Provide a Hebrew translation for organization_not_found_or_unauthorized.

This keeps the locale complete and avoids fallback strings.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'אינך חבר עוד בארגון זה. רענן את העמוד ונסה שוב.',
packages/localizations/src/sv-SE.ts (1)

861-862: Add missing Swedish translation for new error key.

The new key is undefined. Suggest adding a clear Swedish translation to keep parity with en-US/pt-BR and surface helpful messaging in UI.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Du är inte längre medlem i den här organisationen. Uppdatera sidan och försök igen.',
packages/localizations/src/pt-BR.ts (1)

872-874: Minor PT-BR punctuation fix for natural tone.

Add a comma after “Por favor,” for correct punctuation.

Apply this diff:

-      'Você não é mais parte dessa organização. Por favor atualize a página para tentar novamente.',
+      'Você não é mais parte dessa organização. Por favor, atualize a página para tentar novamente.',
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/index.tsx (1)

105-107: Avoid double-wrapping withCardStateProvider.

You’re wrapping both TaskChooseOrganizationFlows (Line 91) and the exported TaskChooseOrganizationInternal with withCardStateProvider. The inner flows are the only ones that use card state here, so the outer wrapper is redundant.

Apply this diff:

-export const TaskChooseOrganization = withCoreSessionSwitchGuard(
-  withTaskGuard(withCardStateProvider(TaskChooseOrganizationInternal)),
-);
+export const TaskChooseOrganization = withCoreSessionSwitchGuard(
+  withTaskGuard(TaskChooseOrganizationInternal),
+);
packages/clerk-js/src/ui/components/OrganizationList/OrganizationListPage.tsx (3)

97-104: Render Card.Alert conditionally to avoid empty space when there’s no error.

Currently the alert renders unconditionally with possibly no content.

Apply this diff:

-        <>
-          <Card.Alert sx={t => ({ margin: `${t.space.$none} ${t.space.$5}` })}>{card.error}</Card.Alert>
+        <>
+          {card.error && (
+            <Card.Alert sx={t => ({ margin: `${t.space.$none} ${t.space.$5}` })}>{card.error}</Card.Alert>
+          )}

164-165: Render Card.Alert conditionally to avoid layout gaps.

Mirror the pattern suggested above for the list view alert.

Apply this diff:

-      <Card.Alert sx={t => ({ margin: `${t.space.$none} ${t.space.$5}` })}>{card.error}</Card.Alert>
+      {card.error && (
+        <Card.Alert sx={t => ({ margin: `${t.space.$none} ${t.space.$5}` })}>{card.error}</Card.Alert>
+      )}

51-84: Tests suggestion: cover per-flow Card error display and clearing.

No tests were added in this PR. Recommend adding UI tests to assert:

  • Card.Alert shows localized text when a mocked organization_not_found_or_unauthorized error is set via card.setError.
  • Switching from list to create flow clears the error (no alert rendered).
  • After successful organization creation, the flow returns to list and no stale error is displayed.

I can scaffold React Testing Library tests that mock the hooks (useOrganizationListInView/useCardState) and verify the behavior. Want me to open a follow-up PR with a test suite?

packages/clerk-js/src/ui/components/OrganizationList/UserMembershipList.tsx (2)

60-71: Mirror error handling in PersonalAccountPreview to avoid silent failures

Personal account activation still lacks try/catch + handleError. For consistency and better UX, surface errors here too.

Apply:

   const handlePersonalClicked = () => {
     if (!isLoaded) {
       return;
     }
     return card.runAsync(async () => {
-      await setActive({
-        organization: null,
-      });
-
-      await navigateAfterSelectPersonal(user);
+      try {
+        await setActive({
+          organization: null,
+        });
+        await navigateAfterSelectPersonal(user);
+      } catch (err) {
+        handleError(err, [], card.setError);
+      }
     });
   };

14-14: Add an explicit return type to exported component (nitpick)

To match our TS guidelines for public APIs.

-export const MembershipPreview = (props: { organization: OrganizationResource }) => {
+export const MembershipPreview = (props: { organization: OrganizationResource }): JSX.Element | null => {
packages/clerk-js/src/ui/components/SessionTasks/tasks/TaskChooseOrganization/ChooseOrganizationScreen.tsx (2)

33-33: Add an explicit return type to exported component (nitpick)

Bring this in line with our TS guideline for public APIs.

-export const ChooseOrganizationScreen = ({ onCreateOrganizationClick }: ChooseOrganizationScreenProps) => {
+export const ChooseOrganizationScreen = ({ onCreateOrganizationClick }: ChooseOrganizationScreenProps): JSX.Element => {

47-96: Add tests for stale-organization error handling and UI surfacing

No tests were added. Please add coverage to ensure:

  • setActive failures (e.g., organization not found/unauthorized on /touch or /tokens) route through handleError and display via Card.Alert.
  • Accepting an invitation then rendering MembershipPreview behaves as expected (including the fallback to server-returned org id).
  • Pagination guardrails still render items in correct order with the falsy-filtering in place.

I can help scaffold tests with mocked useOrganizationList, handleError, and Card context if useful.

@@ -861,6 +861,7 @@ export const beBY: LocalizationResource = {
organization_domain_exists_for_enterprise_connection: undefined,
organization_membership_quota_exceeded: 'Квота ўдзельнікаў арганізацыі перавышана.',
organization_minimum_permissions_needed: 'Патрабуюцца мінімальныя правы доступу.',
organization_not_found_or_unauthorized: undefined,
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Provide a Belarusian translation instead of undefined

Filling in this key helps users understand stale/unauthorized org state without falling back to English.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Вы больш не з’яўляецеся членам гэтай арганізацыі. Абнавіце старонку і паспрабуйце яшчэ раз.',

To ensure we didn’t miss this key in other locales and to track which locales still have it undefined, run:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locales missing the key:"
fd -t f -e ts '' packages/localizations/src | while read -r f; do
  if ! rg -nq '\borganization_not_found_or_unauthorized\b' "$f"; then
    echo "  MISSING: $f"
  fi
done

echo
echo "Locales where the key is present but still undefined:"
rg -n "organization_not_found_or_unauthorized:\s*undefined" packages/localizations/src | sed 's/^/  /'

Length of output: 10812


Provide Belarusian translation for organization_not_found_or_unauthorized

Replace the undefined value in
packages/localizations/src/be-BY.ts:864

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Вы больш не з’яўляецеся членам гэтай арганізацыі. Абнавіце старонку і паспрабуйце яшчэ раз.',

Script output also flags other files:

• Non-locale files (can be ignored unless you intended to export this key there):
– packages/localizations/src/index.ts
– packages/localizations/src/utils/enUS_v4.ts
– packages/localizations/src/utils/generate.ts
– packages/localizations/src/utils/utils.ts

• Locale files where the key is present but still undefined (≈42):
bn-IN.ts, zh-TW.ts, zh-CN.ts, vi-VN.ts, uk-UA.ts, tr-TR.ts, te-IN.ts, ta-IN.ts, sv-SE.ts,
bg-BG.ts, sr-RS.ts, ru-RU.ts, sk-SK.ts, pt-PT.ts, pl-PL.ts, nl-BE.ts, nl-NL.ts, ro-RO.ts,
ms-MY.ts, mn-MN.ts, nb-NO.ts, th-TH.ts, it-IT.ts, kk-KZ.ts, ko-KR.ts, id-ID.ts, hr-HR.ts,
hu-HU.ts, he-IL.ts, hi-IN.ts, is-IS.ts, fr-FR.ts, ja-JP.ts, fi-FI.ts, fa-IR.ts, es-ES.ts,
es-UY.ts, es-CR.ts, en-GB.ts, el-GR.ts, es-MX.ts, ca-ES.ts, da-DK.ts, cs-CZ.ts, ar-SA.ts, de-DE.ts

Please update the Belarusian string as shown and coordinate filling in translations for the other locales.

🤖 Prompt for AI Agents
In packages/localizations/src/be-BY.ts around line 864, the key
organization_not_found_or_unauthorized is set to undefined; replace it with the
Belarusian translation string "Арганізацыя не знойдзена або доступ не дазволены"
(as a proper string literal), keeping surrounding syntax intact and running the
localization lint/checks; also flag the other locale files listed for
translators to fill similarly.

@@ -872,6 +872,7 @@ export const deDE: LocalizationResource = {
'Sie haben Ihr Limit an Organisationsmitgliedschaften einschließlich ausstehender Einladungen erreicht.',
organization_minimum_permissions_needed:
'Es muss mindestens ein Organisationsmitglied mit den erforderlichen Mindestberechtigungen geben.',
organization_not_found_or_unauthorized: undefined,
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Provide an explicit German translation to avoid English fallback

Filling this now improves UX consistency with the rest of de-DE.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Die Organisation wurde nicht gefunden oder Sie haben keine Berechtigung, darauf zuzugreifen.',

To ensure coverage and typing across the repo:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "1) Confirm all locales include the key:"
rg -n "organization_not_found_or_unauthorized" packages/localizations/src | sed 's/^/  /'

echo
echo "2) en-US should NOT be undefined (must be a real string):"
if rg -n "organization_not_found_or_unauthorized:\s*undefined" packages/localizations/src/en-US.ts > /dev/null; then
  echo "  en-US appears undefined (unexpected) — please set a concrete string."
  rg -n -C2 "organization_not_found_or_unauthorized" packages/localizations/src/en-US.ts
  exit 1
else
  echo "  OK: en-US has a concrete value."
fi

echo
echo "3) Type includes the new key:"
rg -n "organization_not_found_or_unauthorized" packages/types/src/localization.ts | sed 's/^/  /'

Length of output: 5480


Provide German translation for organization_not_found_or_unauthorized

  • packages/localizations/src/de-DE.ts (line 875): replace the undefined value with the explicit German string.

Apply this diff:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Die Organisation wurde nicht gefunden oder Sie haben keine Berechtigung, darauf zuzugreifen.',
🤖 Prompt for AI Agents
In packages/localizations/src/de-DE.ts around line 875, the key
organization_not_found_or_unauthorized is set to undefined; replace that
undefined with the appropriate German translation string (e.g., "Organisation
nicht gefunden oder nicht autorisiert") so the localization returns a proper
message; ensure the value is a quoted string and follows the file's existing
formatting conventions.

@@ -855,6 +855,7 @@ export const nbNO: LocalizationResource = {
organization_domain_exists_for_enterprise_connection: undefined,
organization_membership_quota_exceeded: undefined,
organization_minimum_permissions_needed: undefined,
organization_not_found_or_unauthorized: undefined,
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

New error key added; placement looks correct — please add translation or confirm fallback behavior

organization_not_found_or_unauthorized belongs under unstable__errors; the placement here is correct. Leaving it as undefined is acceptable as a placeholder, but please either:

  • provide a Norwegian translation, or
  • confirm that the intended fallback to en-US is in place and tracked to be translated later.

Also, verify that the type declaration includes this key and that en-US defines a concrete string to avoid runtime “missing key” UX.

Run this script to verify the type and base localization coverage and to scan all locales for placement:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "1) Types contain the new key:"
rg -n -C2 'organization_not_found_or_unauthorized' packages/types/src/localization.ts || true

echo -e "\n2) Base localization (en-US) defines the key:"
fd -t f 'en-US.ts' packages/localizations | xargs -I{} rg -n -C2 'organization_not_found_or_unauthorized' {}

echo -e "\n3) Scan all locales for placement and duplicates:"
rg -n -C2 'organization_not_found_or_unauthorized' packages/localizations

Length of output: 27551


organization_not_found_or_unauthorized in nb-NO — translation missing

I’ve verified that:

  • The key organization_not_found_or_unauthorized is declared in packages/types/src/localization.ts.
  • en-US provides a concrete string for this key.
  • In nb-NO (and most other locales) it’s currently set to undefined.

In packages/localizations/src/nb-NO.ts at line 858, please either:

  • Add the Norwegian translation for organization_not_found_or_unauthorized, or
  • Confirm that falling back to en-US is acceptable and ensure the missing translation is tracked for later.
🤖 Prompt for AI Agents
In packages/localizations/src/nb-NO.ts around line 858 the key
organization_not_found_or_unauthorized is set to undefined (missing Norwegian
translation). Replace the undefined with the appropriate Norwegian message
(e.g., a concise translation of "Organization not found or you are not
authorized") or, if you prefer fallback to en-US for now, update the file to
explicitly note the fallback and add a TODO/issue tracking ID so the missing
translation is tracked; after the change, run the localization/compile or linter
step to ensure the file exports valid strings.

@@ -857,6 +857,7 @@ export const roRO: LocalizationResource = {
organization_domain_exists_for_enterprise_connection: undefined,
organization_membership_quota_exceeded: undefined,
organization_minimum_permissions_needed: undefined,
organization_not_found_or_unauthorized: undefined,
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Add Romanian translation for organization_not_found_or_unauthorized

Provide a localized error to avoid English fallback.

Suggested translation:

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Nu mai sunteți membru al acestei organizații. Reîmprospătați pagina și încercați din nou.',

Optionally verify the new key is present in the base locale and all locales for consistency:


🏁 Script executed:

#!/bin/bash
# List all occurrences of the key across localizations and ensure en-US has a translation.
set -euo pipefail

echo "Searching for occurrences of 'organization_not_found_or_unauthorized'..."
rg -n --type=ts -C2 '\borganization_not_found_or_unauthorized\b' packages/localizations/src

echo
echo "Checking base en-US translation exists..."
rg -n --type=ts -C2 $'unstable__errors:\\s*\\{[\\s\\S]*?organization_not_found_or_unauthorized\\s*:' packages/localizations/src/en-US.ts

echo
echo "Verifying the type includes the key..."
rg -n --type=ts -C2 'organization_not_found_or_unauthorized' packages/types/src/localization.ts

Length of output: 26905


Add Romanian translation for organization_not_found_or_unauthorized
Provide a localized error to avoid English fallback.

File: packages/localizations/src/ro-RO.ts
Line: 860

-    organization_not_found_or_unauthorized: undefined,
+    organization_not_found_or_unauthorized: 'Nu mai sunteți membru al acestei organizații. Reîmprospătați pagina și încercați din nou.',
📝 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
organization_not_found_or_unauthorized: undefined,
organization_not_found_or_unauthorized: 'Nu mai sunteți membru al acestei organizații. Reîmprospătați pagina și încercați din nou.',
🤖 Prompt for AI Agents
In packages/localizations/src/ro-RO.ts around line 860, the key
organization_not_found_or_unauthorized is set to undefined; replace the
undefined with a Romanian translation string (for example: "Organizația nu a
fost găsită sau nu aveți autorizare/permisiuni.") so the error message is
localized and avoids falling back to English.

@@ -1329,4 +1329,5 @@ type UnstableErrors = WithParamName<{
organization_domain_blocked: LocalizationValue;
organization_domain_exists_for_enterprise_connection: LocalizationValue;
organization_membership_quota_exceeded: LocalizationValue;
organization_not_found_or_unauthorized: LocalizationValue;
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Type addition looks correct and aligns locales with the new error key.

Adding organization_not_found_or_unauthorized to UnstableErrors is type-safe and unblocks locale propagation. Please verify all locales include this key and that en-US provides a concrete string (not undefined).

Run this script to verify coverage across locales and confirm en-US has a non-undefined value:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Type definition entry:"
rg -n "organization_not_found_or_unauthorized" packages/types/src/localization.ts -C2 || true

echo
echo "All locale occurrences of the key:"
rg -n "organization_not_found_or_unauthorized" packages/localizations/src -g "*.ts" -C1 || true

echo
echo "Locales still undefined for this key:"
rg -nP "organization_not_found_or_unauthorized:\s*undefined" packages/localizations/src -g "*.ts" | sed 's/:.*//g' | sort | uniq || true

echo
echo "en-US entry (should be a concrete string):"
rg -n "organization_not_found_or_unauthorized" packages/localizations/src/en-US.ts -C1 || true

Length of output: 18861


Missing translations for organization_not_found_or_unauthorized

All locale files include the new key and en-US (as well as pt-BR) provides a concrete message. However, the vast majority of locales still have this entry set to undefined. Please add translations for the following files:

• packages/localizations/src/ar-SA.ts
• packages/localizations/src/be-BY.ts
• packages/localizations/src/bg-BG.ts
• packages/localizations/src/bn-IN.ts
• packages/localizations/src/ca-ES.ts
• packages/localizations/src/cs-CZ.ts
• packages/localizations/src/da-DK.ts
• packages/localizations/src/de-DE.ts
• packages/localizations/src/el-GR.ts
• packages/localizations/src/en-GB.ts
• packages/localizations/src/es-CR.ts
• packages/localizations/src/es-ES.ts
• packages/localizations/src/es-MX.ts
• packages/localizations/src/es-UY.ts
• packages/localizations/src/fa-IR.ts
• packages/localizations/src/fi-FI.ts
• packages/localizations/src/fr-FR.ts
• packages/localizations/src/he-IL.ts
• packages/localizations/src/hi-IN.ts
• packages/localizations/src/hr-HR.ts
• packages/localizations/src/hu-HU.ts
• packages/localizations/src/id-ID.ts
• packages/localizations/src/is-IS.ts
• packages/localizations/src/it-IT.ts
• packages/localizations/src/ja-JP.ts
• packages/localizations/src/kk-KZ.ts
• packages/localizations/src/ko-KR.ts
• packages/localizations/src/mn-MN.ts
• packages/localizations/src/ms-MY.ts
• packages/localizations/src/nb-NO.ts
• packages/localizations/src/nl-BE.ts
• packages/localizations/src/nl-NL.ts
• packages/localizations/src/pl-PL.ts
• packages/localizations/src/pt-PT.ts
• packages/localizations/src/ro-RO.ts
• packages/localizations/src/ru-RU.ts
• packages/localizations/src/sk-SK.ts
• packages/localizations/src/sr-RS.ts
• packages/localizations/src/sv-SE.ts
• packages/localizations/src/ta-IN.ts
• packages/localizations/src/te-IN.ts
• packages/localizations/src/th-TH.ts
• packages/localizations/src/tr-TR.ts
• packages/localizations/src/uk-UA.ts
• packages/localizations/src/vi-VN.ts
• packages/localizations/src/zh-CN.ts
• packages/localizations/src/zh-TW.ts

Once translations are added, re-run the verification script to ensure no undefined values remain.

🤖 Prompt for AI Agents
In packages/types/src/localization.ts around line 1332, the new key
organization_not_found_or_unauthorized is declared but most locale files
referenced in the review (packages/localizations/src/{ar-SA.ts, be-BY.ts,
bg-BG.ts, bn-IN.ts, ca-ES.ts, cs-CZ.ts, da-DK.ts, de-DE.ts, el-GR.ts, en-GB.ts,
es-CR.ts, es-ES.ts, es-MX.ts, es-UY.ts, fa-IR.ts, fi-FI.ts, fr-FR.ts, he-IL.ts,
hi-IN.ts, hr-HR.ts, hu-HU.ts, id-ID.ts, is-IS.ts, it-IT.ts, ja-JP.ts, kk-KZ.ts,
ko-KR.ts, mn-MN.ts, ms-MY.ts, nb-NO.ts, nl-BE.ts, nl-NL.ts, pl-PL.ts, pt-PT.ts,
ro-RO.ts, ru-RU.ts, sk-SK.ts, sr-RS.ts, sv-SE.ts, ta-IN.ts, te-IN.ts, th-TH.ts,
tr-TR.ts, uk-UA.ts, vi-VN.ts, zh-CN.ts, zh-TW.ts}) still set it to undefined;
add an appropriate translated string for organization_not_found_or_unauthorized
in each of those locale files (use en-US/pt-BR message as source/context),
ensure types still satisfy LocalizationValue, commit the updated locale files,
and re-run the localization verification script to confirm no undefined values
remain.

Copy link
Contributor

@NicolasLopes7 NicolasLopes7 left a comment

Choose a reason for hiding this comment

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

:shipit:

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.

5 participants