diff --git a/dotnet/src/Microsoft.Agents.AI/Compaction/CompactionProvider.cs b/dotnet/src/Microsoft.Agents.AI/Compaction/CompactionProvider.cs index 2d919f709cf..a8e3948a7ce 100644 --- a/dotnet/src/Microsoft.Agents.AI/Compaction/CompactionProvider.cs +++ b/dotnet/src/Microsoft.Agents.AI/Compaction/CompactionProvider.cs @@ -132,7 +132,8 @@ protected override async ValueTask InvokingCoreAsync(InvokingContext ChatClientAgentSession? chatClientSession = session.GetService(); if (chatClientSession is not null && - !string.IsNullOrWhiteSpace(chatClientSession.ConversationId)) + !string.IsNullOrWhiteSpace(chatClientSession.ConversationId) && + !string.Equals(chatClientSession.ConversationId, PerServiceCallChatHistoryPersistingChatClient.LocalHistoryConversationId, StringComparison.Ordinal)) { logger.LogCompactionProviderSkipped("session managed by remote service"); return context.AIContext; diff --git a/dotnet/tests/Microsoft.Agents.AI.UnitTests/Compaction/CompactionProviderTests.cs b/dotnet/tests/Microsoft.Agents.AI.UnitTests/Compaction/CompactionProviderTests.cs index e4d4fa23780..c4e6dd4f73c 100644 --- a/dotnet/tests/Microsoft.Agents.AI.UnitTests/Compaction/CompactionProviderTests.cs +++ b/dotnet/tests/Microsoft.Agents.AI.UnitTests/Compaction/CompactionProviderTests.cs @@ -131,6 +131,46 @@ public async Task InvokingAsyncAppliesCompactionWhenTriggeredAsync() Assert.True(resultList.Count < messages.Count); } + [Theory] + [InlineData(null, true)] + [InlineData("", true)] + [InlineData(" ", true)] + [InlineData(PerServiceCallChatHistoryPersistingChatClient.LocalHistoryConversationId, true)] + [InlineData("remote-conversation-id", false)] + public async Task InvokingAsyncCompactsOnlyLocallyManagedHistoryAsync(string? conversationId, bool shouldCompact) + { + // Arrange + TruncationCompactionStrategy strategy = new(CompactionTriggers.Always, minimumPreservedGroups: 1); + CompactionProvider provider = new(strategy); + Mock mockAgent = new() { CallBase = true }; + ChatClientAgentSession session = new(conversationId); + List messages = + [ + new ChatMessage(ChatRole.User, "Q1"), + new ChatMessage(ChatRole.Assistant, "A1"), + new ChatMessage(ChatRole.User, "Q2"), + ]; + AIContextProvider.InvokingContext context = new( + mockAgent.Object, + session, + new AIContext { Messages = messages }); + + // Act + AIContext result = await provider.InvokingAsync(context); + + // Assert + Assert.NotNull(result.Messages); + if (shouldCompact) + { + Assert.Same(messages[2], Assert.Single(result.Messages)); + } + else + { + Assert.Same(context.AIContext, result); + Assert.Same(messages, result.Messages); + } + } + [Fact] public async Task InvokingAsyncNoCompactionNeededReturnsOriginalMessagesAsync() {