Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Nov 5, 2025

Description

Introduced a generateTabId helper in MemoryTokenCache so each tab instance gets a stable random identifier, stored once per cache and reused across BroadcastChannel interactions. The ID is threaded through the existing debug logging paths to make multi-tab token updates easier to trace.

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

  • Chores
    • Improved internal diagnostics and logging to include a stable per-tab identifier, enabling clearer cross-tab tracing of token broadcast activity and better troubleshooting of multi-tab session behavior. This is a non-functional change with no public API modifications.

✏️ Tip: You can customize this high-level summary in your review settings.

@changeset-bot
Copy link

changeset-bot bot commented Nov 5, 2025

🦋 Changeset detected

Latest commit: 07d9531

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

This PR includes changesets to release 3 packages
Name Type
@clerk/clerk-js Patch
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch

Not sure what this means? Click here to learn what changesets are.

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

@vercel
Copy link

vercel bot commented Nov 5, 2025

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

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 5, 2025

Walkthrough

A per-instance tab identifier (tabId) is introduced and threaded through logging and broadcast paths in the token cache for cross-tab diagnostic tracing. The broadcast payload structure remains unchanged while diagnostic telemetry gains tabId context.

Changes

Cohort / File(s) Change Summary
Token cache tab identification
packages/clerk-js/src/core/tokenCache.ts
Adds tabId generation via generateTabId() and stores it in MemoryTokenCache. Threads tabId through token mismatch warnings, validation failure logs, entry comparison diagnostics, broadcast update warnings, and broadcast logging to enable cross-tab tracing without altering the broadcast payload.
Release changeset
.changeset/steady-tabs-log.md
Adds a patch changeset documenting the addition of a stable per-instance tab identifier in MemoryTokenCache for tracing multi-tab token broadcasts.

Sequence Diagram

sequenceDiagram
    participant Instance as Token Cache<br/>(Instance)
    participant Log as Diagnostic<br/>Logging
    participant Broadcast as Broadcast<br/>Channel

    rect rgb(245, 250, 255)
    Note over Instance: Initialization
    Instance->>Instance: Generate tabId
    Instance->>Instance: Store in MemoryTokenCache
    end

    rect rgb(245, 250, 255)
    Note over Instance: Token Operations
    Instance->>Log: Log token mismatch (includes tabId)
    Instance->>Log: Log validation failure (includes tabId)
    Instance->>Log: Log entry comparison (includes tabId)
    end

    rect rgb(245, 250, 255)
    Note over Instance: Broadcasting
    Instance->>Broadcast: Send token update (payload unchanged)
    Note over Log: Log broadcast event (includes tabId)
    Broadcast->>Instance: Receive broadcast
    Note over Log: Record tabId in decision logging
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas to focus:
    • Ensure generateTabId() yields stable, unique identifiers per instance and lifecycle.
    • Verify tabId is consistently included in all logging and diagnostic branches.
    • Confirm broadcast payload remains unchanged and backward compatible.
    • Check edge cases around instance recreation, garbage collection, or multiple caches per tab.

Poem

A rabbit hops through tabs so wide,
With tabId as its trusty guide,
Each broadcast logged with whisker-traced,
Cross-tab diagnostics interlaced! 🐰✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat(clerk-js): Enhance BroadcastChannel logging' accurately reflects the main objective of adding a stable tab identifier (tabId) for enhanced traceability in multi-tab BroadcastChannel interactions, which is the primary focus of the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/enhance-cross-tab-sync-logging

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9ad7eb4 and 07d9531.

📒 Files selected for processing (1)
  • .changeset/steady-tabs-log.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/steady-tabs-log.md
⏰ 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). (23)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (nextjs, chrome, 15, RQ)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (elements, chrome)

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

134-136: Consider adding explicit return type annotation.

The generateTabId function lacks an explicit return type. While TypeScript can infer : string, adding it explicitly improves code clarity and aligns with the coding guideline for explicit return types.

-const generateTabId = (): string => {
+const generateTabId = (): string => {
   return Math.random().toString(36).slice(2);
 };

Note: The current implementation without the explicit type is already valid, but the explicit annotation is a best practice.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 79c8dc7 and 9ad7eb4.

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

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

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

Files:

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

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

Use Prettier for consistent code formatting

Files:

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

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

TypeScript is required for all packages

Files:

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

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

Packages should export TypeScript types alongside runtime code

Files:

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

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

Use proper TypeScript error types

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

Files:

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

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

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

Files:

  • packages/clerk-js/src/core/tokenCache.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). (5)
  • GitHub Check: check-major-bump
  • GitHub Check: pr-title-lint
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/clerk-js/src/core/tokenCache.ts (1)

145-145: LGTM! Tab identifier successfully integrated for diagnostic tracing.

The per-instance tabId is properly initialized and consistently threaded through all relevant logging paths. This enhancement will significantly improve cross-tab diagnostic capabilities by:

  • Identifying which tab generated or received each broadcast event
  • Tracing token updates across multiple tabs using the existing traceId + new tabId
  • Debugging race conditions and timing issues in multi-tab scenarios

The implementation correctly keeps tabId out of the broadcast payload itself (SessionTokenEvent), using it only for local diagnostic logging, which avoids any protocol changes.

Also applies to: 221-221, 236-236, 247-247, 261-261, 270-270, 280-280, 372-372

@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 5, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 07d9531

@blacksmith-sh
Copy link

blacksmith-sh bot commented Nov 5, 2025

Found 2 test failures on Blacksmith runners:

Test View Logs
[chrome] › integration/tests/elements/
otp.test.ts:135:9 › OTP @elements › long-running--elements.next.appRouter › Type: segme
nted-otp › should replace selected segment with new input
View Logs
[chrome] › integration/tests/elements/
otp.test.ts:196:9 › OTP @elements › long-running--elements.next.appRouter › Type: segme
nted-otp › should forward-delete char when pressing delete
View Logs


Fix in Cursor

@jacekradko jacekradko merged commit 77e022f into main Nov 20, 2025
44 of 45 checks passed
@jacekradko jacekradko deleted the feat/enhance-cross-tab-sync-logging branch November 20, 2025 17:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants