(chunk, threadId)
| 92 | * @returns {Boolean} - Returns true if processing should stop (e.g. error, finished, interrupted) |
| 93 | */ |
| 94 | const handleStreamChunk = (chunk, threadId) => { |
| 95 | const { status, msg, request_id, message: chunkMessage } = chunk |
| 96 | const threadState = getThreadState(threadId) |
| 97 | |
| 98 | if (!threadState) return false |
| 99 | |
| 100 | switch (status) { |
| 101 | case 'init': |
| 102 | { |
| 103 | const resolvedRequestId = request_id || threadState.pendingRequestId |
| 104 | if (resolvedRequestId) { |
| 105 | threadState.pendingRequestId = resolvedRequestId |
| 106 | } |
| 107 | if (resolvedRequestId && msg && msg.type !== 'system') { |
| 108 | const localHumanMessage = threadState.onGoingConv.msgChunks[resolvedRequestId]?.find( |
| 109 | (item) => item?.type === 'human' || item?.role === 'user' |
| 110 | ) |
| 111 | const initMessage = { |
| 112 | ...msg, |
| 113 | id: msg?.id || resolvedRequestId, |
| 114 | extra_metadata: { |
| 115 | ...(msg?.extra_metadata || {}), |
| 116 | request_id: resolvedRequestId |
| 117 | } |
| 118 | } |
| 119 | if (localHumanMessage?.image_content && !initMessage.image_content) { |
| 120 | initMessage.message_type = localHumanMessage.message_type || initMessage.message_type |
| 121 | initMessage.image_content = localHumanMessage.image_content |
| 122 | } |
| 123 | threadState.onGoingConv.msgChunks[resolvedRequestId] = [initMessage] |
| 124 | } |
| 125 | } |
| 126 | // 只有在服务端确认 init 后,才展示“正在回复”的加载动画。 |
| 127 | threadState.replyLoadingVisible = true |
| 128 | return false |
| 129 | |
| 130 | case 'loading': |
| 131 | { |
| 132 | const messageChunk = loadingMessageChunk(chunk) |
| 133 | if (messageChunk?.id) { |
| 134 | if (streamSmoother) { |
| 135 | streamSmoother.pushChunk(messageChunk, threadId) |
| 136 | } else { |
| 137 | if (!threadState.onGoingConv.msgChunks[messageChunk.id]) { |
| 138 | threadState.onGoingConv.msgChunks[messageChunk.id] = [] |
| 139 | } |
| 140 | threadState.onGoingConv.msgChunks[messageChunk.id].push(messageChunk) |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | return false |
| 145 | |
| 146 | case 'stream_event': |
| 147 | { |
| 148 | // 工具结果需立即落地(不经平滑层),写入 msgChunks 后由 convertToolResultToMessages |
| 149 | // 按 tool_call_id 关联到对应 AI 消息的 tool_call,驱动其完成态。 |
| 150 | const toolMessage = toolFinishedMessage(chunk) |
| 151 | if (toolMessage) { |
no test coverage detected