Skip to content

Refactor socket store access and split useEffect hooks#695

Open
2witstudios wants to merge 2 commits intomasterfrom
claude/fix-ai-monitor-socket-g8zdL
Open

Refactor socket store access and split useEffect hooks#695
2witstudios wants to merge 2 commits intomasterfrom
claude/fix-ai-monitor-socket-g8zdL

Conversation

@2witstudios
Copy link
Owner

@2witstudios 2witstudios commented Feb 16, 2026

Summary

Refactored socket store integration in billing and AI usage monitoring components to improve code clarity and fix potential race conditions with async socket connections.

Key Changes

  • Changed socket store access pattern: Replaced getSocket() method calls with direct socket state access in UsageCounter and AiUsageMonitor components
  • Split useEffect hooks: Separated socket connection initialization from event listener registration into two distinct effects:
    • First effect: Initiates socket connection via connect()
    • Second effect: Registers event listeners once socket is available
  • Improved dependency arrays: Updated effect dependencies to properly reflect what each effect actually uses
  • Added null checks: Explicit if (!socket) return; guards in listener registration effects to handle async connection timing

Implementation Details

The refactoring addresses a potential race condition where event listeners were being registered before the socket connection was fully established. By splitting the effects:

  1. The connection effect runs once and has minimal dependencies ([connect])
  2. The listener effect waits for the socket to be available before registering handlers, with proper cleanup on unmount
  3. This pattern is now consistent across both UsageCounter.tsx and AiUsageMonitor.tsx

The changes maintain all existing functionality while improving code maintainability and reducing the risk of missed socket events due to timing issues.

https://claude.ai/code/session_01B5GJTEZGDpfPTcJ3DqpsTE

Summary by CodeRabbit

  • Refactor
    • Enhanced socket event handling architecture for improved code organization and maintainability across components.

…unter

Subscribe to socket state reactively from the Zustand store instead of
calling getSocket() synchronously after the async connect(). Previously,
connect() initiated an async token fetch while getSocket() was called
immediately — returning null before the socket existed. This meant the
usage:updated listener was never registered, leaving the UI stale.

Split the single effect into two: one for initiating the connection, and
one reactive to the socket reference for registering event listeners.

https://claude.ai/code/session_01B5GJTEZGDpfPTcJ3DqpsTE
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 16, 2026

Warning

Rate limit exceeded

@2witstudios has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 19 minutes and 31 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

Two components (AiUsageMonitor and UsageCounter) are refactored to retrieve socket instances from store state rather than direct socket retrieval calls. Socket event listeners are now registered in separate effects that depend on socket availability, reducing coupling to synchronous socket acquisition.

Changes

Cohort / File(s) Summary
Socket State Migration
apps/web/src/components/ai/shared/AiUsageMonitor.tsx, apps/web/src/components/billing/UsageCounter.tsx
Both components replace getSocket() calls with store-provided socket state. Each refactors effect hooks so socket event listeners ("usage:updated") are registered only when socket is available, moving logic to separate effects that react to socket state presence.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Socket state flows through the store,
No more chasing getters like before,
Effects now dance when socket's here,
Listeners register, crystal clear,
Decoupled and reactive—a bunny's cheer! 🌟

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main changes: refactoring socket access from getSocket() to store state and splitting useEffect hooks into separate concerns for connection and event listener registration.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into master

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/fix-ai-monitor-socket-g8zdL

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

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.

🤖 Fix all issues with AI agents
Verify each finding against the current code and only fix it if needed.


In `@apps/web/src/components/ai/shared/AiUsageMonitor.tsx`:
- Around line 48-66: The handler registered in useEffect currently ignores the
event payload; update handleUsageUpdated to accept the event parameter (typed as
UsageEventPayload to match UsageCounter.tsx) and filter by payload identifiers
before revalidating: if payload.conversationId exists and doesn't equal the
local conversationId, return; similarly check payload.pageId against pageId;
only call mutateConversation or mutatePage when the payload matches the
instance. Keep the socket.on('usage:updated', handleUsageUpdated) and socket.off
cleanup but ensure the function signature and filtering logic are applied so
unnecessary SWR revalidations are avoided.
🧹 Nitpick comments (1)
🤖 Fix all nitpicks with AI agents
Verify each finding against the current code and only fix it if needed.


In `@apps/web/src/components/ai/shared/AiUsageMonitor.tsx`:
- Around line 48-66: The handler registered in useEffect currently ignores the
event payload; update handleUsageUpdated to accept the event parameter (typed as
UsageEventPayload to match UsageCounter.tsx) and filter by payload identifiers
before revalidating: if payload.conversationId exists and doesn't equal the
local conversationId, return; similarly check payload.pageId against pageId;
only call mutateConversation or mutatePage when the payload matches the
instance. Keep the socket.on('usage:updated', handleUsageUpdated) and socket.off
cleanup but ensure the function signature and filtering logic are applied so
unnecessary SWR revalidations are avoided.
apps/web/src/components/ai/shared/AiUsageMonitor.tsx (1)

48-66: Consider filtering usage:updated events by conversation/page ID.

The handler ignores the event payload and revalidates unconditionally. In UsageCounter.tsx, the same event is typed as UsageEventPayload and the payload data is used directly. Here, the payload is discarded. If the payload contains identifying fields (e.g., conversationId), you could filter to avoid unnecessary SWR revalidations when multiple AiUsageMonitor instances are mounted.

At minimum, accepting the payload parameter would keep the two listeners consistent:

Suggested improvement
-    const handleUsageUpdated = () => {
+    const handleUsageUpdated = (payload: UsageEventPayload) => {
       if (conversationId) {
         mutateConversation();
       } else if (pageId) {
         mutatePage();
       }
     };

This would also let you add filtering later (e.g., if (payload.conversationId !== conversationId) return;) without another refactor.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web/src/components/ai/shared/AiUsageMonitor.tsx` around lines 48 - 66,
The handler registered in useEffect currently ignores the event payload; update
handleUsageUpdated to accept the event parameter (typed as UsageEventPayload to
match UsageCounter.tsx) and filter by payload identifiers before revalidating:
if payload.conversationId exists and doesn't equal the local conversationId,
return; similarly check payload.pageId against pageId; only call
mutateConversation or mutatePage when the payload matches the instance. Keep the
socket.on('usage:updated', handleUsageUpdated) and socket.off cleanup but ensure
the function signature and filtering logic are applied so unnecessary SWR
revalidations are avoided.

…nitor

Accept the UsageEventPayload in handleUsageUpdated (matching the pattern
in UsageCounter.tsx) and skip events whose conversationId or pageId
don't match the local instance. This avoids unnecessary SWR
revalidations when multiple AiUsageMonitor instances are mounted.

The filter is forward-compatible: the current payload lacks these fields,
so all events pass through today; once the backend includes them,
filtering activates automatically.

https://claude.ai/code/session_01B5GJTEZGDpfPTcJ3DqpsTE
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