Skip to content

fix: initial switch and common flow websocket fixes - #225

Merged
Vinod-V3 merged 18 commits into
ELEVATE-Project:release-1.0.5from
pinkman7009:fix/flow-websocket
Jan 15, 2026
Merged

fix: initial switch and common flow websocket fixes#225
Vinod-V3 merged 18 commits into
ELEVATE-Project:release-1.0.5from
pinkman7009:fix/flow-websocket

Conversation

@pinkman7009

@pinkman7009 pinkman7009 commented Jan 14, 2026

Copy link
Copy Markdown

Summary by CodeRabbit

  • Refactor

    • Centralized flow configuration and normalized flow type handling for more consistent routing.
    • Simplified components by removing unused props and reducing local state.
  • Improvements

    • Chat textarea now auto-resizes to fit content.
    • WebSocket handling simplified with a sensible default protocol and better pending-message behavior for more reliable connections.
  • Behavior

    • Flow selection and navigation logic made more consistent across pages.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 14, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

Replaced a centralized FLOW_CONFIG with new helper getBotConfigForFlow, normalized flow type strings, added websocket route mappings, defaulted WebSocket protocol handling, and refactored multiple mitra pages to queue messages, use refs for connection state, and simplify component props and UI state.

Changes

Cohort / File(s) Summary
Configuration & Flow Mapping
src/configure.js, src/pages/ShikshalokamVoiceChat/enum.js, src/pages/ai-creation/utils/common_flow.js
Removed exported FLOW_CONFIG; changed FLOW_TYPES values to lowercase; added free_flow, lfa, lcf websocket mappings; added sessionFlowName entries and introduced getBotConfigForFlow and compareFlowTypesEquality.
WebSocket URL & Helpers
src/utils/helpers.js, src/pages/ShikshalokamVoiceChat/voice-chat.js, src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/WeeksSelection.jsx
buildWebSocketUrl now defaults wssProtocol='wss://'; removed explicit wssProtocol usage in voice-chat and WeeksSelection, relying on helper default.
Common Flow & Connection Lifecycle
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx, src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx
Replaced FLOW_CONFIG lookups with getBotConfigForFlow; added refs for connection state and pendingMessage queuing; changed connect/auth flow to flush queued messages after auth; disabled auto-reconnect and tightened cleanup conditions.
Component API & Chat Integration
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/ActionItems.jsx, src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/SelectObjective.jsx
Removed several props (setIsLoading, handleGoForward, setChatHistory, hasClickedOnAddmore), removed local textbox refs/state and ChatBox inline usage, and eliminated per-component wssProtocol wiring and handleSendMessage path.
ChatBox UI Enhancement
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/components/ChatBox.jsx
Added adjustTextareaHeight helper to auto-resize textarea on transcription result updates.
Miscellaneous small changes
src/hooks/useChatWebhook.js, src/pages/ai-creation/pages/shikshalokam-mitra/MainPage.jsx
Minor formatting/no-op change in connect function; replaced direct FLOW_TYPES equality checks with compareFlowTypesEquality.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant UI as Mitra UI
  participant Connector as WebSocketConnector
  participant BotSvc as Bot WebSocket (ws)
  participant SessionStore

  User->>UI: Trigger send message
  UI->>Connector: isConnected? (ref)
  alt not connected
    UI->>Connector: queue message (pendingMessageRef) & connectToWebSocket()
    Connector->>SessionStore: getSession() for auth
    Connector->>BotSvc: connect (no auto-reconnect)
    BotSvc-->>Connector: onOpen -> authenticate(sessionId)
    BotSvc-->>Connector: onAuthSuccess
    Connector->>UI: notify connected
    Connector->>BotSvc: send queued message (flush)
  else connected
    UI->>Connector: send message immediately
    Connector->>BotSvc: send message
  end
  BotSvc-->>UI: bot response (messages)
  UI->>UI: scroll into view (handleScrollIntoViewRef)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • Vinod-V3

Poem

🐰
I hopped through configs, neat and spry,
Lowercased flows and websockets fly,
Queues now wait until auth's nigh,
Textareas stretch, inputs sigh—
A rabbit cheers the refactor sky!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 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: websocket configuration simplifications and routing updates across common flow and initial switch components.

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


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.

@pinkman7009

Copy link
Copy Markdown
Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Jan 14, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/ActionItems.jsx (2)

194-201: Potential issue: connectToWebSocket missing from dependencies.

The effect calls connectToWebSocket() on mount but only includes disconnect in the dependency array. If connectToWebSocket reference changes, the effect won't re-run with the new function.

Additionally, calling connectToWebSocket on mount without checking if already connected could cause issues if the component remounts.

Suggested fix
  useEffect(() => {
    connectToWebSocket();

    return () => {
      disconnect();
    }
-  }, [disconnect])
+  }, [connectToWebSocket, disconnect])

334-340: Avoid using setTimeout without cleanup.

The setTimeout inside the useEffect for showSelectedActionLoader does not return a cleanup function. If the component unmounts before the timeout fires, it could attempt to set state on an unmounted component.

Suggested fix
  useEffect(() => {
    if (showSelectedActionLoader) {
-      setTimeout(() => {
+      const timeoutId = setTimeout(() => {
        setShowSelectedActionLoader(false)
      }, 1000)
+      return () => clearTimeout(timeoutId);
    }
  }, [showSelectedActionLoader])
🤖 Fix all issues with AI agents
In `@src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx`:
- Around line 141-148: The cleanup useEffect in CommonFlow.jsx captures the
disconnect function but uses an empty dependency array, risking a stale
reference; update the effect so the cleanup always calls the current disconnect
by either (A) adding disconnect to the dependency array of the useEffect that
returns the cleanup, or (B) memoizing disconnect with useCallback so it remains
stable and then include that stable disconnect in the effect dependencies;
ensure you still reference hasConnectedRef.current inside the cleanup and adjust
imports/hooks if you choose to memoize disconnect.

In
`@src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx`:
- Around line 201-210: hasConnectedRef currently marks that a connect attempt
was made, not that the socket is connected, so sends after a dropped connection
silently fail; change the logic to track real connection state (e.g., add
isConnectedRef or connectionState and update it in your socket callbacks such as
onOpen/onClose/onError) and use that for branching: if not connected store the
pending message in pendingMessageRef and call connectToWebSocket, otherwise call
sendSocketMessage; additionally, ensure connectToWebSocket sets
isConnectedRef=true on successful open and resets it (and optionally clears
pendingMessageRef or retries) in onClose/onError, and add error handling around
sendSocketMessage to surface send failures.
- Around line 79-89: The current logic uses pendingMessageRef + a fixed 100ms
setTimeout to call sendSocketMessage, which causes a race with authentication;
replace this by leveraging the useChatWebhook hook's built-in socketQueue /
auto-flush behavior or by waiting for an explicit authentication success event
from the server before flushing pending messages. Specifically, remove the
ad-hoc timeout+pendingMessageRef send and instead either push the text into the
hook's socketQueue (or call the hook's exposed flush/sendQueuedMessages API) so
the hook can auto-flush once authenticated, or wire an event listener that waits
for the authentication success response and only then calls sendSocketMessage
with pendingMessageRef.current and clears it. Ensure you reference
pendingMessageRef and sendSocketMessage in InitialSwitch.jsx and the
socketQueue/auto-flush mechanism in useChatWebhook.js.
🧹 Nitpick comments (7)
src/pages/ai-creation/utils/common_flow.js (1)

4-14: Consider logging or warning on unknown flow types.

The default case silently returns FREE_FLOW config for any unrecognized flowType. This could mask bugs if an unexpected value is passed. Consider adding a warning:

🔧 Suggested improvement
       case FLOW_TYPES.FREE_FLOW:
         return { route: bot_routes.free_flow_bot, flow_name: sessionFlowName.free_flow };
       default:
+        console.warn(`Unknown flowType: ${flowType}, defaulting to FREE_FLOW`);
         return { route: bot_routes.free_flow_bot, flow_name: sessionFlowName.free_flow };
     }
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/components/ChatBox.jsx (1)

281-299: Duplicated height-adjustment logic with slightly different behavior.

This helper duplicates the logic in the onInput handler (lines 335-363) but uses a simpler algorithm. The onInput handler has additional branches (e.g., setting minHeight + 20 when scrollHeight === clientHeight) that aren't present here. This could cause inconsistent textarea sizing.

Consider extracting a single shared function or aligning the algorithms.

♻️ Suggested consolidation
  const adjustTextareaHeight = () => {
    if (!textInputRef?.current) return
    
    const el = textInputRef.current
    const minHeight = 24
    const maxHeight = 100
    
    el.style.height = "auto"
    
    if (!el.value) {
      el.style.height = `${minHeight}px`
      el.style.overflowY = "hidden"
      return
    }
    
-   const nextHeight = Math.min(el.scrollHeight, maxHeight)
-   el.style.height = `${nextHeight}px`
-   el.style.overflowY = nextHeight >= maxHeight ? "auto" : "hidden"
+   // Match the onInput logic for consistency
+   if (el.scrollHeight > el.clientHeight) {
+     const nextHeight = Math.min(el.scrollHeight, maxHeight)
+     el.style.height = `${nextHeight}px`
+     el.style.overflowY = nextHeight >= maxHeight ? "auto" : "hidden"
+   } else if (el.scrollHeight === el.clientHeight) {
+     el.style.height = `${minHeight + 20}px`
+     el.style.overflowY = "hidden"
+   } else {
+     el.style.height = `${minHeight}px`
+     el.style.overflowY = "hidden"
+   }
  }
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx (1)

40-41: Consider caching the config lookup result.

getBotConfigForFlow(flowType) is called twice. While likely inexpensive, you could destructure both values from a single call.

Suggested improvement
-  const storageFlow = getBotConfigForFlow(flowType).flow_name;
-  const botRoute = getBotConfigForFlow(flowType).route;
+  const { flow_name: storageFlow, route: botRoute } = getBotConfigForFlow(flowType);
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/ActionItems.jsx (4)

113-114: Empty callbacks should be removed or documented.

onWebSocketClose is an empty callback. If this is intentional (no action needed on close), consider removing the handler entirely or adding a comment explaining why it's a no-op.


168-172: Remove empty error handlers or add implementation.

Both onWebSocketError and onFinalReconnectAttempt are empty callbacks. For error handling, at minimum consider logging the error for debugging purposes.

Suggested improvement
  const onWebSocketError = useCallback((error) => {
+   console.error('WebSocket error:', error);
  }, [])

  const onFinalReconnectAttempt = useCallback(() => {
+   console.warn('Final WebSocket reconnect attempt reached');
  }, [])

722-733: Remove commented-out code.

The ChatBox integration is commented out. If this functionality is intentionally removed, delete the commented code to keep the codebase clean. If it's meant to be restored, consider tracking it in an issue instead.


126-126: Unused dependency in onWebSocketOpen.

preferredLanguage is listed in the dependency array but is not used within the callback body. This won't cause bugs but is misleading.

Suggested fix
-  }, [sessionId, profileId, accessToken, preferredLanguage, storageFlow])
+  }, [sessionId, profileId, accessToken, storageFlow])
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a587823 and 38433a1.

📒 Files selected for processing (11)
  • src/configure.js
  • src/pages/ShikshalokamVoiceChat/enum.js
  • src/pages/ShikshalokamVoiceChat/voice-chat.js
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/ActionItems.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/SelectObjective.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/WeeksSelection.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/components/ChatBox.jsx
  • src/pages/ai-creation/utils/common_flow.js
  • src/utils/helpers.js
💤 Files with no reviewable changes (4)
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/WeeksSelection.jsx
  • src/configure.js
  • src/pages/ShikshalokamVoiceChat/voice-chat.js
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/SelectObjective.jsx
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: pinkman7009
Repo: ELEVATE-Project/mohini-app-frontend PR: 223
File: src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx:124-140
Timestamp: 2026-01-11T21:04:07.741Z
Learning: In CommonFlow.jsx (src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx), the WebSocket URL intentionally uses `sessionFlowName.Creation` for all common flows (LFA, LCF, FREE_FLOW) in the `buildWebSocketUrl` call. The derived `storageFlow` (from `flowConfig.flow_name`) is used in the authentication message sent via `onWebSocketOpen`, not in the WebSocket URL construction. This is the expected design.
📚 Learning: 2026-01-11T21:04:07.741Z
Learnt from: pinkman7009
Repo: ELEVATE-Project/mohini-app-frontend PR: 223
File: src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx:124-140
Timestamp: 2026-01-11T21:04:07.741Z
Learning: In CommonFlow.jsx (src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx), the WebSocket URL intentionally uses `sessionFlowName.Creation` for all common flows (LFA, LCF, FREE_FLOW) in the `buildWebSocketUrl` call. The derived `storageFlow` (from `flowConfig.flow_name`) is used in the authentication message sent via `onWebSocketOpen`, not in the WebSocket URL construction. This is the expected design.

Applied to files:

  • src/utils/helpers.js
  • src/pages/ai-creation/utils/common_flow.js
  • src/pages/ShikshalokamVoiceChat/enum.js
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/ActionItems.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx
📚 Learning: 2025-12-23T16:55:04.450Z
Learnt from: pinkman7009
Repo: ELEVATE-Project/mohini-app-frontend PR: 218
File: src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/ActionItems.jsx:318-320
Timestamp: 2025-12-23T16:55:04.450Z
Learning: In ActionItems.jsx (src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/ActionItems.jsx), the action list is intentionally refetched every time the objective changes. The commented-out guard and the useEffect dependency on `objective` are part of the expected design for handling objective regeneration flows.

Applied to files:

  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/ActionItems.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx
🧬 Code graph analysis (3)
src/pages/ai-creation/utils/common_flow.js (2)
src/configure.js (4)
  • FLOW_TYPES (44-49)
  • FLOW_TYPES (44-49)
  • bot_routes (22-41)
  • bot_routes (22-41)
src/pages/ShikshalokamVoiceChat/enum.js (2)
  • sessionFlowName (32-47)
  • sessionFlowName (32-47)
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/components/ChatBox.jsx (6)
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx (1)
  • textInputRef (15-15)
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx (1)
  • textInputRef (15-15)
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/WeeksSelection.jsx (1)
  • textInputRef (31-31)
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/SelectObjective.jsx (1)
  • textInputRef (86-86)
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/DefineChallenge.jsx (1)
  • textInputRef (91-91)
src/index.js (1)
  • el (10-10)
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx (1)
src/pages/ai-creation/utils/common_flow.js (2)
  • getBotConfigForFlow (4-15)
  • getBotConfigForFlow (4-15)
🔇 Additional comments (9)
src/pages/ShikshalokamVoiceChat/enum.js (1)

44-46: LGTM!

The new session flow name entries are consistent with the FLOW_TYPES enum and properly support the centralized flow configuration in getBotConfigForFlow.

src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/components/ChatBox.jsx (1)

195-199: Appropriate use of setTimeout(0) for deferred DOM update.

Using setTimeout with 0 delay correctly defers height adjustment until after React has updated the DOM with the new transcription value.

src/utils/helpers.js (1)

57-57: LGTM!

Adding a sensible default of 'wss://' simplifies caller code and ensures secure WebSocket connections by default.

src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx (3)

17-17: Good addition: pendingMessageRef enables deferred message sending.

Using a ref to queue the message until after WebSocket connection is a valid pattern for handling the async connection flow.


156-156: Verify reconnect: false is intentional.

Disabling reconnection means the WebSocket won't automatically recover from dropped connections. Ensure this aligns with the intended UX, especially on unstable networks.


160-167: Cleanup correctly guards disconnect with hasConnectedRef.

This prevents calling disconnect() on an uninitialized WebSocket connection. The pattern is appropriate.

src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx (3)

16-17: LGTM on connection state tracking refs.

Using hasConnectedRef to track connection state and pendingMessageRef for queuing messages before connection is established is a clean pattern for handling the async WebSocket connection flow.


23-27: LGTM on ref synchronization pattern.

This pattern correctly keeps the ref in sync with the prop, allowing callbacks with empty dependency arrays to access the latest handleScrollIntoView without causing re-subscriptions.


175-184: LGTM on connection-aware message sending.

The logic correctly queues the message if not yet connected and triggers connection, otherwise sends immediately. The hasConnectedRef flag is set before connectToWebSocket() to prevent duplicate connection attempts.

Comment thread src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx Outdated
Comment thread src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx Outdated
@pinkman7009

Copy link
Copy Markdown
Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Jan 14, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx (1)

70-93: Stale closure risk: onWebSocketOpen has empty dependencies but references mutable values.

The onWebSocketOpen callback (line 93) has an empty dependency array but references sendSocketMessage, profileId, and accessToken. If these values change after mount, the callback will use stale values.

This is particularly concerning because:

  1. sendSocketMessage is defined after onWebSocketOpen (lines 157-158) and may change on reconnection
  2. profileId and accessToken are captured at mount time

Consider adding dependencies or using refs for these values, similar to how handleScrollIntoViewRef is handled:

Suggested fix
  const onWebSocketOpen = useCallback(() => {
    isConnectedRef.current = true;
    
    const currentSessionId = useAICreationSessionStore.getState().getSession();
    sendSocketMessage({
      type: 'authenticate',
      sessionid: currentSessionId,
      profileid: profileId,
      access_token: accessToken,
      route: 'en',
      bot_route: bot_routes.initial_switch_bot,
      flow_name: storageFlow,
    });

    if (pendingMessageRef.current) {
      setTimeout(() => {
        sendSocketMessage({
          text: pendingMessageRef.current,
          context: '',
        });
        pendingMessageRef.current = null;
      }, 100);
    }
- }, []);
+ }, [sendSocketMessage, profileId, accessToken, storageFlow]);
🧹 Nitpick comments (2)
src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx (2)

16-17: Connection state tracking may be incomplete.

Similar to the concern previously raised in InitialSwitch.jsx, hasConnectedRef tracks whether a connection was attempted, not whether the WebSocket is currently connected. If the connection drops unexpectedly (since reconnect: false), subsequent messages will be sent via sendSocketMessage but may fail silently.

Consider adding onClose and onError handlers to track actual connection state, as was done in the updated InitialSwitch.jsx:

Suggested enhancement
+ const isConnectedRef = useRef(false);

  const onWebSocketOpen = useCallback(() => {
+   isConnectedRef.current = true;
    // ... existing code
  }, [profileId, accessToken, botRoute, storageFlow]);

+ const onWebSocketClose = useCallback(() => {
+   isConnectedRef.current = false;
+ }, []);

+ const onWebSocketError = useCallback(() => {
+   isConnectedRef.current = false;
+   pendingMessageRef.current = null;
+   setIsWaitingForBot(false);
+ }, []);

  // In useChatWebhook options:
  {
    onOpen: onWebSocketOpen,
    onMessage: onWebSocketMessage,
+   onClose: onWebSocketClose,
+   onError: onWebSocketError,
    autoConnect: false,
    reconnect: false,
  }

  // In handleSendMessage:
- if (!hasConnectedRef.current) {
+ if (!isConnectedRef.current) {

40-41: Consider extracting config once to avoid duplicate calls.

getBotConfigForFlow(flowType) is called twice. While this is functionally correct, extracting it once improves clarity:

Optional refactor
- const storageFlow = getBotConfigForFlow(flowType).flow_name;
- const botRoute = getBotConfigForFlow(flowType).route;
+ const { flow_name: storageFlow, route: botRoute } = getBotConfigForFlow(flowType);
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 38433a1 and 80b388e.

📒 Files selected for processing (8)
  • src/configure.js
  • src/hooks/useChatWebhook.js
  • src/pages/ShikshalokamVoiceChat/enum.js
  • src/pages/ai-creation/pages/shikshalokam-mitra/MainPage.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx
  • src/pages/ai-creation/utils/common_flow.js
  • src/utils/helpers.js
✅ Files skipped from review due to trivial changes (1)
  • src/hooks/useChatWebhook.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/pages/ai-creation/utils/common_flow.js
  • src/pages/ShikshalokamVoiceChat/enum.js
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: pinkman7009
Repo: ELEVATE-Project/mohini-app-frontend PR: 223
File: src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx:124-140
Timestamp: 2026-01-11T21:04:07.741Z
Learning: In CommonFlow.jsx (src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx), the WebSocket URL intentionally uses `sessionFlowName.Creation` for all common flows (LFA, LCF, FREE_FLOW) in the `buildWebSocketUrl` call. The derived `storageFlow` (from `flowConfig.flow_name`) is used in the authentication message sent via `onWebSocketOpen`, not in the WebSocket URL construction. This is the expected design.
📚 Learning: 2026-01-14T02:51:09.584Z
Learnt from: pinkman7009
Repo: ELEVATE-Project/mohini-app-frontend PR: 225
File: src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx:79-89
Timestamp: 2026-01-14T02:51:09.584Z
Learning: In the AI creation flow React components (InitialSwitch.jsx and CommonFlow.jsx), the pattern of using a pendingMessageRef with a 100ms setTimeout after WebSocket authentication is an accepted approach to ensure the authenticate message is sent before user messages. Apply this pattern to all JSX files in src/pages/ai-creation/pages/ to maintain consistent timing-based readiness across the flow.

Applied to files:

  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/MainPage.jsx
📚 Learning: 2026-01-11T21:04:07.741Z
Learnt from: pinkman7009
Repo: ELEVATE-Project/mohini-app-frontend PR: 223
File: src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx:124-140
Timestamp: 2026-01-11T21:04:07.741Z
Learning: In CommonFlow.jsx (src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx), the WebSocket URL intentionally uses `sessionFlowName.Creation` for all common flows (LFA, LCF, FREE_FLOW) in the `buildWebSocketUrl` call. The derived `storageFlow` (from `flowConfig.flow_name`) is used in the authentication message sent via `onWebSocketOpen`, not in the WebSocket URL construction. This is the expected design.

Applied to files:

  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/MainPage.jsx
  • src/utils/helpers.js
  • src/configure.js
📚 Learning: 2025-12-23T16:55:04.450Z
Learnt from: pinkman7009
Repo: ELEVATE-Project/mohini-app-frontend PR: 218
File: src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/ActionItems.jsx:318-320
Timestamp: 2025-12-23T16:55:04.450Z
Learning: In ActionItems.jsx (src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/ActionItems.jsx), the action list is intentionally refetched every time the objective changes. The commented-out guard and the useEffect dependency on `objective` are part of the expected design for handling objective regeneration flows.

Applied to files:

  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx
  • src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx
📚 Learning: 2026-01-11T21:08:05.729Z
Learnt from: pinkman7009
Repo: ELEVATE-Project/mohini-app-frontend PR: 223
File: src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/SelectObjective.jsx:416-439
Timestamp: 2026-01-11T21:08:05.729Z
Learning: In the SelectObjective.jsx component (src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/SelectObjective.jsx), objectives are guaranteed to have unique text values, so text-based equality comparison is safe for determining objective selection without risk of duplicate matches.

Applied to files:

  • src/pages/ai-creation/pages/shikshalokam-mitra/MainPage.jsx
📚 Learning: 2026-01-14T02:51:15.737Z
Learnt from: pinkman7009
Repo: ELEVATE-Project/mohini-app-frontend PR: 225
File: src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx:79-89
Timestamp: 2026-01-14T02:51:15.737Z
Learning: In the AI creation flow components (InitialSwitch.jsx, CommonFlow.jsx), the pattern of using `pendingMessageRef` with a 100ms `setTimeout` after WebSocket authentication is intentionally used to ensure the authenticate message is sent before any user messages. This is an accepted implementation pattern for these flows.

Applied to files:

  • src/configure.js
🧬 Code graph analysis (2)
src/pages/ai-creation/pages/shikshalokam-mitra/MainPage.jsx (2)
src/pages/ai-creation/utils/common_flow.js (2)
  • compareFlowTypesEquality (18-20)
  • compareFlowTypesEquality (18-20)
src/configure.js (2)
  • FLOW_TYPES (45-50)
  • FLOW_TYPES (45-50)
src/utils/helpers.js (2)
src/pages/ShikshalokamVoiceChat/enum.js (2)
  • sessionFlowName (32-47)
  • sessionFlowName (32-47)
src/configure.js (2)
  • bot_websocket (52-65)
  • bot_websocket (52-65)
🔇 Additional comments (12)
src/pages/ai-creation/pages/shikshalokam-mitra/MainPage.jsx (3)

28-28: LGTM!

The import of compareFlowTypesEquality aligns with the centralized flow type comparison utility and is used consistently throughout the file.


252-265: LGTM!

The case-insensitive comparison via compareFlowTypesEquality handles potential case variations in flowType values, which improves robustness when flow types originate from different sources.


304-308: LGTM!

The isCommonFlow logic correctly uses case-insensitive comparisons for all three common flow types (LFA, LCF, FREE_FLOW). The truthy check on selectedFlowType before the comparisons is good defensive coding.

src/utils/helpers.js (2)

57-57: Good improvement: Default protocol parameter.

Adding the default wssProtocol = 'wss://' prevents potential issues when callers don't explicitly provide the protocol, ensuring secure WebSocket connections by default.


74-78: LGTM: WebSocket mappings added for new flow types.

The mappings correctly align with the sessionFlowName enum values (FreeFlow, Lfa, Lcf) and the corresponding bot_websocket entries in configure.js. This enables proper WebSocket routing for the new common flows.

src/configure.js (2)

45-50: LGTM: Normalized flow type values.

Lowercase string values (mip, lfa, lcf, free_flow) improve consistency and align with the validation?.toLowerCase() calls in InitialSwitch.jsx.


62-65: LGTM: WebSocket routes for new flows.

The free_flow, lfa, and lcf entries all routing to /ws/free_flow/ is consistent with the design where these flows share the same WebSocket endpoint.

src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/CommonFlow.jsx (2)

70-91: LGTM: Stale closure concern addressed.

The onWebSocketOpen callback now includes the proper dependencies (profileId, accessToken, botRoute, storageFlow), addressing the previously raised concern about capturing stale values.


128-132: Verify WebSocket URL construction aligns with intended design.

Based on learnings, the WebSocket URL previously used sessionFlowName.Creation for all common flows. Now storageFlow is derived from getBotConfigForFlow(flowType).flow_name, which could be lfa, lcf, or free_flow depending on the flow type.

The new mappings in helpers.js (lines 75-77) should handle this correctly, routing to the appropriate bot_websocket entries. Please verify this change is intentional and that the server-side WebSocket endpoints accept these new flow names correctly.

src/pages/ai-creation/pages/shikshalokam-mitra/mitra-pages/InitialSwitch.jsx (3)

95-104: LGTM: Connection state tracking properly implemented.

The onWebSocketClose and onWebSocketError handlers correctly reset isConnectedRef.current to false, addressing the previously raised concern about tracking actual connection state. The error handler also appropriately clears the pending message and resets the waiting state.


140-151: LGTM: Flow type comparison and normalization.

Using compareFlowTypesEquality provides consistent case-insensitive comparison. The validation?.toLowerCase() call on lines 149-150 aligns with the lowercase FLOW_TYPES values in configure.js.


219-229: LGTM: Message sending with proper connection state check.

The logic correctly uses isConnectedRef.current to determine whether to queue the message for post-connection sending or send immediately. This properly handles the case where the WebSocket may have disconnected.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@Vinod-V3
Vinod-V3 merged commit de9b90d into ELEVATE-Project:release-1.0.5 Jan 15, 2026
1 check passed
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