Refactor socket store access and split useEffect hooks#695
Refactor socket store access and split useEffect hooks#6952witstudios wants to merge 2 commits intomasterfrom
Conversation
…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
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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. 📝 WalkthroughWalkthroughTwo components ( Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
🤖 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 filteringusage:updatedevents by conversation/page ID.The handler ignores the event payload and revalidates unconditionally. In
UsageCounter.tsx, the same event is typed asUsageEventPayloadand 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 multipleAiUsageMonitorinstances 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
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
getSocket()method calls with directsocketstate access inUsageCounterandAiUsageMonitorcomponentsconnect()if (!socket) return;guards in listener registration effects to handle async connection timingImplementation 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:
[connect])UsageCounter.tsxandAiUsageMonitor.tsxThe 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