| 11 | type Listener = () => void |
| 12 | |
| 13 | class StreamingManager { |
| 14 | // 支持多个并行 streaming,key 是 messageId |
| 15 | private dataMap = new Map<string, StreamingData>() |
| 16 | private listeners = new Set<Listener>() |
| 17 | private rafId: number | null = null |
| 18 | |
| 19 | start(pageId: string, messageId: string, aiService?: AIService): void { |
| 20 | this.dataMap.set(messageId, { pageId, messageId, content: '', aiService }) |
| 21 | this.notify() |
| 22 | } |
| 23 | |
| 24 | setAIService(messageId: string, aiService: AIService): void { |
| 25 | const data = this.dataMap.get(messageId) |
| 26 | if (data) { |
| 27 | data.aiService = aiService |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | update(messageId: string, content: string, reasoning?: string): void { |
| 32 | const data = this.dataMap.get(messageId) |
| 33 | if (!data) return |
| 34 | data.content = content |
| 35 | data.reasoning = reasoning |
| 36 | this.scheduleNotify() |
| 37 | } |
| 38 | |
| 39 | finish(messageId: string): StreamingData | null { |
| 40 | const result = this.dataMap.get(messageId) ?? null |
| 41 | this.dataMap.delete(messageId) |
| 42 | this.notify() |
| 43 | return result |
| 44 | } |
| 45 | |
| 46 | abort(messageId: string): void { |
| 47 | this.dataMap.delete(messageId) |
| 48 | this.notify() |
| 49 | } |
| 50 | |
| 51 | async stop(messageId: string): Promise<StreamingData | null> { |
| 52 | const data = this.dataMap.get(messageId) |
| 53 | if (data?.aiService) { |
| 54 | await data.aiService.stopStreaming() |
| 55 | } |
| 56 | return this.finish(messageId) |
| 57 | } |
| 58 | |
| 59 | async stopAll(): Promise<StreamingData[]> { |
| 60 | const messageIds = Array.from(this.dataMap.keys()) |
| 61 | const results = await Promise.all(messageIds.map((messageId) => this.stop(messageId))) |
| 62 | return results.filter((item): item is StreamingData => item !== null) |
| 63 | } |
| 64 | |
| 65 | reset(): void { |
| 66 | this.dataMap.clear() |
| 67 | this.notify() |
| 68 | } |
| 69 | |
| 70 | get(messageId: string): StreamingData | null { |
nothing calls this directly
no outgoing calls
no test coverage detected