Skip to content

Conversation

@jmanhype
Copy link

…alth indicator

  • Add useSSEStream hook with EventSource API supporting:

    • Exponential backoff reconnection (configurable initial/max delay)
    • Jitter to prevent thundering herd
    • last-event-ID tracking for replay capability
    • Connection state management (connected/connecting/reconnecting/disconnected)
  • Add ConnectionHealthIndicator UI component:

    • Visual indicator with color-coded states
    • Pulsing animation during connection attempts
    • Tooltip with detailed status info
    • Optional label display
    • Click-to-reconnect support
  • Add useGlobalStreamStatus Zustand store:

    • Tracks multiple stream connections
    • Provides aggregate connection health
    • Integrates with existing WebSocket streams
  • Add SSE context provider for shared connection state

  • Add useRealtimeConnection convenience hook

  • Integrate health indicator into navbar

  • Register existing WebSocket streams with global tracker

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @jmanhype, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the application's real-time communication infrastructure by introducing a comprehensive Server-Sent Events (SSE) solution. It provides robust connection management with automatic reconnection strategies, a centralized system for tracking the health of all real-time streams, and a user-friendly UI component to visualize this status. This ensures a more resilient and transparent real-time experience for users, allowing for better handling of network fluctuations and providing clear feedback on data stream availability.

Highlights

  • Robust SSE Streaming Hook: Introduced a new useSSEStream hook that provides Server-Sent Events (SSE) streaming capabilities, including configurable exponential backoff for reconnection attempts, jitter to prevent thundering herd issues, and last-event-ID tracking for replay functionality. It also manages connection states (connected, connecting, reconnecting, disconnected).
  • Connection Health Indicator UI: Added a ConnectionHealthIndicator UI component that visually represents the connection status with color-coded states, pulsing animations during connection attempts, and a tooltip for detailed status information. It supports an optional label display and click-to-reconnect functionality.
  • Global Stream Status Management: Implemented a useGlobalStreamStatus Zustand store to track the health of multiple real-time stream connections (both new SSE and existing WebSocket streams), providing an aggregate view of the overall connection health across the application.
  • SSE Context Provider: Created an SSEConnectionProvider and associated hooks (useSSEConnection, useSSEConnectionOptional) to provide shared SSE connection state to descendant components, simplifying state management for SSE consumers.
  • Convenience Hook and Navbar Integration: Added a useRealtimeConnection convenience hook for a simplified interface to SSE streams and integrated the NavbarConnectionStatus component into the application's navbar to display the global connection health visually.
  • WebSocket Stream Integration: Modified existing useJsonPatchWsStream to register WebSocket streams with the new global status tracker, ensuring a unified view of all real-time connections.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a robust SSE client implementation with exponential backoff and jitter for reconnections, which is a great improvement for real-time features. It also adds a global connection status tracking system using Zustand and a new ConnectionHealthIndicator UI component. The code is well-structured with clear separation of concerns into hooks, context, and UI components. I've provided a few suggestions to improve maintainability and fix an issue with a hook implementation. Overall, this is a solid contribution.

Comment on lines +155 to +169
export function useRegisterStream(
id: string,
name: string,
isConnected: boolean,
error: string | null
) {
const updateStream = useGlobalStreamStatus((s) => s.updateStream);
const removeStream = useGlobalStreamStatus((s) => s.removeStream);

// Update on mount and when status changes
updateStream(id, name, isConnected, error);

// Return cleanup function
return () => removeStream(id);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The useRegisterStream function is named as a hook (starts with use) but doesn't follow the Rules of Hooks. It performs side effects (calling updateStream) directly in its body, which runs during the render phase. This can lead to unexpected behavior and performance issues.

This change refactors it into a proper hook that uses useEffect to manage its lifecycle. This will correctly handle registering, updating, and un-registering the stream.

Note: You will also need to import useEffect from react at the top of the file.

Suggested change
export function useRegisterStream(
id: string,
name: string,
isConnected: boolean,
error: string | null
) {
const updateStream = useGlobalStreamStatus((s) => s.updateStream);
const removeStream = useGlobalStreamStatus((s) => s.removeStream);
// Update on mount and when status changes
updateStream(id, name, isConnected, error);
// Return cleanup function
return () => removeStream(id);
}
export function useRegisterStream(
id: string,
name: string,
isConnected: boolean,
error: string | null
) {
const updateStream = useGlobalStreamStatus((s) => s.updateStream);
const removeStream = useGlobalStreamStatus((s) => s.removeStream);
useEffect(() => {
updateStream(id, name, isConnected, error);
// On unmount, or if dependencies change, this cleanup will run.
return () => removeStream(id);
}, [id, name, isConnected, error, updateStream, removeStream]);
}

Comment on lines +186 to +189
state === 'connected' && 'text-green-600 dark:text-green-400',
state === 'connecting' && 'text-yellow-600 dark:text-yellow-400',
state === 'reconnecting' && 'text-yellow-600 dark:text-yellow-400',
state === 'disconnected' && 'text-red-600 dark:text-red-400'
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

To improve maintainability and centralize state-specific styles, consider moving these text color classes into the stateConfigs object. This will colocate all display logic for each connection state and reduce repetition.

You could add a textColor property to the StateConfig interface and the stateConfigs object, then use it here like config.textColor.

Comment on lines +55 to +65
const streamName = endpoint.includes('tasks/stream')
? 'Tasks'
: endpoint.includes('diff/ws')
? 'Diff'
: endpoint.includes('logs/ws')
? 'Logs'
: endpoint.includes('execution-processes')
? 'Processes'
: endpoint.includes('drafts/stream')
? 'Drafts'
: 'Stream';
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This series of ternary operators to determine the streamName works, but it can become difficult to read and maintain as more stream types are added. Consider refactoring this into a map or a helper function to improve readability and scalability.

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 355 to 359
}, [
endpoint,
enabled,
reconnectAttempts,
lastEventId,

Choose a reason for hiding this comment

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

P1 Badge Remove lastEventId from SSE effect deps

The SSE effect lists lastEventId as a dependency, but the effect’s cleanup closes the current EventSource. Because onmessage updates lastEventId for every event, any stream that emits an Last-Event-ID header will trigger the effect on each message, closing and recreating the connection repeatedly instead of keeping a stable stream. That defeats SSE continuity and can drop or duplicate events under normal traffic. Consider removing lastEventId from the dependency array (it’s already available when reconnecting via other state changes) so the connection isn’t torn down on every event.

Useful? React with 👍 / 👎.

claude and others added 2 commits November 28, 2025 08:48
…alth indicator

- Add useSSEStream hook with EventSource API supporting:
  - Exponential backoff reconnection (configurable initial/max delay)
  - Jitter to prevent thundering herd
  - last-event-ID tracking for replay capability
  - Connection state management (connected/connecting/reconnecting/disconnected)

- Add ConnectionHealthIndicator UI component:
  - Visual indicator with color-coded states
  - Pulsing animation during connection attempts
  - Tooltip with detailed status info
  - Optional label display
  - Click-to-reconnect support

- Add useGlobalStreamStatus Zustand store:
  - Tracks multiple stream connections
  - Provides aggregate connection health
  - Integrates with existing WebSocket streams

- Add SSE context provider for shared connection state
- Add useRealtimeConnection convenience hook
- Integrate health indicator into navbar
- Register existing WebSocket streams with global tracker

Co-authored-by: Automagik Genie 🧞 <genie@namastex.ai>
Based on PR automagik-dev#281 review feedback from Gemini Code Assist:

1. **Fix hook implementation issue** (useGlobalStreamStatus):
   - Refactor useRegisterStream to properly use useEffect
   - Follows React Hooks rules for side effects and cleanup
   - Prevents Rules of Hooks violations

2. **Fix SSE dependency issue** (useSSEStream):
   - Remove lastEventId from dependency array
   - Prevents unnecessary reconnections when only event ID changes
   - Improves connection stability

3. **Improve maintainability** (ConnectionHealthIndicator):
   - Move text color classes into stateConfigs object
   - Eliminates repetitive conditional styling
   - Better code organization and extensibility

4. **Improve readability** (useJsonPatchWsStream):
   - Extract stream name logic into getStreamNameFromEndpoint helper
   - Replace complex nested ternaries with maintainable map lookup
   - Easier to add new stream types

All changes maintain functionality while improving code quality,
maintainability, and following React best practices.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Automagik Genie 🧞 <genie@namastex.ai>
@jmanhype jmanhype force-pushed the claude/sse-reconnection-backoff-01JuLVY1t4C9zkuvFEw6dkea branch from 2412ae4 to 6996dc4 Compare November 28, 2025 14:50
@namastex888
Copy link
Contributor

@codex review this pr

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 356 to 359
endpoint,
enabled,
reconnectAttempts,
lastEventId,

Choose a reason for hiding this comment

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

P1 Badge Prevent reconnect loop on every SSE message

The main effect depends on lastEventId while lastEventId is updated for every incoming event, so each message forces the effect to cleanup the current EventSource and recreate it. On SSE endpoints that send an ID on each event (the common case), the connection will be torn down and re-established for every message, causing constant reconnects and likely dropping events rather than maintaining a stable stream. Removing lastEventId from the dependency list would keep the connection alive while still using the latest ID on actual reconnects.

Useful? React with 👍 / 👎.

Comment on lines 292 to 294
setError(null);
setReconnectAttempts(0);
updateConnectionState('connected');

Choose a reason for hiding this comment

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

P2 Badge Avoid closing a recovered SSE connection immediately

When a reconnect succeeds, onopen resets reconnectAttempts to 0, but because reconnectAttempts is a dependency of the main effect (355–359), that state change triggers the effect cleanup, closing the freshly reconnected EventSource and creating another one. After any network hiccup the hook always tears down the first successful reconnection, potentially discarding the first post-outage events and doubling reconnect churn. The attempt counter should be reset without retriggering the effect that owns the live connection.

Useful? React with 👍 / 👎.

@jmanhype
Copy link
Author

@codex review this pr

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +260 to +264
// Build URL with last-event-id for replay capability
const url = new URL(endpoint, window.location.origin);
if (lastEventId) {
url.searchParams.set('lastEventId', lastEventId);
}

Choose a reason for hiding this comment

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

P2 Badge Reset lastEventId when endpoint changes

The SSE hook always appends the previously seen lastEventId to whatever endpoint is passed in, but the state is never cleared when callers switch to a different stream or toggle the connection off and back on. If a component reuses the hook with a new endpoint after viewing another feed, the new connection will send an unrelated lastEventId, which many SSE servers reject or treat as an empty replay, so the new stream can come up missing data until the page is reloaded.

Useful? React with 👍 / 👎.

Resolves three critical SSE reconnection issues identified by Codex:

1. Reconnect loop on every message: Removed lastEventId from effect
   dependencies to prevent effect rerun on each message received.

2. Connection closes on successful reconnect: Use ref for tracking
   reconnect attempts internally. When connection succeeds and resets
   attempts, it no longer triggers effect cleanup that closes connection.

3. lastEventId not reset on endpoint change: Added dedicated effect
   to reset lastEventId when endpoint changes, preventing stale event
   ID from being sent to new endpoints.

Technical changes:
- Added reconnectAttemptsRef for internal tracking
- Added reconnectTrigger state for controlled effect reruns
- Removed lastEventId and reconnectAttempts from effect dependencies
- Added endpoint change effect to reset lastEventId

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Automagik Genie 🧞 <genie@namastex.ai>
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.

3 participants