Skip to content

Conversation

@orionmiz
Copy link
Collaborator

@orionmiz orionmiz commented Aug 1, 2025

No description provided.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Aug 1, 2025

Deploying stackflow-demo with  Cloudflare Pages  Cloudflare Pages

Latest commit: 7726c76
Status: ✅  Deploy successful!
Preview URL: https://f4d7e0d0.stackflow-demo.pages.dev
Branch Preview URL: https://lazy-activity.stackflow-demo.pages.dev

View logs

@changeset-bot
Copy link

changeset-bot bot commented Aug 1, 2025

🦋 Changeset detected

Latest commit: 7726c76

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

This PR includes changesets to release 1 package
Name Type
@stackflow/react Minor

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

@coderabbitai
Copy link

coderabbitai bot commented Aug 1, 2025

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Added support for lazy-loaded activities on React 18–19; navigation now waits for components to load, improving transition reliability.
  • Bug Fixes
    • More predictable behavior when the animation option is undefined, preventing unintended animation states.
  • Chores
    • Prepared a minor release for @stackflow/react.

Walkthrough

Adds a new internal React plugin that detects React.lazy and memoized activity components, pauses navigation while unresolved lazy components load, and conditionally registers the plugin for React major versions 18–19; includes a changeset for a minor @stackflow/react release.

Changes

Cohort / File(s) Change Summary
Lazy Activity Plugin Implementation
integrations/react/src/stable/lazyActivityPlugin.ts
New file: adds lazyActivityPlugin(activityComponentMap) which detects React lazy/memo components, tracks load status, pauses navigation on onBeforePush/onBeforeReplace while awaiting the component's loading promise, and resumes navigation after resolve/reject.
Plugin Registration & Setup
integrations/react/src/stable/stackflow.tsx
Modified plugin initialization: normalizes and types incoming plugins array, imports React version, conditionally appends lazyActivityPlugin(activityComponentMap) when React major version is 18–19, and tightened parsing of animate in action options.
Changeset / Release Note
.changeset/small-rice-listen.md
New changeset added declaring a minor release for @stackflow/react documenting the lazy activity support addition.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Stackflow
    participant LazyPlugin as lazyActivityPlugin
    participant ReactLazy as ReactLazyComponent

    User->>Stackflow: request navigation (push/replace)
    Stackflow->>LazyPlugin: onBeforePush/onBeforeReplace
    LazyPlugin->>ReactLazy: inspect activity component (lazy/memo)
    alt component is lazy and uninitialized
        LazyPlugin->>Stackflow: pause navigation
        LazyPlugin->>ReactLazy: start loading (invoke promise)
        ReactLazy-->>LazyPlugin: promise resolves / rejects
        LazyPlugin->>Stackflow: resume navigation
    else not lazy or already loaded
        LazyPlugin->>Stackflow: allow navigation to continue
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 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.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 8823102 and 7726c76.

📒 Files selected for processing (1)
  • integrations/react/src/stable/stackflow.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • integrations/react/src/stable/stackflow.tsx
⏰ 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: Workers Builds: stackflow-docs
  • GitHub Check: Build all packages
  • GitHub Check: Check whether the written test passes normally
  • GitHub Check: Check the TypeScript typings
  • GitHub Check: Create PR or release packages
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch lazy-activity

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

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.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Aug 1, 2025

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
stackflow-docs 7726c76 Commit Preview URL Aug 20 2025, 06:45 AM

@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 1, 2025

@stackflow/demo

yarn add https://pkg.pr.new/@stackflow/[email protected]

commit: 7726c76

@orionmiz orionmiz changed the title feat(react): add lazy activity plugin for stable version feat(react): support lazy activity plugin Aug 4, 2025
@orionmiz orionmiz changed the title feat(react): support lazy activity plugin feat(react): support lazy activity with internal plugin Aug 4, 2025
@orionmiz orionmiz marked this pull request as ready for review August 4, 2025 03:30
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
integrations/react/src/stable/lazyActivityPlugin.ts (2)

43-46: Consider using an enum for status constants

The status constants would be more maintainable and type-safe as an enum:

-const Uninitialized = -1;
-const Pending = 0;
-const Resolved = 1;
-const Rejected = 2;
+enum LazyStatus {
+  Uninitialized = -1,
+  Pending = 0,
+  Resolved = 1,
+  Rejected = 2,
+}

Then update the type definitions to use the enum:

-type UninitializedPayload<T> = {
-  _status: -1;
+type UninitializedPayload<T> = {
+  _status: LazyStatus.Uninitialized;

126-133: Add error logging for failed lazy loading

When lazy loading fails, the navigation is resumed but the error is silently swallowed. This could make debugging difficult.

       Activity._payload._result().then(
         () => {
           actions.resume();
         },
-        () => {
+        (error) => {
+          console.error(`Failed to load lazy activity "${actionParams.activityName}":`, error);
           actions.resume();
         },
       );
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7db7958 and 6b8fa40.

📒 Files selected for processing (3)
  • .changeset/small-rice-listen.md (1 hunks)
  • integrations/react/src/stable/lazyActivityPlugin.ts (1 hunks)
  • integrations/react/src/stable/stackflow.tsx (2 hunks)
⏰ 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). (1)
  • GitHub Check: Workers Builds: stackflow-docs
🔇 Additional comments (4)
integrations/react/src/stable/lazyActivityPlugin.ts (1)

137-146: Well-structured plugin implementation

Good use of the factory pattern and code reuse by extracting the common logic to handleLazyActivity.

integrations/react/src/stable/stackflow.tsx (2)

23-23: Import statement looks good


144-149: Strategic plugin placement ensures compatibility

Placing the lazyActivityPlugin at the end of the plugins array is a good design choice. This ensures user plugins execute first and can potentially modify the activity map before lazy loading logic runs.

.changeset/small-rice-listen.md (1)

1-5: Appropriate changeset documentation

The minor version bump is correct for this new feature addition, and the description clearly communicates the change.

Comment on lines +4 to +6
// https://github.com/facebook/react/blob/v19.1.1/packages/shared/ReactSymbols.js#L32
const REACT_LAZY_TYPE: symbol = Symbol.for("react.lazy");
const REACT_MEMO_TYPE: symbol = Symbol.for("react.memo");
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider the risks of using React internals

Using React's internal symbols (react.lazy and react.memo) makes this implementation fragile. These symbols are not part of React's public API and could change in future versions without notice, potentially breaking this plugin.

Consider adding:

  1. Version checks or feature detection
  2. Fallback behavior if symbols are undefined
  3. Documentation about supported React versions
🤖 Prompt for AI Agents
In integrations/react/src/stable/lazyActivityPlugin.ts around lines 4 to 6, the
code uses React internal symbols react.lazy and react.memo which are not part of
the public API and may change unexpectedly. To fix this, add runtime checks to
verify these symbols exist before using them, implement fallback behavior if
they are undefined, and document the React versions supported by this plugin to
inform users of compatibility constraints.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
integrations/react/src/stable/stackflow.tsx (1)

146-151: Normalize plugin flattening (DRY) and avoid Infinity-as-0 hack scattered inline

Current inline flatten/cast is duplicated (also used in addPlugin) and relies on a TS hack. Centralize into a helper to improve readability and reduce mistakes.

Apply this diff here:

-  const plugins: StackflowReactPlugin[] = [
-    ...(options.plugins ?? [])
-      .flat(Number.POSITIVE_INFINITY as 0)
-      .map((p) => p as StackflowReactPlugin),
-  ];
+  const plugins: StackflowReactPlugin[] = normalizePlugins(options.plugins);

Add this helper (can be placed near the top of stackflow() or file-level):

function normalizePlugins<T extends BaseActivities>(
  entries: Array<StackflowPluginsEntry<T>> | undefined,
): StackflowReactPlugin[] {
  return (entries ?? [])
    .flat(Number.POSITIVE_INFINITY as 0)
    .map((p) => p as StackflowReactPlugin);
}

Optionally, reuse the same helper in addPlugin() to remove duplication.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a488fe9 and eebe0c6.

📒 Files selected for processing (1)
  • integrations/react/src/stable/stackflow.tsx (2 hunks)
⏰ 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). (6)
  • GitHub Check: Workers Builds: stackflow-docs
  • GitHub Check: Create PR or release packages
  • GitHub Check: Check whether the written test passes normally
  • GitHub Check: Check the TypeScript typings
  • GitHub Check: Build all packages
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (2)
integrations/react/src/stable/stackflow.tsx (2)

23-23: Import of internal plugin looks good

Import path and locality are appropriate for stable internals.


158-160: Verify plugin ordering relative to user plugins

Appending places the lazy plugin last. If other plugins hook onBeforePush/Replace, they may run before the lazy pause logic. Prepending ensures lazy-load pausing happens earliest.

If you keep append semantics, please confirm behavior with commonly used plugins (e.g., history sync) to ensure no regressions. Otherwise, switch to unshift as suggested above.

Comment on lines +152 to +161
const majorReactVersion = Number.parseInt(version);

/**
* TODO: This plugin depends on internal APIs of React.
* A proper solution (e.g. Suspense integration) should be implemented in the next major version.
*/
if (majorReactVersion >= 18 && majorReactVersion <= 19) {
plugins.push(lazyActivityPlugin(activityComponentMap));
}

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Tighten React version gate to 18.x and prepend plugin; add radix to parseInt

The plugin relies on React internals; enabling it for 19.x is risky. Also, to ensure it pauses navigation before other plugins, it should run first. Pass radix 10 to parseInt for robustness.

Apply this diff:

-  const majorReactVersion = Number.parseInt(version);
+  const majorReactVersion = Number.parseInt(version, 10);
@@
-  if (majorReactVersion >= 18 && majorReactVersion <= 19) {
-    plugins.push(lazyActivityPlugin(activityComponentMap));
+  if (majorReactVersion >= 18 && majorReactVersion < 19) {
+    // Prepend so it can pause navigation early
+    plugins.unshift(lazyActivityPlugin(activityComponentMap));
   }

If you prefer extra safety, also log a dev-only warning when outside the supported range to aid debugging. I can provide a snippet.

📝 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
const majorReactVersion = Number.parseInt(version);
/**
* TODO: This plugin depends on internal APIs of React.
* A proper solution (e.g. Suspense integration) should be implemented in the next major version.
*/
if (majorReactVersion >= 18 && majorReactVersion <= 19) {
plugins.push(lazyActivityPlugin(activityComponentMap));
}
const majorReactVersion = Number.parseInt(version, 10);
/**
* TODO: This plugin depends on internal APIs of React.
* A proper solution (e.g. Suspense integration) should be implemented in the next major version.
*/
if (majorReactVersion >= 18 && majorReactVersion < 19) {
// Prepend so it can pause navigation early
plugins.unshift(lazyActivityPlugin(activityComponentMap));
}
🤖 Prompt for AI Agents
integrations/react/src/stable/stackflow.tsx around lines 152 to 161: tighten the
React version gate to only allow 18.x (e.g., check majorReactVersion === 18 or
majorReactVersion >= 18 && majorReactVersion < 19), pass radix 10 into
Number.parseInt(version, 10), and prepend the plugin to the plugins array
instead of pushing it (use unshift) so it runs before other plugins; optionally
add a dev-only warning (guarded by NODE_ENV !== 'production') when the React
version is outside the supported range to aid debugging.

@orionmiz
Copy link
Collaborator Author

/oc summarize

@opencode-agent
Copy link

opencode-agent bot commented Aug 11, 2025

This PR adds support for lazy-loaded React components in Stackflow by implementing an internal plugin that handles React.lazy and React.memo components.

Key Changes

New lazy activity plugin (integrations/react/src/stable/lazyActivityPlugin.ts):

  • Detects React.lazy and React.memo components using internal React symbols
  • Pauses navigation during lazy component loading to prevent flicker/errors
  • Handles both onBeforePush and onBeforeReplace events
  • Automatically resumes navigation after component loads (success or failure)

Plugin integration (integrations/react/src/stable/stackflow.tsx):

  • Conditionally registers the plugin only for React 18.x
  • Appends plugin to existing plugin array
  • Uses React version detection to ensure compatibility

Changeset (.changeset/small-rice-listen.md):

  • Documents this as a minor version bump for @stackflow/react
  • No breaking changes to public APIs

Technical Implementation

The plugin works by:

  1. Inspecting activity components for lazy/memo wrappers
  2. Extracting loading promises from React's internal _payload structure
  3. Pausing navigation until promises resolve/reject
  4. Automatically resuming navigation afterward

This is backward-compatible and requires no configuration - it's automatically applied for supported React versions.

Implementing%20lazy%20activity%20support%20for%20Stackflow%20R
opencode session  |  github run

Copy link

@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)
integrations/react/src/stable/stackflow.tsx (1)

29-29: Tighten React gating to 18.x, prepend the plugin, and add radix to parseInt (optional dev warning)

Given the plugin depends on React internals, be conservative: only enable on 18.x, run it before user plugins (so pause executes early), and parse React version with radix 10. Optional: warn in dev when disabled.

- import { version } from "react";
+ import { version as reactVersion } from "react";
@@
- const majorReactVersion = Number.parseInt(version);
+ const majorReactVersion = Number.parseInt(reactVersion, 10);
@@
- /**
-  * TODO: This plugin depends on internal APIs of React.
-  * A proper solution (e.g. Suspense integration) should be implemented in the next major version.
-  */
- if (majorReactVersion >= 18 && majorReactVersion <= 19) {
-   plugins.push(lazyActivityPlugin(activityComponentMap));
- }
+ /**
+  * TODO: This plugin depends on internal React internals.
+  * A proper solution (e.g., Suspense integration) should be implemented in the next major version.
+  */
+ if (majorReactVersion >= 18 && majorReactVersion < 19) {
+   // Prepend so it can pause navigation before other plugins
+   plugins.unshift(lazyActivityPlugin(activityComponentMap));
+ } else if (process.env.NODE_ENV !== "production") {
+   console.warn(
+     `@stackflow/react: lazyActivityPlugin disabled (React ${reactVersion} not in supported range 18.x).`,
+   );
+ }

Also applies to: 152-161

🧹 Nitpick comments (1)
integrations/react/src/stable/stackflow.tsx (1)

146-151: Simplify flattening and preserve generic typing for better type-safety

The flat(Number.POSITIVE_INFINITY as 0) trick works but is a bit opaque and drops the generic parameter. Consider simplifying and keeping the generic to help TS catch mismatches.

-  const plugins: StackflowReactPlugin[] = [
-    ...(options.plugins ?? [])
-      .flat(Number.POSITIVE_INFINITY as 0)
-      .map((p) => p as StackflowReactPlugin),
-  ];
+  const plugins: StackflowReactPlugin<NoInfer<T>>[] = [];
+  (options.plugins ?? [])
+    .flat(Infinity)
+    .forEach((p) => {
+      plugins.push(p as StackflowReactPlugin<NoInfer<T>>);
+    });

Alternatively, extract a tiny helper for clarity:

function normalizePlugins<T extends BaseActivities>(
  entries: Array<StackflowPluginsEntry<T>>,
): StackflowReactPlugin<T>[] {
  return (entries.flat(Infinity) as unknown as StackflowReactPlugin<T>[]);
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eebe0c6 and 8823102.

📒 Files selected for processing (1)
  • integrations/react/src/stable/stackflow.tsx (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
integrations/react/src/stable/stackflow.tsx (2)
integrations/react/src/__internal__/StackflowReactPlugin.ts (1)
  • StackflowReactPlugin (4-41)
integrations/react/src/stable/lazyActivityPlugin.ts (1)
  • lazyActivityPlugin (105-147)
⏰ 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: Workers Builds: stackflow-docs
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (1)
integrations/react/src/stable/stackflow.tsx (1)

23-23: Import looks good

Brings in the internal plugin cleanly for use below. No issues.

@daangn daangn deleted a comment from opencode-agent bot Aug 20, 2025
@orionmiz
Copy link
Collaborator Author

/oc could you review this PR line-by-line via gh api command with gh cli?

@opencode-agent
Copy link

opencode-agent bot commented Aug 20, 2025

undefined is not an object (evaluating '(await client.session.chat({
path: session,
body: {
providerID,
modelID,
agent: "build",
parts: [
{
type: "text",
text
},
...files.flatMap((f) => [
{
type: "file",
mime: f.mime,
url: data:${f.mime};base64,${f.content},
filename: f.filename,
source: {
type: "file",
text: {
value: f.replacement,
start: f.start,
end: f.end
},
path: f.filename
}
}
])
]
}
})).data.parts')

opencode session  |  github run

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.

2 participants