@@ -39,10 +39,13 @@ const ChatMessageSchema = z.object({
3939 chatId : z . string ( ) . optional ( ) ,
4040 workflowId : z . string ( ) . min ( 1 , 'Workflow ID is required' ) ,
4141 mode : z . enum ( [ 'ask' , 'agent' ] ) . optional ( ) . default ( 'agent' ) ,
42+ depth : z . number ( ) . int ( ) . min ( 0 ) . max ( 3 ) . optional ( ) . default ( 0 ) ,
4243 createNewChat : z . boolean ( ) . optional ( ) . default ( false ) ,
4344 stream : z . boolean ( ) . optional ( ) . default ( true ) ,
4445 implicitFeedback : z . string ( ) . optional ( ) ,
4546 fileAttachments : z . array ( FileAttachmentSchema ) . optional ( ) ,
47+ provider : z . string ( ) . optional ( ) . default ( 'openai' ) ,
48+ conversationId : z . string ( ) . optional ( ) ,
4649} )
4750
4851// Sim Agent API configuration
@@ -156,10 +159,13 @@ export async function POST(req: NextRequest) {
156159 chatId,
157160 workflowId,
158161 mode,
162+ depth,
159163 createNewChat,
160164 stream,
161165 implicitFeedback,
162166 fileAttachments,
167+ provider,
168+ conversationId,
163169 } = ChatMessageSchema . parse ( body )
164170
165171 logger . info ( `[${ tracker . requestId } ] Processing copilot chat request` , {
@@ -171,6 +177,8 @@ export async function POST(req: NextRequest) {
171177 createNewChat,
172178 messageLength : message . length ,
173179 hasImplicitFeedback : ! ! implicitFeedback ,
180+ provider : provider || 'openai' ,
181+ hasConversationId : ! ! conversationId ,
174182 } )
175183
176184 // Handle chat context
@@ -252,7 +260,7 @@ export async function POST(req: NextRequest) {
252260 }
253261
254262 // Build messages array for sim agent with conversation history
255- const messages = [ ]
263+ const messages : any [ ] = [ ]
256264
257265 // Add conversation history (need to rebuild these with file support if they had attachments)
258266 for ( const msg of conversationHistory ) {
@@ -327,16 +335,13 @@ export async function POST(req: NextRequest) {
327335 } )
328336 }
329337
330- // Start title generation in parallel if this is a new chat with first message
331- if ( actualChatId && ! currentChat ?. title && conversationHistory . length === 0 ) {
332- logger . info ( `[ ${ tracker . requestId } ] Will start parallel title generation inside stream` )
333- }
338+ // Determine provider and conversationId to use for this request
339+ const providerToUse = provider || 'openai'
340+ const effectiveConversationId =
341+ ( currentChat ?. conversationId as string | undefined ) || conversationId
334342
335- // Forward to sim agent API
336- logger . info ( `[${ tracker . requestId } ] Sending request to sim agent API` , {
337- messageCount : messages . length ,
338- endpoint : `${ SIM_AGENT_API_URL } /api/chat-completion-streaming` ,
339- } )
343+ // If we have a conversationId, only send the most recent user message; else send full history
344+ const messagesForAgent = effectiveConversationId ? [ messages [ messages . length - 1 ] ] : messages
340345
341346 const simAgentResponse = await fetch ( `${ SIM_AGENT_API_URL } /api/chat-completion-streaming` , {
342347 method : 'POST' ,
@@ -345,12 +350,15 @@ export async function POST(req: NextRequest) {
345350 ...( SIM_AGENT_API_KEY && { 'x-api-key' : SIM_AGENT_API_KEY } ) ,
346351 } ,
347352 body : JSON . stringify ( {
348- messages,
353+ messages : messagesForAgent ,
349354 workflowId,
350355 userId : authenticatedUserId ,
351356 stream : stream ,
352357 streamToolCalls : true ,
353358 mode : mode ,
359+ provider : providerToUse ,
360+ ...( effectiveConversationId ? { conversationId : effectiveConversationId } : { } ) ,
361+ ...( typeof depth === 'number' ? { depth } : { } ) ,
354362 ...( session ?. user ?. name && { userName : session . user . name } ) ,
355363 } ) ,
356364 } )
@@ -388,6 +396,8 @@ export async function POST(req: NextRequest) {
388396 const toolCalls : any [ ] = [ ]
389397 let buffer = ''
390398 let isFirstDone = true
399+ let responseIdFromStart : string | undefined
400+ let responseIdFromDone : string | undefined
391401
392402 // Send chatId as first event
393403 if ( actualChatId ) {
@@ -486,6 +496,13 @@ export async function POST(req: NextRequest) {
486496 }
487497 break
488498
499+ case 'reasoning' :
500+ // Treat like thinking: do not add to assistantContent to avoid leaking
501+ logger . debug (
502+ `[${ tracker . requestId } ] Reasoning chunk received (${ ( event . data || event . content || '' ) . length } chars)`
503+ )
504+ break
505+
489506 case 'tool_call' :
490507 logger . info (
491508 `[${ tracker . requestId } ] Tool call ${ event . data ?. partial ? '(partial)' : '(complete)' } :` ,
@@ -528,7 +545,22 @@ export async function POST(req: NextRequest) {
528545 } )
529546 break
530547
548+ case 'start' :
549+ if ( event . data ?. responseId ) {
550+ responseIdFromStart = event . data . responseId
551+ logger . info (
552+ `[${ tracker . requestId } ] Received start event with responseId: ${ responseIdFromStart } `
553+ )
554+ }
555+ break
556+
531557 case 'done' :
558+ if ( event . data ?. responseId ) {
559+ responseIdFromDone = event . data . responseId
560+ logger . info (
561+ `[${ tracker . requestId } ] Received done event with responseId: ${ responseIdFromDone } `
562+ )
563+ }
532564 if ( isFirstDone ) {
533565 logger . info (
534566 `[${ tracker . requestId } ] Initial AI response complete, tool count: ${ toolCalls . length } `
@@ -622,19 +654,23 @@ export async function POST(req: NextRequest) {
622654 )
623655 }
624656
657+ const responseId = responseIdFromDone || responseIdFromStart
658+
625659 // Update chat in database immediately (without title)
626660 await db
627661 . update ( copilotChats )
628662 . set ( {
629663 messages : updatedMessages ,
630664 updatedAt : new Date ( ) ,
665+ ...( responseId ? { conversationId : responseId } : { } ) ,
631666 } )
632667 . where ( eq ( copilotChats . id , actualChatId ! ) )
633668
634669 logger . info ( `[${ tracker . requestId } ] Updated chat ${ actualChatId } with new messages` , {
635670 messageCount : updatedMessages . length ,
636671 savedUserMessage : true ,
637672 savedAssistantMessage : assistantContent . trim ( ) . length > 0 ,
673+ updatedConversationId : responseId || null ,
638674 } )
639675 }
640676 } catch ( error ) {
0 commit comments