|
| 1 | +/** |
| 2 | + * AI 流式输出 IPC Handler |
| 3 | + * |
| 4 | + * 处理 ai:stream:start IPC 请求,通过 postJsonStream() 获取 SSE 流, |
| 5 | + * 将 chunk 以 50ms 节流推送到渲染进程。 |
| 6 | + * |
| 7 | + * 通信协议: |
| 8 | + * - 渲染进程 → 主进程:ipcRenderer.invoke('ai:stream:start', { requestId, method, payload }) |
| 9 | + * - 主进程 → 渲染进程: |
| 10 | + * - 'ai:stream:chunk' { requestId, chunk } |
| 11 | + * - 'ai:stream:end' { requestId } |
| 12 | + * - 'ai:stream:error' { requestId, error } |
| 13 | + */ |
| 14 | + |
| 15 | +import { safeHandle } from '../ipcUtils.js'; |
| 16 | +import { logger } from '../logger.js'; |
| 17 | +import { postJsonStream } from './utils.js'; |
| 18 | + |
| 19 | +// ================================================================ |
| 20 | +// 节流配置 |
| 21 | +// ================================================================ |
| 22 | + |
| 23 | +/** IPC chunk 推送节流间隔(ms),防止高频 chunk 风暴 */ |
| 24 | +const CHUNK_THROTTLE_MS = 50; |
| 25 | + |
| 26 | +/** 活跃的流式请求 AbortController 映射(requestId → controller) */ |
| 27 | +const activeStreams = new Map<string, AbortController>(); |
| 28 | + |
| 29 | +// ================================================================ |
| 30 | +// IPC Handler 注册 |
| 31 | +// ================================================================ |
| 32 | + |
| 33 | +/** |
| 34 | + * 注册 ai:stream:start handler |
| 35 | + * |
| 36 | + * 渲染进程通过 invoke 发起流式请求,主进程逐 chunk 推送到渲染进程。 |
| 37 | + * 使用 50ms 节流合并高频 chunk,防止 IPC 风暴。 |
| 38 | + */ |
| 39 | +export function registerStreamHandler(): void { |
| 40 | + safeHandle( |
| 41 | + 'ai:stream:start', |
| 42 | + async ( |
| 43 | + event, |
| 44 | + args: { |
| 45 | + requestId: string; |
| 46 | + /** API 路径,如 /api/v1/ai/summarize/stream */ |
| 47 | + method: string; |
| 48 | + /** 请求体 */ |
| 49 | + payload: Record<string, unknown>; |
| 50 | + /** 认证 token */ |
| 51 | + authToken?: string; |
| 52 | + /** 用户 API Key */ |
| 53 | + userApiKey?: string; |
| 54 | + }, |
| 55 | + ) => { |
| 56 | + const { requestId, method, payload, authToken, userApiKey } = args; |
| 57 | + const sender = event.sender; |
| 58 | + |
| 59 | + logger.info(`[AI] [stream] Start: requestId=${requestId}, method=${method}`); |
| 60 | + |
| 61 | + // 为该流式请求创建 AbortController |
| 62 | + const abortController = new AbortController(); |
| 63 | + activeStreams.set(requestId, abortController); |
| 64 | + |
| 65 | + // 50ms 节流缓冲 |
| 66 | + let chunkBuffer = ''; |
| 67 | + let throttleTimer: ReturnType<typeof setTimeout> | null = null; |
| 68 | + let cancelled = false; |
| 69 | + |
| 70 | + /** 将缓冲区内的 chunk 一次性推送到渲染进程 */ |
| 71 | + function flushChunks(): void { |
| 72 | + if (cancelled || !chunkBuffer) return; |
| 73 | + if (sender.isDestroyed()) return; |
| 74 | + sender.send('ai:stream:chunk', { requestId, chunk: chunkBuffer }); |
| 75 | + chunkBuffer = ''; |
| 76 | + throttleTimer = null; |
| 77 | + } |
| 78 | + |
| 79 | + try { |
| 80 | + const stream = postJsonStream( |
| 81 | + method, |
| 82 | + payload, |
| 83 | + authToken, |
| 84 | + userApiKey, |
| 85 | + ); |
| 86 | + |
| 87 | + for await (const chunk of stream) { |
| 88 | + if (cancelled || abortController.signal.aborted) { |
| 89 | + cancelled = true; |
| 90 | + break; |
| 91 | + } |
| 92 | + |
| 93 | + chunkBuffer += chunk; |
| 94 | + |
| 95 | + // 启动节流定时器(仅在无定时器运行时) |
| 96 | + if (!throttleTimer) { |
| 97 | + throttleTimer = setTimeout(flushChunks, CHUNK_THROTTLE_MS); |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + // 流结束:刷出剩余缓冲 |
| 102 | + if (throttleTimer) { |
| 103 | + clearTimeout(throttleTimer); |
| 104 | + throttleTimer = null; |
| 105 | + } |
| 106 | + flushChunks(); |
| 107 | + |
| 108 | + // 推送结束信号 |
| 109 | + if (!cancelled && !sender.isDestroyed()) { |
| 110 | + sender.send('ai:stream:end', { requestId }); |
| 111 | + } |
| 112 | + |
| 113 | + logger.info(`[AI] [stream] Complete: requestId=${requestId}`); |
| 114 | + return { ok: true, requestId }; |
| 115 | + } catch (err) { |
| 116 | + // 流异常:刷出剩余缓冲,推送错误信号 |
| 117 | + if (throttleTimer) { |
| 118 | + clearTimeout(throttleTimer); |
| 119 | + throttleTimer = null; |
| 120 | + } |
| 121 | + flushChunks(); |
| 122 | + |
| 123 | + const errorMessage = err instanceof Error ? err.message : String(err); |
| 124 | + logger.error(`[AI] [stream] Error: requestId=${requestId}, error=${errorMessage}`); |
| 125 | + |
| 126 | + if (!cancelled && !sender.isDestroyed()) { |
| 127 | + sender.send('ai:stream:error', { requestId, error: errorMessage }); |
| 128 | + } |
| 129 | + |
| 130 | + return { ok: false, requestId, error: errorMessage }; |
| 131 | + } finally { |
| 132 | + activeStreams.delete(requestId); |
| 133 | + } |
| 134 | + }, |
| 135 | + ); |
| 136 | + |
| 137 | + // 注册取消流式请求的 handler |
| 138 | + safeHandle( |
| 139 | + 'ai:stream:cancel', |
| 140 | + async (_event, args: { requestId: string }) => { |
| 141 | + const { requestId } = args; |
| 142 | + logger.info(`[AI] [stream] Cancel requested: requestId=${requestId}`); |
| 143 | + const controller = activeStreams.get(requestId); |
| 144 | + if (controller) { |
| 145 | + controller.abort(); |
| 146 | + activeStreams.delete(requestId); |
| 147 | + logger.info(`[AI] [stream] Cancelled: requestId=${requestId}`); |
| 148 | + } |
| 149 | + return { ok: true }; |
| 150 | + }, |
| 151 | + ); |
| 152 | +} |
0 commit comments