From bab17d75208ffca043ff85c258ec42507d955a1e Mon Sep 17 00:00:00 2001 From: adamdottv <2363879+adamdottv@users.noreply.github.com> Date: Thu, 8 May 2025 07:43:31 -0500 Subject: feat: session manager --- internal/session/manager.go | 88 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 internal/session/manager.go (limited to 'internal/session') diff --git a/internal/session/manager.go b/internal/session/manager.go new file mode 100644 index 000000000..8df421bd8 --- /dev/null +++ b/internal/session/manager.go @@ -0,0 +1,88 @@ +package session + +import ( + "context" + "sync" + + "github.com/opencode-ai/opencode/internal/logging" + "github.com/opencode-ai/opencode/internal/pubsub" +) + +// Manager handles session management, tracking the currently active session. +type Manager struct { + currentSessionID string + service Service + mu sync.RWMutex +} + +// Global instance of the session manager +var globalManager *Manager + +// InitManager initializes the global session manager with the provided service. +func InitManager(service Service) { + globalManager = &Manager{ + currentSessionID: "", + service: service, + } + + // Subscribe to session events to handle session deletions + go func() { + ctx := context.Background() + eventCh := service.Subscribe(ctx) + for event := range eventCh { + if event.Type == pubsub.DeletedEvent && event.Payload.ID == CurrentSessionID() { + // If the current session is deleted, clear the current session + SetCurrentSession("") + } + } + }() +} + +// SetCurrentSession changes the active session to the one with the specified ID. +func SetCurrentSession(sessionID string) { + if globalManager == nil { + logging.Warn("Session manager not initialized") + return + } + + globalManager.mu.Lock() + defer globalManager.mu.Unlock() + + globalManager.currentSessionID = sessionID + logging.Debug("Current session changed", "sessionID", sessionID) +} + +// CurrentSessionID returns the ID of the currently active session. +func CurrentSessionID() string { + if globalManager == nil { + logging.Warn("Session manager not initialized") + return "" + } + + globalManager.mu.RLock() + defer globalManager.mu.RUnlock() + + return globalManager.currentSessionID +} + +// CurrentSession returns the currently active session. +// If no session is set or the session cannot be found, it returns nil. +func CurrentSession() *Session { + if globalManager == nil { + logging.Warn("Session manager not initialized") + return nil + } + + sessionID := CurrentSessionID() + if sessionID == "" { + return nil + } + + session, err := globalManager.service.Get(context.Background(), sessionID) + if err != nil { + logging.Warn("Failed to get current session", "err", err) + return nil + } + + return &session +} \ No newline at end of file -- cgit v1.2.3