Skip to content

Commit d116e11

Browse files
committed
improvement(search-mcp): lock inside the turn and keep resumed chats resumable
1 parent bb54718 commit d116e11

2 files changed

Lines changed: 27 additions & 21 deletions

File tree

‎apps/sim/lib/knowledge/application/chat.integration.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -195,15 +195,15 @@ describe('Search MCP chat follow-ups', () => {
195195
expect(await transcript(chatId)).toHaveLength(6)
196196
})
197197

198-
it('keeps a resumed conversation when its follow-up fails', async () => {
199-
mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('First answer.'))
200-
const { chatId } = await ask('First question')
201-
if (!chatId) throw new Error('Expected a saved conversation')
198+
it('keeps a resumed conversation when its follow-up fails, even with no messages yet', async () => {
199+
const chatId = generateId()
200+
await db
201+
.insert(copilotChats)
202+
.values({ id: chatId, userId: memberId, organizationId, type: 'mothership' })
202203

203204
mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce({ ...answer(''), success: false })
204-
await expect(ask('Second question', chatId)).rejects.toThrow('could not finish')
205+
await expect(ask('First question', chatId)).rejects.toThrow('could not finish')
205206

206207
expect(await liveChats(memberId)).toContainEqual({ id: chatId })
207-
expect(await transcript(chatId)).toHaveLength(2)
208208
})
209209
})

‎apps/sim/lib/knowledge/application/chat.ts‎

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -165,18 +165,14 @@ export const organizationSearchChat: OperationUseCase<
165165
})
166166
input.signal?.throwIfAborted()
167167
const resumed = input.chatId !== undefined
168-
const chat = resumed
169-
? await findConversation(input.chatId ?? '', userId, organizationId)
170-
: await createConversation(userId, organizationId, query)
168+
const chat =
169+
input.chatId === undefined
170+
? await createConversation(userId, organizationId, query)
171+
: await findConversation(input.chatId, userId, organizationId)
171172
if (!chat) throw new OrchestrationError('not_found', CONVERSATION_NOT_FOUND)
172173

173174
const chatId = chat.id
174175
const messageId = generateId()
175-
if (!(await acquirePendingChatStream(chatId, messageId, 0)))
176-
throw new OrchestrationError(
177-
'conflict',
178-
'This conversation is still answering an earlier question. Wait for that answer, then ask again.'
179-
)
180176
const controller = new AbortController()
181177
let running = false
182178
let persisted = false
@@ -198,6 +194,11 @@ export const organizationSearchChat: OperationUseCase<
198194
if (input.signal?.aborted) abort()
199195

200196
try {
197+
if (!(await acquirePendingChatStream(chatId, messageId, 0)))
198+
throw new OrchestrationError(
199+
'conflict',
200+
'This conversation is still answering an earlier question. Wait for that answer, then ask again.'
201+
)
201202
controller.signal.throwIfAborted()
202203
running = true
203204
const payload = await buildCopilotRequestPayload({
@@ -261,17 +262,20 @@ export const organizationSearchChat: OperationUseCase<
261262
if (!isResolvedSecretModelContentUnchanged(answer, registry)) {
262263
throw new OrchestrationError('internal', 'Search answer could not be returned safely')
263264
}
264-
let conversation: Pick<OrganizationSearchChatResult, 'chatId' | 'conversationUrl'> = {}
265265
try {
266266
await persistCopilotChatTurn(chatId, [userMessage, assistantMessage])
267267
persisted = true
268-
conversation = {
269-
chatId,
270-
conversationUrl: `${getBaseUrl()}/o/${encodeURIComponent(organizationId)}/chat/${encodeURIComponent(chatId)}`,
271-
}
272268
} catch {
273269
logger.warn('Unable to save Search chat transcript', { chatId })
274270
}
271+
/** A conversation that already existed stays resumable even when this turn was not saved. */
272+
const conversation: Pick<OrganizationSearchChatResult, 'chatId' | 'conversationUrl'> =
273+
persisted || resumed
274+
? {
275+
chatId,
276+
conversationUrl: `${getBaseUrl()}/o/${encodeURIComponent(organizationId)}/chat/${encodeURIComponent(chatId)}`,
277+
}
278+
: {}
275279
controller.signal.throwIfAborted()
276280
return { ...answer, ...conversation }
277281
} finally {
@@ -281,9 +285,11 @@ export const organizationSearchChat: OperationUseCase<
281285
input.signal?.removeEventListener('abort', abort)
282286
await explicitAbort
283287
await releasePendingChatStream(chatId, messageId)
284-
/** A resumed conversation keeps its history whatever this turn did. */
288+
/**
289+
* Retain run diagnostics, but keep an unsuccessful empty conversation this turn created out
290+
* of history. A resumed one stays even when empty, as a conversation started in the app can be.
291+
*/
285292
if (!persisted && !resumed) {
286-
/** Retain run diagnostics, but keep an unsuccessful empty conversation out of history. */
287293
try {
288294
await db.transaction(async (tx) => {
289295
const ownedChat = and(

0 commit comments

Comments
 (0)