Skip to content

Conversation

@iceljc
Copy link
Collaborator

@iceljc iceljc commented Jul 9, 2025

PR Type

Enhancement


Description

  • Add initial states support to realtime chat streaming

  • Refactor event response models for better structure

  • Improve conversation state management during WebSocket connections


Changes diagram

flowchart LR
  A["WebSocket Connection"] --> B["Parse Initial States"]
  B --> C["Connect to Model with States"]
  C --> D["Set Conversation States"]
  D --> E["Save States on Disconnect"]
Loading

Changes walkthrough 📝

Relevant files
Enhancement
IRealtimeHub.cs
Add initial states parameter to interface                               

src/Infrastructure/BotSharp.Abstraction/Realtime/IRealtimeHub.cs

  • Add initStates parameter to ConnectToModel method signature
+1/-1     
RealtimeHub.cs
Implement initial states in realtime hub                                 

src/Infrastructure/BotSharp.Core.Realtime/Services/RealtimeHub.cs

  • Add initStates parameter to ConnectToModel method implementation
  • Pass initial states to conversation service during setup
  • Add import for BotSharp.Abstraction.Models
  • +3/-2     
    ChatStreamMiddleware.cs
    Enhance WebSocket handling with initial states                     

    src/Plugins/BotSharp.Plugin.ChatHub/ChatStreamMiddleware.cs

  • Add InitStates method to parse initial states from WebSocket data
  • Pass initial states to model connection on start event
  • Add conversation state service and save states on disconnect
  • Refactor event mapping to use unified response body structure
  • +22/-7   
    ChatStreamEventResponse.cs
    Refactor event response model structure                                   

    src/Plugins/BotSharp.Plugin.ChatHub/Models/Stream/ChatStreamEventResponse.cs

  • Consolidate event response models into single structure
  • Remove separate ChatStreamMediaEventResponse class
  • Rename MediaEventResponseBody to ChatStreamEventResponseBody
  • +2/-5     

    Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • @qodo-merge-pro
    Copy link

    qodo-merge-pro bot commented Jul 9, 2025

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Error Handling

    The InitStates method catches all exceptions and returns an empty list without logging. This could hide deserialization errors or other issues that should be investigated.

    private List<MessageState> InitStates(string data)
    {
        try
        {
            var states = JsonSerializer.Deserialize<List<MessageState>>(data, BotSharpOptions.defaultJsonOptions);
            return states ?? [];
        }
        catch
        {
            return [];
        }
    }
    State Management

    The SaveStates() call is made without error handling and may fail silently. Consider adding try-catch or validation to ensure states are properly persisted.

    convService.SaveStates();
    await _session.DisconnectAsync();
    Null Reference

    The code accesses response?.Body?.Payload without null checking the response object first, which could cause null reference exceptions if deserialization fails.

    var data = response?.Body?.Payload ?? string.Empty;

    @iceljc iceljc merged commit 5adaa3a into SciSharp:master Jul 9, 2025
    3 of 4 checks passed
    @qodo-merge-pro
    Copy link

    qodo-merge-pro bot commented Jul 9, 2025

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    General
    Log deserialization exceptions properly

    The catch block silently swallows all exceptions, making debugging difficult.
    Consider logging the exception or at least checking for specific exception types
    to handle deserialization failures appropriately.

    src/Plugins/BotSharp.Plugin.ChatHub/ChatStreamMiddleware.cs [160-171]

     private List<MessageState> InitStates(string data)
     {
         try
         {
             var states = JsonSerializer.Deserialize<List<MessageState>>(data, BotSharpOptions.defaultJsonOptions);
             return states ?? [];
         }
    -    catch
    +    catch (JsonException ex)
         {
    +        _logger?.LogWarning(ex, "Failed to deserialize initial states from data: {Data}", data);
             return [];
         }
     }
    • Apply / Chat
    Suggestion importance[1-10]: 7

    __

    Why: The suggestion correctly identifies a silent catch block and proposes adding logging, which significantly improves debuggability and code robustness.

    Medium
    Add error handling for state saving

    The SaveStates() method is called without error handling, which could cause the
    application to crash if state saving fails. Consider wrapping this in a
    try-catch block to handle potential exceptions gracefully.

    src/Plugins/BotSharp.Plugin.ChatHub/ChatStreamMiddleware.cs [102]

    -convService.SaveStates();
    +try
    +{
    +    convService.SaveStates();
    +}
    +catch (Exception ex)
    +{
    +    _logger?.LogError(ex, "Failed to save conversation states for conversation {ConversationId}", conversationId);
    +}
    • Apply / Chat
    Suggestion importance[1-10]: 7

    __

    Why: The suggestion correctly points out the lack of error handling for convService.SaveStates() and proposes a try-catch block with logging, which makes the application more resilient to failures.

    Medium
    • More

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    1 participant