feat: add assistant mode, SSE streaming, and OpenCode server integration (#214)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-02 21:51:37 -04:00
1 parent 3cc24288a6
commit c3d6549f01
133 files changed
+7284 -6293

No files matched your search

-7
View File
@@ -52,13 +52,6 @@ describe('getSwipeBackTarget', () => {
});
});
describe('memories route', () => {
it('returns repo path', () => {
expect(getSwipeBackTarget('/repos/42/memories', '')).toBe('/repos/42');
expect(getSwipeBackTarget('/repos/123/memories', '?filter=all')).toBe('/repos/123');
});
});
describe('schedules routes', () => {
it('returns repo path for repo schedules', () => {
expect(getSwipeBackTarget('/repos/42/schedules', '')).toBe('/repos/42');
-5
View File
@@ -30,11 +30,6 @@ export function getSwipeBackTarget(pathname: string, search = ''): string | null
return '/';
}
if (/^\/repos\/[^/]+\/memories$/.test(pathname)) {
const repoId = pathname.split('/')[2];
return `/repos/${repoId}`;
}
if (/^\/repos\/[^/]+\/schedules$/.test(pathname)) {
const repoId = pathname.split('/')[2];
return `/repos/${repoId}`;
@@ -0,0 +1,97 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { OpenCodeEventStream, TestEventStreamTransport } from '..'
import type { EventStreamHealthState } from '..'
describe('OpenCodeEventStream', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('delivers raw events to the global monitor', () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const onEvent = vi.fn()
stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent })
transport.openConnection()
transport.connected()
transport.message({ type: 'permission.asked', properties: { sessionID: 'session-1' }, directory: '/repo' })
expect(onEvent).toHaveBeenCalledWith({
type: 'permission.asked',
properties: { sessionID: 'session-1' },
directory: '/repo',
})
})
it('publishes health through monitor output', () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const healthStates: EventStreamHealthState[] = []
stream.subscribeGlobalMonitor({
directories: [],
onEvent: vi.fn(),
onHealthChange: (health) => healthStates.push(health),
})
transport.openConnection()
expect(healthStates.at(-1)).toMatchObject({ isConnected: true, isHealthy: true, isStalled: false })
})
it('reconnects when the watchdog detects a stall', async () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
stream.subscribeGlobalMonitor({ directories: [], onEvent: vi.fn() })
transport.openConnection()
await vi.advanceTimersByTimeAsync(105_001)
expect(transport.closeCount).toBeGreaterThan(0)
})
it('diffs global monitor directories through the transport adapter', async () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const subscription = stream.subscribeGlobalMonitor({ directories: ['/repo-a'], onEvent: vi.fn() })
transport.openConnection()
transport.connected('client-1')
subscription.updateDirectories(['/repo-a', '/repo-b'])
await Promise.resolve()
subscription.updateDirectories(['/repo-b'])
await Promise.resolve()
expect(transport.posts).toContainEqual({
path: '/api/sse/subscribe',
body: { clientId: 'client-1', directories: ['/repo-b'] },
})
expect(transport.posts).toContainEqual({
path: '/api/sse/unsubscribe',
body: { clientId: 'client-1', directories: ['/repo-a'] },
})
})
it('reports visibility through the transport adapter', async () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const subscription = stream.subscribeToDirectory({ directory: '/repo', onEvent: vi.fn() })
transport.openConnection()
transport.connected('client-1')
subscription.reportVisibility(true, 'session-1')
await Promise.resolve()
expect(transport.posts).toContainEqual({
path: '/api/sse/visibility',
body: { clientId: 'client-1', visible: true, activeSessionId: 'session-1' },
})
})
})
@@ -0,0 +1,31 @@
import type { EventStreamConnection, EventStreamTransport, EventStreamTransportHandlers } from './types'
export function createBrowserEventStreamTransport(): EventStreamTransport {
return {
open(url: string, handlers: EventStreamTransportHandlers): EventStreamConnection {
const eventSource = new EventSource(url, { withCredentials: true })
eventSource.onopen = handlers.onOpen
eventSource.onerror = handlers.onError
eventSource.onmessage = (event) => handlers.onMessage(event.data)
eventSource.addEventListener('connected', (event) => {
handlers.onConnected((event as MessageEvent).data)
})
eventSource.addEventListener('heartbeat', handlers.onHeartbeat)
return {
close: () => eventSource.close(),
}
},
async post(path: string, body: unknown): Promise<boolean> {
const response = await fetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
return response.ok
},
}
}
@@ -0,0 +1,13 @@
export { openCodeEventStream, OpenCodeEventStream } from './openCodeEventStream'
export { createBrowserEventStreamTransport } from './browserTransport'
export { TestEventStreamTransport } from './testTransport'
export type {
EventStreamConnection,
EventStreamHealthState,
EventStreamStatusHandler,
EventStreamSubscription,
EventStreamTransport,
EventStreamTransportHandlers,
GlobalMonitorSubscription,
OpenCodeEventHandler,
} from './types'
@@ -0,0 +1,401 @@
import { DEFAULTS } from '@opencode-manager/shared/config'
import { createBrowserEventStreamTransport } from './browserTransport'
import type {
EventStreamHealthState,
EventStreamStatusHandler,
EventStreamSubscription,
EventStreamTransport,
GlobalMonitorSubscription,
OpenCodeEventHandler,
} from './types'
interface Subscriber {
id: string
onEvent: OpenCodeEventHandler
onStatusChange?: EventStreamStatusHandler
onHealthChange?: (state: EventStreamHealthState) => void
directories: Set<string>
}
interface OpenCodeEventStreamOptions {
transport?: EventStreamTransport
}
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS, STALL_THRESHOLD_MS, WATCHDOG_TICK_MS } = DEFAULTS.SSE
export class OpenCodeEventStream {
private connection: { close(): void } | null = null
private readonly transport: EventStreamTransport
private subscribers = new Map<string, Subscriber>()
private directoryRefCounts = new Map<string, number>()
private pendingDirectories = new Set<string>()
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
private reconnectDelay: number = RECONNECT_DELAY_MS
private connected = false
private subscriberIdCounter = 0
private clientId: string | null = null
private lastEventAt: number | null = null
private watchdogTimer: ReturnType<typeof setInterval> | null = null
constructor(options: OpenCodeEventStreamOptions = {}) {
this.transport = options.transport ?? createBrowserEventStreamTransport()
}
subscribeGlobalMonitor(input: {
directories: string[]
onEvent: OpenCodeEventHandler
onStatusChange?: EventStreamStatusHandler
onHealthChange?: (state: EventStreamHealthState) => void
}): GlobalMonitorSubscription {
const id = this.addSubscriber(input.onEvent, input.onStatusChange, input.onHealthChange)
this.updateSubscriberDirectories(id, input.directories)
return {
updateDirectories: (directories) => this.updateSubscriberDirectories(id, directories),
reconnect: () => this.reconnect(),
reportVisibility: (visible, activeSessionId) => this.reportVisibility(visible, activeSessionId),
dispose: () => this.removeSubscriber(id),
}
}
subscribeToDirectory(input: {
directory: string
onEvent: OpenCodeEventHandler
onStatusChange?: EventStreamStatusHandler
onHealthChange?: (state: EventStreamHealthState) => void
}): EventStreamSubscription {
const id = this.addSubscriber(input.onEvent, input.onStatusChange, input.onHealthChange)
this.updateSubscriberDirectories(id, [input.directory])
return {
reconnect: () => this.reconnect(),
reportVisibility: (visible, activeSessionId) => this.reportVisibility(visible, activeSessionId),
dispose: () => this.removeSubscriber(id),
}
}
getHealth(): EventStreamHealthState {
return this.buildHealth()
}
private addSubscriber(
onEvent: OpenCodeEventHandler,
onStatusChange?: EventStreamStatusHandler,
onHealthChange?: (state: EventStreamHealthState) => void,
): string {
const id = `sub_${++this.subscriberIdCounter}`
this.subscribers.set(id, {
id,
onEvent,
onStatusChange,
onHealthChange,
directories: new Set(),
})
onStatusChange?.(this.connected)
onHealthChange?.(this.buildHealth())
if (this.subscribers.size === 1) {
this.connect()
}
return id
}
private removeSubscriber(id: string): void {
const subscriber = this.subscribers.get(id)
if (!subscriber) return
this.updateSubscriberDirectories(id, [])
this.subscribers.delete(id)
if (this.subscribers.size === 0) {
this.disconnect()
}
}
private updateSubscriberDirectories(id: string, directories: string[]): void {
const subscriber = this.subscribers.get(id)
if (!subscriber) return
const nextDirectories = new Set(directories.filter(Boolean))
for (const directory of subscriber.directories) {
if (!nextDirectories.has(directory)) {
this.removeDirectory(directory)
}
}
for (const directory of nextDirectories) {
if (!subscriber.directories.has(directory)) {
this.addDirectory(directory)
}
}
subscriber.directories = nextDirectories
}
private addDirectory(directory: string): void {
const currentCount = this.directoryRefCounts.get(directory) ?? 0
this.directoryRefCounts.set(directory, currentCount + 1)
if (currentCount > 0) return
if (this.clientId && this.connected) {
void this.subscribeToRemoteDirectories([directory])
return
}
this.pendingDirectories.add(directory)
if (!this.connection) {
this.reconnect()
}
}
private removeDirectory(directory: string): void {
const currentCount = this.directoryRefCounts.get(directory) ?? 0
if (currentCount > 1) {
this.directoryRefCounts.set(directory, currentCount - 1)
return
}
this.directoryRefCounts.delete(directory)
this.pendingDirectories.delete(directory)
if (this.clientId && this.connected) {
void this.transport.post('/api/sse/unsubscribe', {
clientId: this.clientId,
directories: [directory],
})
}
}
private buildUrl(): string {
const url = new URL('/api/sse/stream', window.location.origin)
const directories = Array.from(this.directoryRefCounts.keys())
if (directories.length > 0) {
url.searchParams.set('directories', directories.join(','))
}
return url.toString()
}
private connect(): void {
if (this.connection) return
this.connection = this.transport.open(this.buildUrl(), {
onOpen: () => this.handleOpen(),
onError: () => this.handleError(),
onMessage: (data) => this.handleMessage(data),
onConnected: (data) => this.handleConnected(data),
onHeartbeat: () => this.markActivity(),
})
}
private handleOpen(): void {
this.connected = true
this.reconnectDelay = RECONNECT_DELAY_MS
this.startWatchdog()
this.markActivity()
this.notifyStatusChange(true)
}
private handleError(): void {
this.connected = false
this.clientId = null
this.stopWatchdog()
this.lastEventAt = null
if (this.connection) {
this.connection.close()
this.connection = null
}
this.notifyStatusChange(false)
this.notifyHealth()
if (this.subscribers.size > 0) {
this.scheduleReconnect()
}
}
private handleMessage(data: string): void {
try {
this.markActivity()
this.broadcast(JSON.parse(data))
} catch {
this.markActivity()
}
}
private handleConnected(data: string): void {
try {
const parsed = JSON.parse(data) as { clientId?: unknown }
if (typeof parsed.clientId === 'string') {
this.clientId = parsed.clientId
}
} catch {
this.clientId = null
}
this.connected = true
this.startWatchdog()
this.markActivity()
this.notifyStatusChange(true)
this.flushPendingDirectories()
}
private disconnect(): void {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
this.stopWatchdog()
this.connection?.close()
this.connection = null
this.connected = false
this.clientId = null
this.lastEventAt = null
this.pendingDirectories.clear()
this.notifyHealth()
}
private reconnect(): void {
if (this.subscribers.size === 0) return
this.reconnectDelay = RECONNECT_DELAY_MS
this.disconnectConnectionOnly()
this.connect()
}
private disconnectConnectionOnly(): void {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
this.stopWatchdog()
this.connection?.close()
this.connection = null
this.connected = false
this.clientId = null
this.lastEventAt = null
this.pendingDirectories = new Set(this.directoryRefCounts.keys())
this.notifyStatusChange(false)
this.notifyHealth()
}
private scheduleReconnect(): void {
if (this.reconnectTimeout) return
this.reconnectTimeout = setTimeout(() => {
this.reconnectTimeout = null
this.reconnectDelay = Math.min(this.reconnectDelay * 2, MAX_RECONNECT_DELAY_MS)
this.connect()
}, this.reconnectDelay)
}
private startWatchdog(): void {
if (this.watchdogTimer) return
this.watchdogTimer = setInterval(() => {
if (this.lastEventAt == null) return
if (Date.now() - this.lastEventAt > STALL_THRESHOLD_MS) {
this.handleStall()
}
}, WATCHDOG_TICK_MS)
}
private stopWatchdog(): void {
if (!this.watchdogTimer) return
clearInterval(this.watchdogTimer)
this.watchdogTimer = null
}
private handleStall(): void {
this.disconnectConnectionOnly()
this.connect()
}
private markActivity(): void {
this.lastEventAt = Date.now()
this.notifyHealth()
}
private buildHealth(): EventStreamHealthState {
const isStalled = this.connected && this.lastEventAt != null && Date.now() - this.lastEventAt > STALL_THRESHOLD_MS
return {
isConnected: this.connected,
isHealthy: this.connected && this.lastEventAt != null && !isStalled,
lastEventAt: this.lastEventAt,
isStalled,
}
}
private notifyHealth(): void {
const health = this.buildHealth()
this.subscribers.forEach((subscriber) => {
try {
subscriber.onHealthChange?.(health)
} catch {
void 0
}
})
}
private notifyStatusChange(connected: boolean): void {
this.subscribers.forEach((subscriber) => {
try {
subscriber.onStatusChange?.(connected)
} catch {
void 0
}
})
}
private broadcast(data: unknown): void {
this.subscribers.forEach((subscriber) => {
try {
subscriber.onEvent(data)
} catch {
void 0
}
})
}
private async subscribeToRemoteDirectories(directories: string[]): Promise<void> {
if (!this.clientId || directories.length === 0) return
const success = await this.transport.post('/api/sse/subscribe', {
clientId: this.clientId,
directories,
})
if (!success) {
directories.forEach((directory) => this.pendingDirectories.add(directory))
this.reconnect()
}
}
private flushPendingDirectories(): void {
if (this.pendingDirectories.size === 0) return
if (!this.clientId || !this.connected) return
const directories = Array.from(this.pendingDirectories)
this.pendingDirectories.clear()
void this.subscribeToRemoteDirectories(directories)
}
private reportVisibility(visible: boolean, activeSessionId?: string): void {
if (!this.clientId || !this.connected) return
void this.transport.post('/api/sse/visibility', {
clientId: this.clientId,
visible,
activeSessionId: activeSessionId ?? null,
})
}
}
export const openCodeEventStream = new OpenCodeEventStream()
@@ -0,0 +1,46 @@
import type { EventStreamConnection, EventStreamTransport, EventStreamTransportHandlers } from './types'
export class TestEventStreamTransport implements EventStreamTransport {
readonly posts: Array<{ path: string; body: unknown }> = []
closeCount = 0
private handlers: EventStreamTransportHandlers | null = null
private connection: EventStreamConnection | null = null
open(_url: string, handlers: EventStreamTransportHandlers): EventStreamConnection {
this.handlers = handlers
this.connection = {
close: () => {
if (this.connection) {
this.connection = null
this.closeCount += 1
}
},
}
return this.connection
}
async post(path: string, body: unknown): Promise<boolean> {
this.posts.push({ path, body })
return true
}
openConnection(): void {
this.handlers?.onOpen()
}
connected(clientId = 'test-client'): void {
this.handlers?.onConnected(JSON.stringify({ clientId }))
}
message(data: unknown): void {
this.handlers?.onMessage(JSON.stringify(data))
}
heartbeat(): void {
this.handlers?.onHeartbeat()
}
fail(): void {
this.handlers?.onError()
}
}
@@ -0,0 +1,36 @@
export type OpenCodeEventHandler = (data: unknown) => void
export type EventStreamStatusHandler = (connected: boolean) => void
export interface EventStreamHealthState {
isConnected: boolean
isHealthy: boolean
lastEventAt: number | null
isStalled: boolean
}
export interface EventStreamConnection {
close(): void
}
export interface EventStreamTransportHandlers {
onOpen(): void
onError(): void
onMessage(data: string): void
onConnected(data: string): void
onHeartbeat(): void
}
export interface EventStreamTransport {
open(url: string, handlers: EventStreamTransportHandlers): EventStreamConnection
post(path: string, body: unknown): Promise<boolean>
}
export interface EventStreamSubscription {
dispose(): void
reconnect(): void
reportVisibility(visible: boolean, activeSessionId?: string): void
}
export interface GlobalMonitorSubscription extends EventStreamSubscription {
updateDirectories(directories: string[]): void
}
-351
View File
@@ -1,351 +0,0 @@
import { DEFAULTS } from '@opencode-manager/shared/config'
type SSEEventHandler = (data: unknown) => void
type SSEStatusHandler = (connected: boolean) => void
interface SSESubscriber {
id: string
onMessage: SSEEventHandler
onStatusChange?: SSEStatusHandler
}
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS } = DEFAULTS.SSE
class SSEManager {
private static instance: SSEManager
private eventSource: EventSource | null = null
private subscribers: Map<string, SSESubscriber> = new Map()
private directoryRefCounts: Map<string, number> = new Map()
private pendingDirectories: Set<string> = new Set()
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
private reconnectDelay: number = RECONNECT_DELAY_MS
private isConnected = false
private subscriberIdCounter = 0
private clientId: string | null = null
private constructor() {}
static getInstance(): SSEManager {
if (!SSEManager.instance) {
SSEManager.instance = new SSEManager()
}
return SSEManager.instance
}
subscribe(
onMessage: SSEEventHandler,
onStatusChange?: SSEStatusHandler
): () => void {
const id = `sub_${++this.subscriberIdCounter}`
const subscriber: SSESubscriber = {
id,
onMessage,
onStatusChange
}
this.subscribers.set(id, subscriber)
if (onStatusChange) {
onStatusChange(this.isConnected)
}
if (this.subscribers.size === 1) {
this.connect()
}
return () => this.unsubscribe(id)
}
private unsubscribe(id: string): void {
this.subscribers.delete(id)
if (this.subscribers.size === 0) {
this.disconnect()
}
}
addDirectory(directory: string): () => void {
const currentCount = this.directoryRefCounts.get(directory) ?? 0
this.directoryRefCounts.set(directory, currentCount + 1)
if (currentCount === 0) {
if (this.clientId && this.isConnected) {
this.subscribeToDirectory(directory)
} else {
this.pendingDirectories.add(directory)
if (!this.eventSource) {
this.reconnect()
}
}
}
return () => this.cleanupDirectory(directory)
}
private cleanupDirectory(directory: string): void {
const currentCount = this.directoryRefCounts.get(directory) ?? 0
if (currentCount <= 1) {
this.directoryRefCounts.delete(directory)
this.pendingDirectories.delete(directory)
if (this.clientId && this.isConnected) {
fetch('/api/sse/unsubscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
}).catch(() => {})
}
} else {
this.directoryRefCounts.set(directory, currentCount - 1)
}
}
private subscribeToDirectory(directory: string): void {
fetch('/api/sse/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: this.clientId, directories: [directory] })
}).then(res => {
if (!res.ok) {
this.reconnect()
}
}).catch(() => {
this.reconnect()
})
}
private flushPendingDirectories(): void {
if (this.pendingDirectories.size === 0) return
if (!this.clientId || !this.isConnected) return
const dirs = Array.from(this.pendingDirectories)
this.pendingDirectories.clear()
fetch('/api/sse/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: this.clientId, directories: dirs })
}).then(res => {
if (!res.ok) {
dirs.forEach(d => this.pendingDirectories.add(d))
this.reconnect()
}
}).catch(() => {
dirs.forEach(d => this.pendingDirectories.add(d))
this.reconnect()
})
}
removeDirectory(directory: string): void {
this.cleanupDirectory(directory)
}
getDirectories(): string[] {
return Array.from(this.directoryRefCounts.keys())
}
private buildUrl(): string {
const url = new URL('/api/sse/stream', window.location.origin)
if (this.directoryRefCounts.size > 0) {
url.searchParams.set('directories', Array.from(this.directoryRefCounts.keys()).join(','))
}
return url.toString()
}
private connect(): void {
if (this.eventSource) return
const url = this.buildUrl()
this.eventSource = new EventSource(url, { withCredentials: true })
this.eventSource.onopen = () => {
this.isConnected = true
this.reconnectDelay = RECONNECT_DELAY_MS
this.notifyStatusChange(true)
}
this.eventSource.onerror = () => {
this.isConnected = false
this.clientId = null
this.notifyStatusChange(false)
if (this.eventSource) {
this.eventSource.close()
this.eventSource = null
}
if (this.subscribers.size > 0) {
this.scheduleReconnect()
}
}
this.eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data)
this.broadcast(data)
} catch {
// Ignore parse errors
}
}
this.eventSource.addEventListener('connected', (event) => {
try {
const data = JSON.parse((event as MessageEvent).data)
if (data.clientId) {
this.clientId = data.clientId
}
this.isConnected = true
this.notifyStatusChange(true)
this.flushPendingDirectories()
} catch {
// Ignore
}
})
this.eventSource.addEventListener('heartbeat', () => {
// Heartbeat received - connection is alive
})
}
private disconnect(): void {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
if (this.eventSource) {
this.eventSource.close()
this.eventSource = null
}
this.isConnected = false
this.clientId = null
}
private scheduleReconnect(): void {
if (this.reconnectTimeout) return
this.reconnectTimeout = setTimeout(() => {
this.reconnectTimeout = null
this.reconnectDelay = Math.min(this.reconnectDelay * 2, MAX_RECONNECT_DELAY_MS)
this.connect()
}, this.reconnectDelay)
}
private notifyStatusChange(connected: boolean): void {
this.subscribers.forEach(sub => {
if (sub.onStatusChange) {
try {
sub.onStatusChange(connected)
} catch {
// Ignore callback errors
}
}
})
}
private broadcast(data: unknown): void {
this.subscribers.forEach(sub => {
try {
sub.onMessage(data)
} catch {
// Ignore callback errors
}
})
}
reconnect(): void {
if (this.subscribers.size === 0) return
this.reconnectDelay = RECONNECT_DELAY_MS
this.disconnect()
this.connect()
}
getConnectionStatus(): boolean {
return this.isConnected
}
reportVisibility(visible: boolean, activeSessionId?: string): void {
if (!this.clientId || !this.isConnected) return
fetch('/api/sse/visibility', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: this.clientId, visible, activeSessionId: activeSessionId ?? null })
}).catch(() => {})
}
async ensureConnected(timeoutMs: number = 5000): Promise<boolean> {
if (this.isConnected && this.clientId) {
return true
}
if (this.subscribers.size === 0) {
return false
}
this.reconnectDelay = RECONNECT_DELAY_MS
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
if (this.eventSource) {
this.eventSource.close()
this.eventSource = null
}
return new Promise<boolean>((resolve) => {
const timeout = setTimeout(() => {
resolve(false)
}, timeoutMs)
const checkConnection = () => {
if (this.isConnected && this.clientId) {
clearTimeout(timeout)
resolve(true)
}
}
const originalNotify = this.notifyStatusChange.bind(this)
this.notifyStatusChange = (connected: boolean) => {
originalNotify(connected)
if (connected) {
this.notifyStatusChange = originalNotify
checkConnection()
}
}
this.connect()
})
}
}
export const sseManager = SSEManager.getInstance()
export function subscribeToSSE(
onMessage: SSEEventHandler,
onStatusChange?: SSEStatusHandler
): () => void {
return sseManager.subscribe(onMessage, onStatusChange)
}
export function addSSEDirectory(directory: string): () => void {
return sseManager.addDirectory(directory)
}
export function removeSSEDirectory(directory: string): void {
sseManager.removeDirectory(directory)
}
export function reconnectSSE(): void {
sseManager.reconnect()
}
export function isSSEConnected(): boolean {
return sseManager.getConnectionStatus()
}
export async function ensureSSEConnected(timeoutMs?: number): Promise<boolean> {
return sseManager.ensureConnected(timeoutMs)
}