From 9221b1b3d7eaea0244a9a2bfb7b7a12dafce81e3 Mon Sep 17 00:00:00 2001 From: qs3c <2749950753@qq.com> Date: Wed, 4 Mar 2026 17:50:26 +0800 Subject: [PATCH] fix(agent): preserve explicit direct session keys --- pkg/agent/loop.go | 4 ++-- pkg/agent/loop_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/pkg/agent/loop.go b/pkg/agent/loop.go index ef7ded721..14bca66b5 100644 --- a/pkg/agent/loop.go +++ b/pkg/agent/loop.go @@ -485,9 +485,9 @@ func (al *AgentLoop) processMessage(ctx context.Context, msg bus.InboundMessage) } } - // Use routed session key, but honor pre-set agent-scoped keys (for ProcessDirect/cron) + // Preserve explicit session keys for direct invocations and other internal callers. sessionKey := route.SessionKey - if msg.SessionKey != "" && strings.HasPrefix(msg.SessionKey, "agent:") { + if msg.SessionKey != "" { sessionKey = msg.SessionKey } diff --git a/pkg/agent/loop_test.go b/pkg/agent/loop_test.go index 023286f02..ef47e1818 100644 --- a/pkg/agent/loop_test.go +++ b/pkg/agent/loop_test.go @@ -15,6 +15,7 @@ import ( "github.com/sipeed/picoclaw/pkg/config" "github.com/sipeed/picoclaw/pkg/media" "github.com/sipeed/picoclaw/pkg/providers" + "github.com/sipeed/picoclaw/pkg/routing" "github.com/sipeed/picoclaw/pkg/tools" ) @@ -603,6 +604,51 @@ func TestAgentLoop_ContextExhaustionRetry(t *testing.T) { } } +func TestProcessDirectWithChannel_PreservesExplicitSessionKey(t *testing.T) { + al, _, _, _, cleanup := newTestAgentLoop(t) + defer cleanup() + + defaultAgent := al.registry.GetDefaultAgent() + if defaultAgent == nil { + t.Fatal("No default agent found") + } + + explicitSessionKey := "custom-session" + routedSessionKey := al.registry.ResolveRoute(routing.RouteInput{ + Channel: "cli", + }).SessionKey + if routedSessionKey == "" { + t.Fatal("Expected routed session key to be set") + } + if routedSessionKey == explicitSessionKey { + t.Fatalf("Test requires different routed and explicit session keys, both were %q", explicitSessionKey) + } + + response, err := al.ProcessDirectWithChannel( + context.Background(), + "hello from cli", + explicitSessionKey, + "cli", + "direct", + ) + if err != nil { + t.Fatalf("ProcessDirectWithChannel failed: %v", err) + } + if response != "Mock response" { + t.Fatalf("Expected mock response, got %q", response) + } + + explicitHistory := defaultAgent.Sessions.GetHistory(explicitSessionKey) + if len(explicitHistory) == 0 { + t.Fatal("Expected explicit session history to be written") + } + + routedHistory := defaultAgent.Sessions.GetHistory(routedSessionKey) + if len(routedHistory) != 0 { + t.Fatalf("Expected routed session history to stay empty, got %d entries", len(routedHistory)) + } +} + func TestTargetReasoningChannelID_AllChannels(t *testing.T) { tmpDir, err := os.MkdirTemp("", "agent-test-*") if err != nil {