| 1 | import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; |
| 2 | |
| 3 | import { logger } from "src/util/logger.js"; |
| 4 | |
| 5 | import { services } from "../../services/index.js"; |
| 6 | import { getCurrentSession, updateSessionTitle } from "../../session.js"; |
| 7 | |
| 8 | import { generateSessionTitle } from "./useChat.helpers.js"; |
| 9 | |
| 10 | interface CreateStreamCallbacksOptions { |
| 11 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 12 | setActivePermissionRequest: React.Dispatch<React.SetStateAction<any>>; |
| 13 | llmApi?: any; |
| 14 | model?: any; |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * Create stream callbacks for chat response |
| 19 | */ |
| 20 | export function createStreamCallbacks( |
| 21 | options: CreateStreamCallbacksOptions, |
| 22 | ): any { |
| 23 | const { setChatHistory, setActivePermissionRequest, llmApi, model } = options; |
| 24 | |
| 25 | return { |
| 26 | onContent: (_: string) => {}, |
| 27 | |
| 28 | onContentComplete: async (content: string) => { |
| 29 | // Do not add assistant messages via service; handleToolCalls is the single writer |
| 30 | // For environments where the service isn't ready (unit tests), update local state only |
| 31 | try { |
| 32 | const svc = services.chatHistory; |
| 33 | const useService = typeof svc?.isReady === "function" && svc.isReady(); |
| 34 | if (!useService && content) { |
| 35 | setChatHistory((prev) => [ |
| 36 | ...prev, |
| 37 | { |
| 38 | contextItems: [], |
| 39 | message: { |
| 40 | role: "assistant", |
| 41 | content: content, |
| 42 | isStreaming: false, |
| 43 | }, |
| 44 | }, |
| 45 | ]); |
| 46 | } |
| 47 | } catch (error) { |
| 48 | logger.error("Failed to update chat history", { error }); |
| 49 | } |
| 50 | // Generate session title after first assistant response |
| 51 | if (content && llmApi && model) { |
| 52 | const currentSession = getCurrentSession(); |
| 53 | const generatedTitle = await generateSessionTitle( |
| 54 | content, |
| 55 | llmApi, |
| 56 | model, |
| 57 | currentSession.title, |
| 58 | ); |
| 59 | |
| 60 | if (generatedTitle) { |
| 61 | updateSessionTitle(generatedTitle); |
| 62 | } |
| 63 | } |
| 64 | }, |
| 65 | |
| 66 | onToolStart: (toolName: string, toolArgs?: any) => { |
| 67 | // When ChatHistoryService is ready, let handleToolCalls add entries |
| 68 | const svc = services.chatHistory; |
| 69 | const useService = typeof svc?.isReady === "function" && svc.isReady(); |
| 70 | if (useService) return; |
| 71 | |
| 72 | // Fallback (service not ready): create a local assistant message representing the tool call |
| 73 | setChatHistory((prev) => { |
| 74 | const newHistory = [...prev]; |
| 75 | |
| 76 | const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`; |
| 77 | const toolCallState: ToolCallState = { |
| 78 | toolCallId: toolCallId, |
| 79 | toolCall: { |
| 80 | id: toolCallId, |
| 81 | type: "function", |
| 82 | function: { |
| 83 | name: toolName, |
| 84 | arguments: JSON.stringify(toolArgs || {}), |
| 85 | }, |
| 86 | }, |
| 87 | status: "calling", |
| 88 | parsedArgs: toolArgs, |
| 89 | }; |
| 90 | |
| 91 | newHistory.push({ |
| 92 | message: { |
| 93 | role: "assistant", |
| 94 | content: "", |
| 95 | toolCalls: [ |
| 96 | { |
| 97 | id: toolCallId, |
| 98 | type: "function", |
| 99 | function: { |
| 100 | name: toolName, |
| 101 | arguments: JSON.stringify(toolArgs || {}), |
| 102 | }, |
| 103 | }, |
| 104 | ], |
| 105 | }, |
| 106 | contextItems: [], |
| 107 | toolCallStates: [toolCallState], |
| 108 | }); |
| 109 | |
| 110 | return newHistory; |
| 111 | }); |
| 112 | }, |
| 113 | |
| 114 | onToolResult: (result: string, toolName: string, status: ToolStatus) => { |
| 115 | // When service is ready, it updates tool results; avoid duplicate local updates |
| 116 | const svc = services.chatHistory; |
| 117 | const useService = typeof svc?.isReady === "function" && svc.isReady(); |
| 118 | if (useService) return; |
| 119 | |
| 120 | // Fallback (service not ready): update local UI-only state |
| 121 | setChatHistory((prev) => { |
| 122 | const newHistory = [...prev]; |
| 123 | |
| 124 | for (let i = newHistory.length - 1; i >= 0; i--) { |
| 125 | const item = newHistory[i]; |
| 126 | if (item.toolCallStates) { |
| 127 | const toolState = item.toolCallStates.find( |
| 128 | (ts) => |
| 129 | ts.toolCall.function.name === toolName && |
| 130 | (ts.status === "calling" || ts.status === "generated"), |
| 131 | ); |
| 132 | |
| 133 | if (toolState) { |
| 134 | toolState.status = status; |
| 135 | toolState.output = [ |
| 136 | { |
| 137 | content: result, |
| 138 | name: `Tool Result: ${toolName}`, |
| 139 | description: "Tool execution result", |
| 140 | }, |
| 141 | ]; |
| 142 | break; |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | return newHistory; |
| 148 | }); |
| 149 | }, |
| 150 | |
| 151 | onToolError: (error: string, toolName?: string) => { |
| 152 | // When service is ready, handleToolCalls adds error entries; avoid duplicate local updates |
| 153 | const svc = services.chatHistory; |
| 154 | const useService = typeof svc?.isReady === "function" && svc.isReady(); |
| 155 | if (useService) return; |
| 156 | |
| 157 | setChatHistory((prev) => { |
| 158 | const newHistory = [...prev]; |
| 159 | |
| 160 | if (toolName) { |
| 161 | for (let i = newHistory.length - 1; i >= 0; i--) { |
| 162 | const item = newHistory[i]; |
| 163 | if (item.toolCallStates) { |
| 164 | const toolState = item.toolCallStates.find( |
| 165 | (ts) => |
| 166 | ts.toolCall.function.name === toolName && |
| 167 | (ts.status === "calling" || ts.status === "generated"), |
| 168 | ); |
| 169 | |
| 170 | if (toolState) { |
| 171 | toolState.status = "errored"; |
| 172 | toolState.output = [ |
| 173 | { |
| 174 | content: error, |
| 175 | name: `Tool Error: ${toolName}`, |
| 176 | description: "Tool execution error", |
| 177 | }, |
| 178 | ]; |
| 179 | break; |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | } else { |
| 184 | // General error message |
| 185 | newHistory.push({ |
| 186 | message: { |
| 187 | role: "system", |
| 188 | content: error, |
| 189 | }, |
| 190 | contextItems: [], |
| 191 | }); |
| 192 | } |
| 193 | |
| 194 | return newHistory; |
| 195 | }); |
| 196 | }, |
| 197 | |
| 198 | onToolPermissionRequest: ( |
| 199 | toolName: string, |
| 200 | toolArgs: any, |
| 201 | requestId: string, |
| 202 | toolCallPreview?: any[], |
| 203 | ) => { |
| 204 | setActivePermissionRequest({ |
| 205 | toolName, |
| 206 | toolArgs, |
| 207 | requestId, |
| 208 | toolCallPreview, |
| 209 | }); |
| 210 | }, |
| 211 | |
| 212 | onSystemMessage: (message: string) => { |
| 213 | try { |
| 214 | const svc = services.chatHistory; |
| 215 | if (typeof svc?.isReady === "function" && svc.isReady()) { |
| 216 | svc.addSystemMessage(message); |
| 217 | return; |
| 218 | } |
| 219 | } catch {} |
| 220 | // Fallback to local state if service unavailable |
| 221 | setChatHistory((prev) => [ |
| 222 | ...prev, |
| 223 | { |
| 224 | message: { |
| 225 | role: "system", |
| 226 | content: message, |
| 227 | }, |
| 228 | contextItems: [], |
| 229 | }, |
| 230 | ]); |
| 231 | }, |
| 232 | }; |
| 233 | } |
| 234 | |
| 235 | interface ExecuteStreamingOptions { |
| 236 | chatHistory: ChatHistoryItem[]; |
| 237 | model: any; |
| 238 | llmApi: any; |
| 239 | controller: AbortController; |
| 240 | streamCallbacks: any; |
| 241 | currentCompactionIndex: number | null; |
| 242 | } |
| 243 | |
| 244 | /** |
| 245 | * Execute streaming chat response |
| 246 | */ |
| 247 | export async function executeStreaming({ |
| 248 | chatHistory, |
| 249 | model, |
| 250 | llmApi, |
| 251 | controller, |
| 252 | streamCallbacks, |
| 253 | currentCompactionIndex, |
| 254 | }: ExecuteStreamingOptions): Promise<void> { |
| 255 | const { getHistoryForLLM } = await import("../../compaction.js"); |
| 256 | const { streamChatResponse } = await import( |
| 257 | "../../stream/streamChatResponse.js" |
| 258 | ); |
| 259 | |
| 260 | if (model && llmApi) { |
| 261 | if ( |
| 262 | currentCompactionIndex !== null && |
| 263 | currentCompactionIndex !== undefined |
| 264 | ) { |
| 265 | const historyForLLM = getHistoryForLLM( |
| 266 | chatHistory, |
| 267 | currentCompactionIndex, |
| 268 | ); |
| 269 | |
| 270 | await streamChatResponse( |
| 271 | historyForLLM, |
| 272 | model, |
| 273 | llmApi, |
| 274 | controller, |
| 275 | streamCallbacks, |
| 276 | ); |
| 277 | |
| 278 | // Service-driven streaming; history updates occur via ChatHistoryService |
| 279 | } else { |
| 280 | await streamChatResponse( |
| 281 | chatHistory, |
| 282 | model, |
| 283 | llmApi, |
| 284 | controller, |
| 285 | streamCallbacks, |
| 286 | ); |
| 287 | } |
| 288 | } |
| 289 | } |