manager.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package session
  2. import (
  3. "context"
  4. "sync"
  5. "github.com/opencode-ai/opencode/internal/logging"
  6. "github.com/opencode-ai/opencode/internal/pubsub"
  7. )
  8. // Manager handles session management, tracking the currently active session.
  9. type Manager struct {
  10. currentSessionID string
  11. service Service
  12. mu sync.RWMutex
  13. }
  14. // Global instance of the session manager
  15. var globalManager *Manager
  16. // InitManager initializes the global session manager with the provided service.
  17. func InitManager(service Service) {
  18. globalManager = &Manager{
  19. currentSessionID: "",
  20. service: service,
  21. }
  22. // Subscribe to session events to handle session deletions
  23. go func() {
  24. ctx := context.Background()
  25. eventCh := service.Subscribe(ctx)
  26. for event := range eventCh {
  27. if event.Type == pubsub.DeletedEvent && event.Payload.ID == CurrentSessionID() {
  28. // If the current session is deleted, clear the current session
  29. SetCurrentSession("")
  30. }
  31. }
  32. }()
  33. }
  34. // SetCurrentSession changes the active session to the one with the specified ID.
  35. func SetCurrentSession(sessionID string) {
  36. if globalManager == nil {
  37. logging.Warn("Session manager not initialized")
  38. return
  39. }
  40. globalManager.mu.Lock()
  41. defer globalManager.mu.Unlock()
  42. globalManager.currentSessionID = sessionID
  43. logging.Debug("Current session changed", "sessionID", sessionID)
  44. }
  45. // CurrentSessionID returns the ID of the currently active session.
  46. func CurrentSessionID() string {
  47. if globalManager == nil {
  48. logging.Warn("Session manager not initialized")
  49. return ""
  50. }
  51. globalManager.mu.RLock()
  52. defer globalManager.mu.RUnlock()
  53. return globalManager.currentSessionID
  54. }
  55. // CurrentSession returns the currently active session.
  56. // If no session is set or the session cannot be found, it returns nil.
  57. func CurrentSession() *Session {
  58. if globalManager == nil {
  59. logging.Warn("Session manager not initialized")
  60. return nil
  61. }
  62. sessionID := CurrentSessionID()
  63. if sessionID == "" {
  64. return nil
  65. }
  66. session, err := globalManager.service.Get(context.Background(), sessionID)
  67. if err != nil {
  68. logging.Warn("Failed to get current session", "err", err)
  69. return nil
  70. }
  71. return &session
  72. }