From 7512b6e8f3c37bd0c9e0e25085e318b735f778b4 Mon Sep 17 00:00:00 2001 From: dj-oyu <68707227+dj-oyu@users.noreply.github.com> Date: Sun, 15 Mar 2026 18:39:12 +0900 Subject: [PATCH] refactor: extract Close fork cleanup to closeExt in loop_ext.go Move done channel close, stats flush, and sessions close into closeExt(). Close() now calls closeExt() + MCP/registry close. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/agent/loop.go | 23 ++--------------------- pkg/agent/loop_ext.go | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 21 deletions(-) diff --git a/pkg/agent/loop.go b/pkg/agent/loop.go index 413b060a8..5ed87144d 100644 --- a/pkg/agent/loop.go +++ b/pkg/agent/loop.go @@ -520,15 +520,7 @@ func (al *AgentLoop) Stop() { // and dirty session data). Should be called during graceful shutdown. func (al *AgentLoop) Close() { - select { - case <-al.done: - - // already closed - - default: - - close(al.done) - } + al.closeExt() mcpManager := al.mcp.takeManager() if mcpManager != nil { @@ -540,18 +532,7 @@ func (al *AgentLoop) Close() { } } - if al.stats != nil { - al.stats.Close() - } - - registry := al.GetRegistry() - for _, agentID := range registry.ListAgentIDs() { - if agent, ok := registry.GetAgent(agentID); ok { - agent.Sessions.Close() - } - } - - registry.Close() + al.GetRegistry().Close() } func (al *AgentLoop) RegisterTool(tool tools.Tool) { diff --git a/pkg/agent/loop_ext.go b/pkg/agent/loop_ext.go index 89dbd9a24..4ef4aaecf 100644 --- a/pkg/agent/loop_ext.go +++ b/pkg/agent/loop_ext.go @@ -75,6 +75,28 @@ func (al *AgentLoop) initLoopExt(cfg *config.Config, registry *AgentRegistry, en go al.gcLoop() } +// closeExt releases fork-specific resources: done channel, stats tracker, +// and session stores for all agents. +func (al *AgentLoop) closeExt() { + select { + case <-al.done: + // already closed + default: + close(al.done) + } + + if al.stats != nil { + al.stats.Close() + } + + registry := al.GetRegistry() + for _, agentID := range registry.ListAgentIDs() { + if agent, ok := registry.GetAgent(agentID); ok { + agent.Sessions.Close() + } + } +} + // SetConfigSaver registers a callback to persist config changes. func (al *AgentLoop) SetConfigSaver(fn func(*config.Config) error) { al.saveConfig = fn