diff --git a/apps/sim/lib/api/contracts/knowledge/mcp.ts b/apps/sim/lib/api/contracts/knowledge/mcp.ts index b5d6571bbb7..3302576545b 100644 --- a/apps/sim/lib/api/contracts/knowledge/mcp.ts +++ b/apps/sim/lib/api/contracts/knowledge/mcp.ts @@ -113,5 +113,11 @@ export const chatSearchMcpSchema = workspaceSearchFiltersSchema .extend({ ...mcpDateFilterFields, query: z.string().trim().min(1, 'A question is required').max(8192), + chatId: z + .string() + .min(1) + .max(64) + .optional() + .describe('The chatId of an earlier chat answer, to ask a follow-up in that conversation.'), }) .strict() diff --git a/apps/sim/lib/knowledge/application/chat.integration.ts b/apps/sim/lib/knowledge/application/chat.integration.ts new file mode 100644 index 00000000000..530f726c88a --- /dev/null +++ b/apps/sim/lib/knowledge/application/chat.integration.ts @@ -0,0 +1,209 @@ +/** + * Search MCP chat follow-ups against real PostgreSQL and Redis: which conversation a chatId + * resumes, the per-conversation stream lock, and the transcript a turn leaves behind are + * production code. Authorization, billing, the payload builder and the worker lifecycle are + * stood in, since only conversation ownership, locking and persistence are under test. + */ +import { createDeferred } from '@sim/testing/helpers/deferred' +import { billingAttributionMock } from '@sim/testing/mocks/billing-attribution.mock' +import { knowledgeAvailabilityMock } from '@sim/testing/mocks/knowledge-availability.mock' +import { + mothershipChatPayloadMock, + mothershipChatPayloadMockFns, +} from '@sim/testing/mocks/mothership-chat-payload.mock' +import { + mothershipHeadlessLifecycleMock, + mothershipHeadlessLifecycleMockFns, +} from '@sim/testing/mocks/mothership-headless-lifecycle.mock' +import { + organizationAuthorizationMock, + organizationAuthorizationMockFns, +} from '@sim/testing/mocks/organization-authorization.mock' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/core/application/organization-authorization', () => organizationAuthorizationMock) +vi.mock('@/lib/knowledge/access/availability', () => knowledgeAvailabilityMock) +vi.mock('@/lib/billing/core/attribution', () => billingAttributionMock) +vi.mock('@/lib/mothership/application/load-search-integrations', () => ({ + loadCopilotSearchIntegrations: async () => '{"connections":[],"available":[]}', +})) +vi.mock('@/lib/mothership/chat/payload', () => mothershipChatPayloadMock) +vi.mock('@/lib/mothership/request/lifecycle/headless', () => mothershipHeadlessLifecycleMock) +vi.mock('@/lib/mothership/request/session/explicit-abort', () => ({ + requestExplicitStreamAbort: async () => undefined, +})) + +import type { OAuthAccessTokenPrincipal } from '@sim/auth/principal' +import { db } from '@sim/db' +import { copilotChats, copilotMessages, organization, user } from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { and, eq, inArray, isNull } from 'drizzle-orm' +import { organizationSearchChat } from '@/lib/knowledge/application/chat' +import type { OrchestratorResult } from '@/lib/mothership/request/types' +import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' + +const { mockRunHeadlessCopilotLifecycle } = mothershipHeadlessLifecycleMockFns +const memberId = generateId() +const otherMemberId = generateId() +const organizationId = generateId() +const otherOrganizationId = generateId() + +function principalFor(userId: string): OAuthAccessTokenPrincipal { + return { + kind: 'oauth_access_token', + userId, + clientId: 'mcp-client', + tokenId: generateId(), + scopes: ['search:read'], + expiresAt: new Date(Date.now() + 3_600_000), + } +} + +function answer(content: string): OrchestratorResult { + return { success: true, content, contentBlocks: [], toolCalls: [] } +} + +function ask(query: string, chatId?: string, userId = memberId) { + return organizationSearchChat.execute({ + principal: principalFor(userId), + input: { + organizationId, + query, + ...(chatId ? { chatId } : {}), + resultSecretRegistry: new ResolvedSecretTraceRegistry(), + }, + }) +} + +async function transcript(chatId: string) { + return db + .select({ id: copilotMessages.id }) + .from(copilotMessages) + .where(eq(copilotMessages.chatId, chatId)) +} + +async function liveChats(userId: string) { + return db + .select({ id: copilotChats.id }) + .from(copilotChats) + .where(and(eq(copilotChats.userId, userId), isNull(copilotChats.deletedAt))) +} + +describe('Search MCP chat follow-ups', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + [memberId, otherMemberId].map((id) => ({ + id, + name: 'Search chat fixture', + email: `${id}@search-chat.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await db.insert(organization).values( + [organizationId, otherOrganizationId].map((id) => ({ + id, + name: 'Search chat fixture', + slug: `search-chat-${id}`, + })) + ) + mothershipChatPayloadMockFns.mockBuildCopilotRequestPayload.mockResolvedValue({ + mode: 'assistant', + }) + }) + + afterAll(async () => { + await db.delete(copilotChats).where(inArray(copilotChats.userId, [memberId, otherMemberId])) + await db + .delete(organization) + .where(inArray(organization.id, [organizationId, otherOrganizationId])) + await db.delete(user).where(inArray(user.id, [memberId, otherMemberId])) + }) + + beforeEach(() => { + mockRunHeadlessCopilotLifecycle.mockReset() + organizationAuthorizationMockFns.mockAuthorizeOrganizationOperation.mockImplementation( + async (principal: OAuthAccessTokenPrincipal) => ({ + userId: principal.userId, + organizationId, + }) + ) + }) + + it('continues the caller’s conversation with the same chat and transcript', async () => { + mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('The kit is in the suitcase.')) + const first = await ask('Where is the field kit?') + if (!first.chatId) throw new Error('Expected a saved conversation') + + mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('It is violet.')) + const followUp = await ask('What colour is it?', first.chatId) + + expect(followUp.chatId).toBe(first.chatId) + expect(mockRunHeadlessCopilotLifecycle).toHaveBeenLastCalledWith( + expect.anything(), + expect.objectContaining({ chatId: first.chatId }) + ) + expect(await transcript(first.chatId)).toHaveLength(4) + expect(await liveChats(memberId)).toEqual([{ id: first.chatId }]) + }) + + it.each([ + ['another member’s conversation', 'other-member'], + ['a conversation in another organization', 'other-organization'], + ['a deleted conversation', 'deleted'], + ['an Agent conversation', 'agent'], + ['a value that is not a chat ID', 'malformed'], + ])('refuses %s as not found before running anything', async (_case, kind) => { + const chatId = generateId() + if (kind !== 'malformed') + await db.insert(copilotChats).values({ + id: chatId, + userId: kind === 'other-member' ? otherMemberId : memberId, + organizationId: kind === 'other-organization' ? otherOrganizationId : organizationId, + type: 'mothership', + ...(kind === 'deleted' ? { deletedAt: new Date() } : {}), + ...(kind === 'agent' ? { config: { conversationMode: 'agent' } } : {}), + }) + await expect( + ask('Follow up', kind === 'malformed' ? 'not-a-chat' : chatId) + ).rejects.toMatchObject({ code: 'not_found' }) + expect(mockRunHeadlessCopilotLifecycle).not.toHaveBeenCalled() + }) + + it('refuses a follow-up while the conversation is still answering', async () => { + mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('First answer.')) + const { chatId } = await ask('First question') + if (!chatId) throw new Error('Expected a saved conversation') + + const running = createDeferred() + const started = createDeferred() + mockRunHeadlessCopilotLifecycle.mockImplementationOnce(async () => { + started.resolve() + return running.promise + }) + const inFlight = ask('Second question', chatId) + await started.promise + + await expect(ask('Third question', chatId)).rejects.toMatchObject({ code: 'conflict' }) + running.resolve(answer('Second answer.')) + await expect(inFlight).resolves.toMatchObject({ chatId }) + + mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('Third answer.')) + await expect(ask('Third question', chatId)).resolves.toMatchObject({ chatId }) + expect(await transcript(chatId)).toHaveLength(6) + }) + + it('keeps a resumed conversation when its follow-up fails, even with no messages yet', async () => { + const chatId = generateId() + await db + .insert(copilotChats) + .values({ id: chatId, userId: memberId, organizationId, type: 'mothership' }) + + mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce({ ...answer(''), success: false }) + await expect(ask('First question', chatId)).rejects.toThrow('could not finish') + + expect(await liveChats(memberId)).toContainEqual({ id: chatId }) + }) +}) diff --git a/apps/sim/lib/knowledge/application/chat.ts b/apps/sim/lib/knowledge/application/chat.ts index 78d74b16260..80c33352089 100644 --- a/apps/sim/lib/knowledge/application/chat.ts +++ b/apps/sim/lib/knowledge/application/chat.ts @@ -2,10 +2,10 @@ import type { Principal } from '@sim/auth/principal' import { db } from '@sim/db' import { copilotChats, copilotMessages } from '@sim/db/schema' import { createLogger } from '@sim/logger' -import { generateId } from '@sim/utils/id' +import { generateId, isValidUuid } from '@sim/utils/id' import { isPlainRecord } from '@sim/utils/object' import { truncate } from '@sim/utils/string' -import { and, eq, isNull, notExists } from 'drizzle-orm' +import { and, eq, isNull, notExists, sql } from 'drizzle-orm' import { type WorkspaceSearchFilters, workspaceSearchFiltersSchema, @@ -23,6 +23,7 @@ import { } from '@/lib/knowledge/application/chat-citations' import { organizationSearchChatOperation } from '@/lib/knowledge/application/chat-operations' import { loadCopilotSearchIntegrations } from '@/lib/mothership/application/load-search-integrations' +import { conversationModeSelection } from '@/lib/mothership/chat/intent' import { persistCopilotChatTurn } from '@/lib/mothership/chat/messages-store' import { buildCopilotRequestPayload } from '@/lib/mothership/chat/payload' import { @@ -34,6 +35,14 @@ import { } from '@/lib/mothership/chat/persisted-message' import { MOTHERSHIP_CHAT_DEFAULT_MODEL } from '@/lib/mothership/constants' import { runHeadlessCopilotLifecycle } from '@/lib/mothership/request/lifecycle/headless' +import { + acquirePendingChatStream, + cleanupAbortMarker, + registerActiveStream, + releasePendingChatStream, + startAbortPoller, + unregisterActiveStream, +} from '@/lib/mothership/request/session/abort' import { requestExplicitStreamAbort } from '@/lib/mothership/request/session/explicit-abort' import { isResolvedSecretModelContentUnchanged, @@ -48,6 +57,8 @@ const SEARCH_CHAT_TIMEOUT_MS = 180_000 export interface OrganizationSearchChatInput { organizationId: string query: string + /** A conversation this caller started here earlier, continued with its history. */ + chatId?: string filters?: WorkspaceSearchFilters resultSecretRegistry: ResolvedSecretTraceRegistry signal?: AbortSignal @@ -80,7 +91,54 @@ async function authorize(principal: Principal, organizationId: string) { return context } -/** Runs the existing organization Assistant in a new private conversation for this caller. */ +const CONVERSATION_NOT_FOUND = + 'Conversation not found. Ask without chatId to start a new conversation.' + +/** + * The caller's own live Assistant conversation in this organization, as {@link createConversation} + * makes them, or undefined. Another member's chat, a deleted one, and an Agent or Plan chat, whose + * turns need permissions this surface does not grant, are all not found alike. + */ +async function findConversation(chatId: string, userId: string, organizationId: string) { + if (!isValidUuid(chatId)) return undefined + const [chat] = await db + .select({ id: copilotChats.id }) + .from(copilotChats) + .where( + and( + eq(copilotChats.id, chatId), + eq(copilotChats.userId, userId), + eq(copilotChats.organizationId, organizationId), + eq(copilotChats.type, 'mothership'), + isNull(copilotChats.deletedAt), + sql`${conversationModeSelection} = 'assistant'` + ) + ) + .limit(1) + return chat +} + +async function createConversation(userId: string, organizationId: string, query: string) { + const [chat] = await db + .insert(copilotChats) + .values({ + userId, + organizationId, + type: 'mothership', + model: MOTHERSHIP_CHAT_DEFAULT_MODEL, + title: truncate(query.replace(/\s+/g, ' '), 80), + lastSeenAt: new Date(), + }) + .returning({ id: copilotChats.id }) + if (!chat) throw new OrchestrationError('internal', 'Unable to create a Search conversation') + return chat +} + +/** + * Runs the existing organization Assistant for this caller: in a new private conversation, or as + * a follow-up in one of the caller's own conversations, whose earlier turns the Assistant reads. + * One question at a time holds a conversation; a follow-up sent while it answers is refused. + */ export const organizationSearchChat: OperationUseCase< typeof organizationSearchChatOperation, OrganizationSearchChatInput, @@ -105,23 +163,18 @@ export const organizationSearchChat: OperationUseCase< 'The question contains protected content. Rephrase it.' ) } + const resumed = input.chatId !== undefined + const existing = + input.chatId === undefined + ? undefined + : await findConversation(input.chatId, userId, organizationId) + if (resumed && !existing) throw new OrchestrationError('not_found', CONVERSATION_NOT_FOUND) const billingAttribution = await resolveOrganizationBillingAttribution({ actorUserId: userId, organizationId, }) input.signal?.throwIfAborted() - const [chat] = await db - .insert(copilotChats) - .values({ - userId, - organizationId, - type: 'mothership', - model: MOTHERSHIP_CHAT_DEFAULT_MODEL, - title: truncate(query.replace(/\s+/g, ' '), 80), - lastSeenAt: new Date(), - }) - .returning({ id: copilotChats.id }) - if (!chat) throw new OrchestrationError('internal', 'Unable to create a Search conversation') + const chat = existing ?? (await createConversation(userId, organizationId, query)) const chatId = chat.id const messageId = generateId() @@ -129,6 +182,7 @@ export const organizationSearchChat: OperationUseCase< let running = false let persisted = false let explicitAbort: Promise | undefined + let lockPoller: ReturnType | undefined const abort = () => { controller.abort(new DOMException('Search chat cancelled', 'AbortError')) if (running && !explicitAbort) { @@ -146,6 +200,14 @@ export const organizationSearchChat: OperationUseCase< if (input.signal?.aborted) abort() try { + if (!(await acquirePendingChatStream(chatId, messageId, 0))) + throw new OrchestrationError( + 'conflict', + 'This conversation is still answering an earlier question. Wait for that answer, then ask again.' + ) + /** Renews the chat lock for the whole turn and lets Stop in the app cancel it. */ + registerActiveStream(messageId, controller) + lockPoller = startAbortPoller(messageId, controller, { chatId }) controller.signal.throwIfAborted() running = true const payload = await buildCopilotRequestPayload({ @@ -209,17 +271,20 @@ export const organizationSearchChat: OperationUseCase< if (!isResolvedSecretModelContentUnchanged(answer, registry)) { throw new OrchestrationError('internal', 'Search answer could not be returned safely') } - let conversation: Pick = {} try { await persistCopilotChatTurn(chatId, [userMessage, assistantMessage]) persisted = true - conversation = { - chatId, - conversationUrl: `${getBaseUrl()}/o/${encodeURIComponent(organizationId)}/chat/${encodeURIComponent(chatId)}`, - } } catch { logger.warn('Unable to save Search chat transcript', { chatId }) } + /** A conversation that already existed stays resumable even when this turn was not saved. */ + const conversation: Pick = + persisted || resumed + ? { + chatId, + conversationUrl: `${getBaseUrl()}/o/${encodeURIComponent(organizationId)}/chat/${encodeURIComponent(chatId)}`, + } + : {} controller.signal.throwIfAborted() return { ...answer, ...conversation } } finally { @@ -228,8 +293,17 @@ export const organizationSearchChat: OperationUseCase< clearTimeout(timeout) input.signal?.removeEventListener('abort', abort) await explicitAbort - if (!persisted) { - /** Retain run diagnostics, but keep an unsuccessful empty conversation out of history. */ + if (lockPoller) { + clearInterval(lockPoller) + unregisterActiveStream(messageId) + await cleanupAbortMarker(messageId) + } + await releasePendingChatStream(chatId, messageId) + /** + * Retain run diagnostics, but keep an unsuccessful empty conversation this turn created out + * of history. A resumed one stays even when empty, as a conversation started in the app can be. + */ + if (!persisted && !resumed) { try { await db.transaction(async (tx) => { const ownedChat = and( diff --git a/apps/sim/lib/knowledge/mcp/server.ts b/apps/sim/lib/knowledge/mcp/server.ts index 9c97346a3b6..7bef811ddcd 100644 --- a/apps/sim/lib/knowledge/mcp/server.ts +++ b/apps/sim/lib/knowledge/mcp/server.ts @@ -341,7 +341,7 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe { title: 'Chat', description: - 'Ask the Sim Assistant to research a question in your accessible organization sources and write a cited answer. It runs its own multi-step search, so it usually takes 30 to 60 seconds and returns a synthesized answer rather than the sources. To answer a question yourself, use search and read_document, which return sources in seconds; use chat only when the user asks for the Sim Assistant’s answer. Starts a new private conversation. Use source, modifiedAfter, or documentIds to narrow the evidence. It searches the public web only when your sources lack the answer, and makes no source changes.', + 'Ask the Sim Assistant to research a question in your accessible organization sources and write a cited answer. It runs its own multi-step search, so it usually takes 30 to 60 seconds and returns a synthesized answer rather than the sources. To answer a question yourself, use search and read_document, which return sources in seconds; use chat only when the user asks for the Sim Assistant’s answer. Starts a new private conversation and returns its chatId; pass that chatId with the next question to ask a follow-up that builds on the earlier answers. Use source, modifiedAfter, or documentIds to narrow the evidence. It searches the public web only when your sources lack the answer, and makes no source changes.', inputSchema: chatSearchMcpSchema, annotations: { readOnlyHint: false, @@ -350,12 +350,12 @@ export function createKnowledgeMcpServer(context: KnowledgeMcpContext): McpServe openWorldHint: true, }, }, - async ({ query, ...filters }, extra) => + async ({ query, chatId, ...filters }, extra) => execute('chat', organizationSearchChatOperation, extra.signal, async (registry, signal) => { const { organizationSearchChat } = await import('@/lib/knowledge/application/chat') const result = await organizationSearchChat.execute({ principal, - input: { organizationId, query, filters, resultSecretRegistry: registry, signal }, + input: { organizationId, query, chatId, filters, resultSecretRegistry: registry, signal }, }) return projectResult(result, registry) })