diff --git a/pkg/agent/agent_outbound.go b/pkg/agent/agent_outbound.go index 1728f6f79..a9a5071f6 100644 --- a/pkg/agent/agent_outbound.go +++ b/pkg/agent/agent_outbound.go @@ -64,12 +64,21 @@ func (al *AgentLoop) PublishResponseIfNeeded(ctx context.Context, channel, chatI return } + agent := al.agentForSession(sessionKey) + agentID := "" + if agent != nil { + agentID = agent.ID + } msg := bus.OutboundMessage{ - Context: bus.NewOutboundContext(channel, chatID, ""), - Content: response, + Channel: channel, + ChatID: chatID, + Context: outboundContextFromInbound(inboundCtx, channel, chatID, ""), + AgentID: agentID, + SessionKey: sessionKey, + Content: response, } if sessionKey != "" { - msg.ContextUsage = computeContextUsage(al.agentForSession(sessionKey), sessionKey) + msg.ContextUsage = computeContextUsage(agent, sessionKey) } al.bus.PublishOutbound(ctx, msg) logger.InfoCF("agent", "Published outbound response", diff --git a/pkg/agent/agent_test.go b/pkg/agent/agent_test.go index 1be0dc988..ebb66e19b 100644 --- a/pkg/agent/agent_test.go +++ b/pkg/agent/agent_test.go @@ -162,6 +162,45 @@ func newTestAgentLoop( return al, cfg, msgBus, provider, func() { os.RemoveAll(tmpDir) } } +func TestPublishResponseWithContextIfNeeded_PreservesSessionMetadata(t *testing.T) { + al, _, msgBus, _, cleanup := newTestAgentLoop(t) + defer cleanup() + + inboundCtx := &bus.InboundContext{ + Channel: "telegram", + ChatID: "-100123", + ChatType: "group", + TopicID: "6", + SenderID: "user-1", + } + al.publishResponseWithContextIfNeeded( + context.Background(), + "telegram", + "-100123", + "session-async-1", + "done", + inboundCtx, + ) + + select { + case outbound := <-msgBus.OutboundChan(): + if outbound.Channel != "telegram" || outbound.ChatID != "-100123" { + t.Fatalf("unexpected outbound target: channel=%q chat=%q", outbound.Channel, outbound.ChatID) + } + if outbound.Context.TopicID != "6" { + t.Fatalf("outbound topic_id = %q, want 6", outbound.Context.TopicID) + } + if outbound.AgentID != routing.DefaultAgentID { + t.Fatalf("outbound agent_id = %q, want %q", outbound.AgentID, routing.DefaultAgentID) + } + if outbound.SessionKey != "session-async-1" { + t.Fatalf("outbound session_key = %q, want session-async-1", outbound.SessionKey) + } + case <-time.After(2 * time.Second): + t.Fatal("expected outbound response") + } +} + func TestNewAgentLoop_RegistersWebSearchTool(t *testing.T) { cfg := config.DefaultConfig() cfg.Agents.Defaults.Workspace = t.TempDir()