Skip to content

Commit 6c3d4b1

Browse files
committed
feat: Refactor session event handler management to use unique IDs for reliable removal.
1 parent b8a836b commit 6c3d4b1

1 file changed

Lines changed: 16 additions & 7 deletions

File tree

go/session.go

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,11 @@ import (
99
"github.com/github/copilot-sdk/go/generated"
1010
)
1111

12+
type sessionHandler struct {
13+
id uint64
14+
fn SessionEventHandler
15+
}
16+
1217
// Session represents a single conversation session with the Copilot CLI.
1318
//
1419
// A session maintains conversation state, handles events, and manages tool execution.
@@ -44,7 +49,8 @@ type Session struct {
4449
// SessionID is the unique identifier for this session.
4550
SessionID string
4651
client *JSONRPCClient
47-
handlers []SessionEventHandler
52+
handlers []sessionHandler
53+
nextHandlerID uint64
4854
handlerMutex sync.RWMutex
4955
toolHandlers map[string]ToolHandler
5056
toolHandlersM sync.RWMutex
@@ -60,7 +66,7 @@ func NewSession(sessionID string, client *JSONRPCClient) *Session {
6066
return &Session{
6167
SessionID: sessionID,
6268
client: client,
63-
handlers: make([]SessionEventHandler, 0),
69+
handlers: make([]sessionHandler, 0),
6470
toolHandlers: make(map[string]ToolHandler),
6571
}
6672
}
@@ -139,16 +145,17 @@ func (s *Session) On(handler SessionEventHandler) func() {
139145
s.handlerMutex.Lock()
140146
defer s.handlerMutex.Unlock()
141147

142-
s.handlers = append(s.handlers, handler)
148+
id := s.nextHandlerID
149+
s.nextHandlerID++
150+
s.handlers = append(s.handlers, sessionHandler{id: id, fn: handler})
143151

144152
// Return unsubscribe function
145153
return func() {
146154
s.handlerMutex.Lock()
147155
defer s.handlerMutex.Unlock()
148156

149157
for i, h := range s.handlers {
150-
// Compare function pointers
151-
if &h == &handler {
158+
if h.id == id {
152159
s.handlers = append(s.handlers[:i], s.handlers[i+1:]...)
153160
break
154161
}
@@ -236,8 +243,10 @@ func (s *Session) handlePermissionRequest(requestData map[string]interface{}) (P
236243
// are recovered to prevent crashing the event dispatcher.
237244
func (s *Session) dispatchEvent(event SessionEvent) {
238245
s.handlerMutex.RLock()
239-
handlers := make([]SessionEventHandler, len(s.handlers))
240-
copy(handlers, s.handlers)
246+
handlers := make([]SessionEventHandler, 0, len(s.handlers))
247+
for _, h := range s.handlers {
248+
handlers = append(handlers, h.fn)
249+
}
241250
s.handlerMutex.RUnlock()
242251

243252
for _, handler := range handlers {

0 commit comments

Comments
 (0)