Skip to content

Conversation

iceljc
Copy link
Collaborator

@iceljc iceljc commented Sep 19, 2025

PR Type

Enhancement


Description

  • Add AddDialogs method to routing context interface

  • Refactor dialog management for better consistency

  • Improve logging format in observers

  • Minor code cleanup and variable renaming


Diagram Walkthrough

flowchart LR
  IRoutingContext["IRoutingContext Interface"] -- "adds" --> AddDialogs["AddDialogs Method"]
  RoutingContext["RoutingContext Implementation"] -- "implements" --> AddDialogs
  ConversationObserver["ConversationObserver"] -- "uses" --> AddDialogs
  RoutingService["RoutingService"] -- "uses" --> AddDialogs
  AddDialogs -- "manages" --> DialogList["Dialog List"]
Loading

File Walkthrough

Relevant files
Enhancement
IRoutingContext.cs
Add AddDialogs method to interface                                             

src/Infrastructure/BotSharp.Abstraction/Routing/IRoutingContext.cs

  • Add AddDialogs method to interface for appending dialog lists
+1/-0     
ConversationObserver.cs
Refactor observer with improved logging                                   

src/Infrastructure/BotSharp.Core/MessageHub/Observers/ConversationObserver.cs

  • Rename variable routeCtx to routingCtx
  • Improve debug logging format with structured messages
  • Replace manual dialog addition with AddDialogs method call
+6/-6     
RoutingContext.cs
Implement AddDialogs with defensive copying                           

src/Infrastructure/BotSharp.Core/Routing/RoutingContext.cs

  • Implement AddDialogs method for appending dialog collections
  • Improve SetDialogs to create defensive copies
  • Enhance GetDialogs to return defensive copies
  • Add null safety checks for dialog operations
+10/-2   
RoutingService.InvokeAgent.cs
Use AddDialogs for message handling                                           

src/Infrastructure/BotSharp.Core/Routing/RoutingService.InvokeAgent.cs

  • Replace Context.SetDialogs calls with Context.AddDialogs
  • Refactor message creation for better code organization
  • Maintain local dialog list alongside context updates
+10/-8   
Formatting
FileInstructService.SelectFile.cs
Rename routing context variable                                                   

src/Infrastructure/BotSharp.Core/Files/Services/Instruct/FileInstructService.SelectFile.cs

  • Rename variable routeContext to routingCtx for consistency
+2/-2     
ChatHubObserver.cs
Add import and improve logging                                                     

src/Plugins/BotSharp.Plugin.ChatHub/Observers/ChatHubObserver.cs

  • Add import for BotSharp.Core.MessageHub.Observers
  • Improve debug logging format consistency
+2/-1     
MySqlService.cs
Reorder using statements                                                                 

src/Plugins/BotSharp.Plugin.ExcelHandler/Services/MySqlService.cs

  • Reorder using statements for better organization
+3/-3     
Documentation
ExcelHandlerSettings.cs
Add documentation comment                                                               

src/Plugins/BotSharp.Plugin.ExcelHandler/Settings/ExcelHandlerSettings.cs

  • Add XML documentation comment for Provider property
+3/-0     

Copy link

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

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

Build Compatibility

The use of C# list literal syntax in AddDialogs calls (e.g., routingCtx.AddDialogs([value.Data])) requires C# 12/.NET 8. Ensure the project targets compatible language/runtime or replace with new List { value.Data } for broader compatibility.

            _logger.LogCritical($"[{nameof(ConversationObserver)}]: Receive {value.EventName} => {value.Data.Content} ({conv.ConversationId})");
#endif
            routingCtx.AddDialogs([value.Data]);
            if (value.SaveDataToDb)
            {
Consistent List Syntax

Multiple calls to Context.AddDialogs use bracket list literals ([message]/[msg]). Verify language version or replace with explicit List initializers to avoid compile issues across projects.

    dialogs.Add(message);
    Context.AddDialogs([message]);
}
Defensive Copy Cost

GetDialogs now returns a new list each call. Call sites that loop frequently may allocate unnecessarily; consider exposing read-only view or keeping existing API but documenting copy behavior to avoid performance regressions.

public List<RoleDialogModel> GetDialogs()
{
    _dialogs ??= [];
    return new List<RoleDialogModel>(_dialogs);
}

Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Simplify state management in RoutingService

Refactor RoutingService to eliminate the redundant local dialogs list. Instead,
use RoutingContext as the single source of truth for dialog history by removing
the dialogs parameter from InvokeAgent and InvokeFunction.

Examples:

src/Infrastructure/BotSharp.Core/Routing/RoutingService.InvokeAgent.cs [8-12]
    public async Task<bool> InvokeAgent(
        string agentId,
        List<RoleDialogModel> dialogs,
        InvokeAgentOptions? options = null)
    {
src/Infrastructure/BotSharp.Core/Routing/RoutingService.InvokeAgent.cs [79-80]
            dialogs.Add(message);
            Context.AddDialogs([message]);

Solution Walkthrough:

Before:

public partial class RoutingService
{
    public async Task<bool> InvokeAgent(string agentId, List<RoleDialogModel> dialogs, ...)
    {
        // ...
        var message = ...;
        dialogs.Add(message);
        Context.AddDialogs([message]);
        return true;
    }

    private async Task<bool> InvokeFunction(RoleDialogModel message, List<RoleDialogModel> dialogs, ...)
    {
        // ...
        await InvokeAgent(curAgentId, dialogs, options);
        // ...
    }
}

After:

public partial class RoutingService
{
    public async Task<bool> InvokeAgent(string agentId, ...) // No 'dialogs' parameter
    {
        var dialogs = Context.GetDialogs(); // Fetched from context
        // ...
        var message = ...;
        Context.AddDialogs([message]); // Single source of truth is updated
        return true;
    }

    private async Task<bool> InvokeFunction(RoleDialogModel message, ...) // No 'dialogs' parameter
    {
        // ...
        await InvokeAgent(curAgentId, options);
        // ...
    }
}
Suggestion importance[1-10]: 9

__

Why: This is an excellent design suggestion that correctly identifies redundant state management, which can lead to bugs and maintenance issues. Centralizing dialog history in RoutingContext would significantly improve the code's robustness and clarity.

High
Learned
best practice
Add null-safe logging guards

Guard potentially null properties in debug logging by using null-conditional
operators and safe defaults to prevent NullReferenceExceptions.

src/Infrastructure/BotSharp.Core/MessageHub/Observers/ConversationObserver.cs [48-50]

 #if DEBUG
-            _logger.LogCritical($"[{nameof(ConversationObserver)}]: Receive {value.EventName} => {value.Data.Content} ({conv.ConversationId})");
+            _logger.LogCritical($"[{nameof(ConversationObserver)}]: Receive {value.EventName} => {value.Data?.Content ?? string.Empty} ({conv?.ConversationId ?? string.Empty})");
 #endif
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Ensure null-safety on optional inputs and object properties when accessing nested properties in logs to avoid NullReferenceExceptions.

Low
General
Simplify and optimize the method

Refactor the AddDialogs method to avoid redundant list allocations when the
input dialogs is null by using a direct null check instead of creating
intermediate empty lists.

src/Infrastructure/BotSharp.Core/Routing/RoutingContext.cs [275-280]

 public void AddDialogs(List<RoleDialogModel> dialogs)
 {
-    var items = new List<RoleDialogeModel>(dialogs ?? []);
-    _dialogs ??= [];
-    _dialogs.AddRange(items);
+    if (dialogs != null)
+    {
+        _dialogs ??= [];
+        _dialogs.AddRange(dialogs);
+    }
 }
  • Apply / Chat
Suggestion importance[1-10]: 3

__

Why: The suggestion correctly identifies a minor inefficiency and proposes a cleaner, slightly more performant implementation, which is a valid but low-impact improvement.

Low
  • More

@iceljc iceljc merged commit 7a7fc0b into SciSharp:master Sep 19, 2025
4 checks passed
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