({
chatId,
userMessageId,
userId,
assistantMessage,
streamMarkerPolicy = 'active-only',
}: FinalizeAssistantTurnParams)
| 32 | * triggering user message. |
| 33 | */ |
| 34 | export async function finalizeAssistantTurn({ |
| 35 | chatId, |
| 36 | userMessageId, |
| 37 | userId, |
| 38 | assistantMessage, |
| 39 | streamMarkerPolicy = 'active-only', |
| 40 | }: FinalizeAssistantTurnParams): Promise<FinalizeAssistantTurnResult> { |
| 41 | return withCopilotSpan( |
| 42 | TraceSpan.CopilotChatFinalizeAssistantTurn, |
| 43 | { |
| 44 | [TraceAttr.DbSystem]: 'postgresql', |
| 45 | [TraceAttr.DbSqlTable]: 'copilot_chats', |
| 46 | [TraceAttr.ChatId]: chatId, |
| 47 | [TraceAttr.ChatUserMessageId]: userMessageId, |
| 48 | [TraceAttr.ChatHasAssistantMessage]: !!assistantMessage, |
| 49 | }, |
| 50 | async (span) => { |
| 51 | const result = await db.transaction(async (tx) => { |
| 52 | const where = userId |
| 53 | ? and(eq(copilotChats.id, chatId), eq(copilotChats.userId, userId)) |
| 54 | : eq(copilotChats.id, chatId) |
| 55 | const [row] = await tx |
| 56 | .select({ |
| 57 | conversationId: copilotChats.conversationId, |
| 58 | workspaceId: copilotChats.workspaceId, |
| 59 | model: copilotChats.model, |
| 60 | }) |
| 61 | .from(copilotChats) |
| 62 | .where(where) |
| 63 | .for('update') |
| 64 | .limit(1) |
| 65 | |
| 66 | if (!row) { |
| 67 | return { |
| 68 | found: false, |
| 69 | updated: false, |
| 70 | appendedAssistant: false, |
| 71 | workspaceId: null, |
| 72 | outcome: CopilotChatFinalizeOutcome.StaleUserMessage, |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | const chatModel = row.model ?? null |
| 77 | |
| 78 | const markerMatches = row.conversationId === userMessageId |
| 79 | const markerAlreadyCleared = row.conversationId === null |
| 80 | const ownsTurn = |
| 81 | markerMatches || (streamMarkerPolicy === 'active-or-cleared' && markerAlreadyCleared) |
| 82 | if (!ownsTurn) { |
| 83 | return { |
| 84 | found: true, |
| 85 | updated: false, |
| 86 | appendedAssistant: false, |
| 87 | workspaceId: row.workspaceId, |
| 88 | outcome: CopilotChatFinalizeOutcome.StaleUserMessage, |
| 89 | } |
| 90 | } |
| 91 |
no test coverage detected