mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat: add assistant mode, SSE streaming, and OpenCode server integration (#214)
This commit is contained in:
1 parent
3cc24288a6
commit
c3d6549f01
133 files changed
+7284
-6293
No files matched your search
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user