import { log, error as logError } from '../logger' export interface SessionEvent { id: string sessionId: string type: string payload: unknown direction: 'inbound' | 'outbound' seqNum: number createdAt: number } type Subscriber = (event: SessionEvent) => void const MAX_EVENTS_PER_BUS = 5000 // UUID dedup ring — must outlive the retained event window so that // hasEventWithUuid keeps returning true for messages whose bus events were // already evicted. Without this, long sessions (>2500 retained events) lose // dedup state and WS reconnect replays duplicate assistant messages into the // web UI. const MAX_SEEN_UUIDS_PER_BUS = 20000 export class EventBus { private subscribers = new Set() private events: SessionEvent[] = [] private seqNum = 0 private closed = false private seenUuids = new Set() private seenUuidRing: (string | undefined)[] = new Array( MAX_SEEN_UUIDS_PER_BUS, ) private seenUuidWriteIdx = 0 /** * Latest models_state payload for the session, kept OUT of the retained * event window. The worker reports models_state only once per bridge * connect, while the event log is mutable (/clear wipes it, the bounded * window evicts old entries) — without this snapshot any log loss makes * the web UI's model selector permanently gray until the worker * reconnects. Lives on the bus so it is dropped when the session is * deleted (removeEventBus) and survives clearHistory(). */ modelsStateSnapshot: Record | null = null /** * Turn-signal for status derivation (ws-handler.ts / worker-events.ts / * control.ts): `true` while a turn is in progress (set by user events), * `false` once it ends (result / result_success / interrupt). * * The REPL bridge's write paths are not strictly ordered — the synthetic * turn-end result can be POSTed BEFORE the final mirrored assistant * message (transcript-mirror render race, flush-gate bypass). Deriving * `running` from such a late assistant flips the session back to running * AFTER the turn ended, so the web UI input stays engaged and every new * message lands in the queue instead of being sent. `false` by default: * an assistant arriving with no user signal in flight belongs to an * already-ended turn. */ turnActive = false subscribe(callback: Subscriber): () => void { this.subscribers.add(callback) return () => this.subscribers.delete(callback) } subscriberCount(): number { return this.subscribers.size } publish( event: Omit, options?: { transient?: boolean }, ): SessionEvent { if (this.closed) throw new Error('EventBus is closed') const full: SessionEvent = { ...event, seqNum: ++this.seqNum, createdAt: Date.now(), } // Transient events (streaming deltas) are delivered to live subscribers // but excluded from the retained history window — replaying them is // meaningless (the final assistant message carries the full content) and // a single turn's worth of deltas would evict real messages from the // bounded window. if (!options?.transient) { this.events.push(full) // Evict oldest events when exceeding limit if (this.events.length > MAX_EVENTS_PER_BUS) { this.events = this.events.slice(-Math.floor(MAX_EVENTS_PER_BUS / 2)) } } // UUID dedup applies to transient events too: HybridTransport retries // POST batches whose response was lost, re-delivering the same // stream_event — without this the delta double-renders in the web UI. const payloadUuid = (event.payload as Record | null)?.uuid if (typeof payloadUuid === 'string' && payloadUuid) { this.recordSeenUuid(payloadUuid) } log( `[RC-DEBUG] bus publish: sessionId=${event.sessionId} type=${event.type} dir=${event.direction} seq=${full.seqNum} subscribers=${this.subscribers.size}`, event.type === 'error' ? `payload=${JSON.stringify(event.payload)}` : '', ) for (const cb of this.subscribers) { try { cb(full) } catch (err) { logError(`[RC-DEBUG] bus subscriber error:`, err) } } return full } getLastSeqNum(): number { return this.seqNum } getEventsSince(seqNum: number): SessionEvent[] { const idx = this.events.findIndex(e => e.seqNum > seqNum) if (idx === -1) return [] return this.events.slice(idx) } /** Drop all retained (non-transient) events from the replay window. * Used by POST /web/sessions/:id/clear so re-entry / other team members * load an empty transcript. Seq numbers keep increasing (Last-Event-ID * stays monotonic), live subscribers stay connected, and uuid dedup state * is preserved so worker echo/replay dedup still works after a clear. */ clearHistory(): void { this.events = [] } /** Check whether an event with the given UUID has already been published. * Used to dedup child-process echoes of replayed history — without this, * WS reconnect → server replays all events → child echoes inbound messages * back → server re-publishes them → web UI shows duplicates. * Backed by a bounded FIFO set that survives event-window eviction. */ hasEventWithUuid(uuid: string): boolean { return this.seenUuids.has(uuid) } private recordSeenUuid(uuid: string): void { if (this.seenUuids.has(uuid)) return const evicted = this.seenUuidRing[this.seenUuidWriteIdx] if (evicted !== undefined) { this.seenUuids.delete(evicted) } this.seenUuidRing[this.seenUuidWriteIdx] = uuid this.seenUuids.add(uuid) this.seenUuidWriteIdx = (this.seenUuidWriteIdx + 1) % MAX_SEEN_UUIDS_PER_BUS } close() { this.closed = true this.subscribers.clear() this.seenUuids.clear() this.seenUuidRing.fill(undefined) this.seenUuidWriteIdx = 0 } } /** Global registry of per-session event buses */ const buses = new Map() export function getEventBus(sessionId: string): EventBus { let bus = buses.get(sessionId) if (!bus) { bus = new EventBus() buses.set(sessionId, bus) } return bus } export function removeEventBus(sessionId: string) { const bus = buses.get(sessionId) if (bus) { bus.close() buses.delete(sessionId) } } export function getAllEventBuses(): Map { return buses } /** Global registry of per-channel-group ACP event buses */ const acpBuses = new Map() export function getAcpEventBus(channelGroupId: string): EventBus { let bus = acpBuses.get(channelGroupId) if (!bus) { bus = new EventBus() acpBuses.set(channelGroupId, bus) } return bus } export function removeAcpEventBus(channelGroupId: string) { const bus = acpBuses.get(channelGroupId) if (bus) { bus.close() acpBuses.delete(channelGroupId) } }