Skip to content

Commit e54faf7

Browse files
committed
Fix SSE stream hang by adding cancel handler for cleanup
- Add cancel() method to ReadableStream to properly clear keepalive interval - Prevents hanging connections when stream is closed or client disconnects - Improves resource cleanup and connection stability - Fixes issue where authenticated tool calls would hang after initial auth
1 parent f871766 commit e54faf7

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/index.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,19 +71,29 @@ export default {
7171
console.log('GET / with SSE - opening minimal stream for session', sessionId)
7272

7373
// Return minimal SSE stream that stays open but sends no events
74+
let keepaliveInterval: number | undefined
7475
const stream = new ReadableStream({
7576
start(controller) {
7677
// Send initial comment to establish connection
7778
controller.enqueue(new TextEncoder().encode(': connected\n\n'))
7879

7980
// Keep alive with periodic comments (not events)
80-
const interval = setInterval(() => {
81+
keepaliveInterval = setInterval(() => {
8182
try {
8283
controller.enqueue(new TextEncoder().encode(': ping\n\n'))
8384
} catch {
84-
clearInterval(interval)
85+
if (keepaliveInterval) {
86+
clearInterval(keepaliveInterval)
87+
}
8588
}
86-
}, 30000)
89+
}, 30000) as unknown as number
90+
},
91+
cancel() {
92+
// Clean up interval when stream is closed
93+
if (keepaliveInterval) {
94+
clearInterval(keepaliveInterval)
95+
}
96+
console.log('SSE stream cancelled for session', sessionId)
8797
}
8898
})
8999

0 commit comments

Comments
 (0)