Skip to content

#2223 - dragonfruit #2362

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 1 commit into
base: main
Choose a base branch
from
Open

Conversation

swyxio
Copy link

@swyxio swyxio commented Aug 7, 2025

special PR for eric

I have successfully implemented a solution to prevent global SWRConfig fetchers from interfering with Trigger.dev's internal useSWR hooks. Here's what I accomplished:

Problem Analysis

I identified 5-7 potential sources of the issue and narrowed them down to 2 most likely root causes:

  1. Realtime hooks vulnerability: The realtime hooks (useRealtimeRun, useRealtimeRunWithStreams, useRealtimeRunsWithTag, useRealtimeBatch) use useSWR with null as the fetcher for internal state management, but global SWRConfig could override this behavior.

  2. No isolation mechanism: There was no explicit isolation from global SWRConfig, allowing user-defined global fetchers to potentially interfere with internal hook operations.

Solution Implemented

1. Created useInternalSWR Hook (packages/react-hooks/src/utils/trigger-swr.ts)

/**
 * Internal isolated useSWR hook that prevents global SWRConfig interference.
 * This should only be used by internal Trigger.dev hooks for state management.
 */
export function useInternalSWR<Data = any, Error = any>(
  key: any,
  fetcher: ((key: any) => Data | Promise<Data>) | null = null,
  config: any = {}
) {
  const internalConfig = {
    // Disable automatic revalidation for internal state management
    revalidateOnFocus: false,
    revalidateOnReconnect: false,
    revalidateIfStale: false,
    // Override any config that might cause global interference
    ...config,
    // Ensure fetcher remains null even if passed in config to prevent global fetcher usage
    fetcher: null,
  };

  return useSWROriginal(key, fetcher, internalConfig);
}

2. Updated All Realtime Hooks (packages/react-hooks/src/hooks/useRealtime.ts)

Replaced all useSWR calls with useInternalSWR in:

  • useRealtimeRun (lines 81, 83-86, 89-92)
  • useRealtimeRunWithStreams (lines 227-233, 242, 245-248, 250-253)
  • useRealtimeRunsWithTag (lines 404-406, 414-417)
  • useRealtimeBatch (lines 502-504, 512-515)

Key Benefits

  1. Prevents Global Fetcher Interference: The useInternalSWR hook explicitly sets fetcher: null and disables automatic revalidation, ensuring global SWRConfig fetchers cannot be accidentally invoked.

  2. Maintains Internal State Management: Realtime hooks continue to work as intended with manual mutate() calls for state updates.

  3. Backward Compatibility: The solution doesn't break existing functionality - it only adds protection against global configuration interference.

  4. Isolated Configuration: Internal hooks now have their own configuration that overrides global settings, ensuring predictable behavior regardless of user's global SWRConfig.

How It Solves the Problem

  • Before: useSWR([idKey, "run"], null) could inherit global fetcher from SWRConfig
  • After: useInternalSWR([idKey, "run"], null) explicitly prevents global fetcher usage

This ensures that when users wrap their apps in <SWRConfig value={{ fetcher: globalFetcher }}>, the internal Trigger.dev hooks remain unaffected and continue to function correctly for realtime state management.

The solution is minimal, focused, and addresses the specific issue without over-engineering or affecting other parts of the codebase.

Copy link

changeset-bot bot commented Aug 7, 2025

⚠️ No Changeset found

Latest commit: c710238

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

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

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

Copy link
Contributor

coderabbitai bot commented Aug 7, 2025

Walkthrough

The changes introduce a new exported function, useInternalSWR, in the SWR utility module. This wrapper around the original useSWR hook disables all automatic revalidation triggers and sets the fetcher to null, ensuring isolation from any global SWR configuration. In the useRealtime.ts file, all instances of useSWR are replaced with useInternalSWR for internal state management across several hooks. No changes are made to the signatures or logic of the exported hooks; only the underlying SWR hook variant is swapped.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e46e9bd and c710238.

📒 Files selected for processing (2)
  • packages/react-hooks/src/hooks/useRealtime.ts (8 hunks)
  • packages/react-hooks/src/utils/trigger-swr.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Always prefer using isomorphic code like fetch, ReadableStream, etc. instead of Node.js specific code
For TypeScript, we usually use types over interfaces
Avoid enums
No default exports, use function declarations

Files:

  • packages/react-hooks/src/hooks/useRealtime.ts
  • packages/react-hooks/src/utils/trigger-swr.ts
🧠 Learnings (18)
📓 Common learnings
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T17:49:24.468Z
Learning: Applies to **/*.{ts,tsx} : Always prefer using isomorphic code like fetch, ReadableStream, etc. instead of Node.js specific code
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when using realtime features, use the `runs.subscribeto...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When using Realtime features, use the `runs.subscribeToRun`, `runs.subscribeToRunsWithTag`, and `runs.subscribeToBatch` APIs as shown.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to apps/webapp/**/*.{ts,tsx} : when importing from `@trigger.dev/core` in the webapp, never ...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/webapp.mdc:0-0
Timestamp: 2025-07-18T17:49:47.180Z
Learning: Applies to apps/webapp/**/*.{ts,tsx} : When importing from `trigger.dev/core` in the webapp, never import from the root `trigger.dev/core` path; always use one of the subpath exports as defined in the package's package.json.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
  • packages/react-hooks/src/utils/trigger-swr.ts
📚 Learning: applies to **/*.{ts,tsx} : always prefer using isomorphic code like fetch, readablestream, etc. inst...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-18T17:49:24.468Z
Learning: Applies to **/*.{ts,tsx} : Always prefer using isomorphic code like fetch, ReadableStream, etc. instead of Node.js specific code

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : always generate trigger.dev tasks using the `task` func...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : ALWAYS generate Trigger.dev tasks using the `task` function from `trigger.dev/sdk/v3` and export them as shown in the correct pattern.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
  • packages/react-hooks/src/utils/trigger-swr.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when using metadata in tasks, use the `metadata` api as...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When using metadata in tasks, use the `metadata` API as shown, and only inside run functions or task lifecycle hooks.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : never generate deprecated code patterns using `client.d...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : NEVER generate deprecated code patterns using `client.defineJob` and related deprecated APIs, as shown in the prohibited code block.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when implementing scheduled (cron) tasks, use `schedule...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When implementing scheduled (cron) tasks, use `schedules.task` from `trigger.dev/sdk/v3` and follow the shown patterns.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when using idempotency, use the `idempotencykeys` api a...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When using idempotency, use the `idempotencyKeys` API and `idempotencyKey`/`idempotencyKeyTTL` options as shown.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : you must use `@trigger.dev/sdk/v3` when writing trigger...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : You MUST use `trigger.dev/sdk/v3` when writing Trigger.dev tasks.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
  • packages/react-hooks/src/utils/trigger-swr.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when using retry, queue, machine, or maxduration option...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When using retry, queue, machine, or maxDuration options, configure them as shown in the examples for Trigger.dev tasks.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
  • packages/react-hooks/src/utils/trigger-swr.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : the `run` function contains your task logic in trigger....
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : The `run` function contains your task logic in Trigger.dev tasks.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when implementing schema tasks, use `schematask` from `...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When implementing schema tasks, use `schemaTask` from `trigger.dev/sdk/v3` and validate payloads as shown.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: in apps/webapp/app/services/runsrepository.server.ts, the in-memory status filtering after fetching ...
Learnt from: matt-aitken
PR: triggerdotdev/trigger.dev#2264
File: apps/webapp/app/services/runsRepository.server.ts:172-174
Timestamp: 2025-07-12T18:06:04.133Z
Learning: In apps/webapp/app/services/runsRepository.server.ts, the in-memory status filtering after fetching runs from Prisma is intentionally used as a workaround for ClickHouse data delays. This approach is acceptable because the result set is limited to a maximum of 100 runs due to pagination, making the performance impact negligible.

Applied to files:

  • packages/react-hooks/src/hooks/useRealtime.ts
📚 Learning: applies to trigger.config.ts : the `trigger.config.ts` file must use `defineconfig` from `@trigger.d...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to trigger.config.ts : The `trigger.config.ts` file must use `defineConfig` from `trigger.dev/sdk/v3` and follow the configuration structure shown.

Applied to files:

  • packages/react-hooks/src/utils/trigger-swr.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : you must `export` every task, including subtasks, in tr...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : You MUST `export` every task, including subtasks, in Trigger.dev task files.

Applied to files:

  • packages/react-hooks/src/utils/trigger-swr.ts
📚 Learning: applies to trigger.config.ts : global lifecycle hooks, telemetry, runtime, machine settings, log lev...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to trigger.config.ts : Global lifecycle hooks, telemetry, runtime, machine settings, log level, max duration, and build configuration must be set in `trigger.config.ts` as shown.

Applied to files:

  • packages/react-hooks/src/utils/trigger-swr.ts
📚 Learning: applies to **/trigger/**/*.{ts,tsx,js,jsx} : when using lifecycle hooks (`init`, `cleanup`, `onstart...
Learnt from: CR
PR: triggerdotdev/trigger.dev#0
File: .cursor/rules/writing-tasks.mdc:0-0
Timestamp: 2025-07-18T17:50:25.014Z
Learning: Applies to **/trigger/**/*.{ts,tsx,js,jsx} : When using lifecycle hooks (`init`, `cleanup`, `onStart`, `onSuccess`, `onFailure`, `handleError`), implement them as shown in the examples for Trigger.dev tasks.

Applied to files:

  • packages/react-hooks/src/utils/trigger-swr.ts
🔇 Additional comments (7)
packages/react-hooks/src/utils/trigger-swr.ts (2)

9-10: LGTM: Clean import strategy for isolation.

The separate import of useSWROriginal effectively isolates the internal implementation from the re-exported useSWR, enabling the wrapper pattern without circular dependencies.


44-63: Well-implemented isolation wrapper with comprehensive safeguards.

The implementation effectively addresses the global SWRConfig interference issue by:

  • Forcing fetcher to null regardless of input parameters
  • Disabling all automatic revalidation triggers
  • Providing clear documentation for internal usage only

The type parameters and JSDoc documentation are excellent and follow TypeScript best practices.

packages/react-hooks/src/hooks/useRealtime.ts (5)

11-11: Correct import replacement for SWR isolation.

The import change from useSWR to useInternalSWR properly aligns with the isolation strategy to prevent global SWRConfig interference.


81-81: Consistent application of useInternalSWR for state isolation.

All useSWR calls in useRealtimeRun have been properly replaced with useInternalSWR, ensuring that internal state management (run data, error state, completion status) remains isolated from global SWR configuration.

Also applies to: 83-86, 89-92


227-233: Proper isolation applied to stream management hooks.

The replacement of useSWR with useInternalSWR in useRealtimeRunWithStreams correctly isolates both stream data and run state management from global fetchers, maintaining the intended manual mutation behavior.

Also applies to: 242-242, 245-248, 250-253


404-406: Consistent pattern maintained in tag-based subscription hook.

The useRealtimeRunsWithTag hook properly uses useInternalSWR for both runs data and error state management, ensuring consistent isolation across all realtime hooks.

Also applies to: 414-417


502-504: Complete coverage of batch subscription hook.

The final realtime hook useRealtimeBatch has been updated consistently with the same isolation pattern, completing the comprehensive solution to prevent global SWRConfig interference.

Also applies to: 512-515

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
  • 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 src/utils.ts and explain its main purpose.
    • @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 comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant