|
| 1 | +/** |
| 2 | + * Search MCP chat follow-ups against real PostgreSQL and Redis: which conversation a chatId |
| 3 | + * resumes, the per-conversation stream lock, and the transcript a turn leaves behind are |
| 4 | + * production code. Authorization, billing, the payload builder and the worker lifecycle are |
| 5 | + * stood in, since only conversation ownership, locking and persistence are under test. |
| 6 | + */ |
| 7 | +import { createDeferred } from '@sim/testing/helpers/deferred' |
| 8 | +import { billingAttributionMock } from '@sim/testing/mocks/billing-attribution.mock' |
| 9 | +import { knowledgeAvailabilityMock } from '@sim/testing/mocks/knowledge-availability.mock' |
| 10 | +import { |
| 11 | + mothershipChatPayloadMock, |
| 12 | + mothershipChatPayloadMockFns, |
| 13 | +} from '@sim/testing/mocks/mothership-chat-payload.mock' |
| 14 | +import { |
| 15 | + mothershipHeadlessLifecycleMock, |
| 16 | + mothershipHeadlessLifecycleMockFns, |
| 17 | +} from '@sim/testing/mocks/mothership-headless-lifecycle.mock' |
| 18 | +import { |
| 19 | + organizationAuthorizationMock, |
| 20 | + organizationAuthorizationMockFns, |
| 21 | +} from '@sim/testing/mocks/organization-authorization.mock' |
| 22 | +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' |
| 23 | + |
| 24 | +vi.mock('@/lib/core/application/organization-authorization', () => organizationAuthorizationMock) |
| 25 | +vi.mock('@/lib/knowledge/access/availability', () => knowledgeAvailabilityMock) |
| 26 | +vi.mock('@/lib/billing/core/attribution', () => billingAttributionMock) |
| 27 | +vi.mock('@/lib/mothership/application/load-search-integrations', () => ({ |
| 28 | + loadCopilotSearchIntegrations: async () => '{"connections":[],"available":[]}', |
| 29 | +})) |
| 30 | +vi.mock('@/lib/mothership/chat/payload', () => mothershipChatPayloadMock) |
| 31 | +vi.mock('@/lib/mothership/request/lifecycle/headless', () => mothershipHeadlessLifecycleMock) |
| 32 | +vi.mock('@/lib/mothership/request/session/explicit-abort', () => ({ |
| 33 | + requestExplicitStreamAbort: async () => undefined, |
| 34 | +})) |
| 35 | + |
| 36 | +import type { OAuthAccessTokenPrincipal } from '@sim/auth/principal' |
| 37 | +import { db } from '@sim/db' |
| 38 | +import { copilotChats, copilotMessages, organization, user } from '@sim/db/schema' |
| 39 | +import { generateId } from '@sim/utils/id' |
| 40 | +import { and, eq, inArray, isNull } from 'drizzle-orm' |
| 41 | +import { organizationSearchChat } from '@/lib/knowledge/application/chat' |
| 42 | +import type { OrchestratorResult } from '@/lib/mothership/request/types' |
| 43 | +import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' |
| 44 | + |
| 45 | +const { mockRunHeadlessCopilotLifecycle } = mothershipHeadlessLifecycleMockFns |
| 46 | +const memberId = generateId() |
| 47 | +const otherMemberId = generateId() |
| 48 | +const organizationId = generateId() |
| 49 | +const otherOrganizationId = generateId() |
| 50 | + |
| 51 | +function principalFor(userId: string): OAuthAccessTokenPrincipal { |
| 52 | + return { |
| 53 | + kind: 'oauth_access_token', |
| 54 | + userId, |
| 55 | + clientId: 'mcp-client', |
| 56 | + tokenId: generateId(), |
| 57 | + scopes: ['search:read'], |
| 58 | + expiresAt: new Date(Date.now() + 3_600_000), |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +function answer(content: string): OrchestratorResult { |
| 63 | + return { success: true, content, contentBlocks: [], toolCalls: [] } |
| 64 | +} |
| 65 | + |
| 66 | +function ask(query: string, chatId?: string, userId = memberId) { |
| 67 | + return organizationSearchChat.execute({ |
| 68 | + principal: principalFor(userId), |
| 69 | + input: { |
| 70 | + organizationId, |
| 71 | + query, |
| 72 | + ...(chatId ? { chatId } : {}), |
| 73 | + resultSecretRegistry: new ResolvedSecretTraceRegistry(), |
| 74 | + }, |
| 75 | + }) |
| 76 | +} |
| 77 | + |
| 78 | +async function transcript(chatId: string) { |
| 79 | + return db |
| 80 | + .select({ id: copilotMessages.id }) |
| 81 | + .from(copilotMessages) |
| 82 | + .where(eq(copilotMessages.chatId, chatId)) |
| 83 | +} |
| 84 | + |
| 85 | +async function liveChats(userId: string) { |
| 86 | + return db |
| 87 | + .select({ id: copilotChats.id }) |
| 88 | + .from(copilotChats) |
| 89 | + .where(and(eq(copilotChats.userId, userId), isNull(copilotChats.deletedAt))) |
| 90 | +} |
| 91 | + |
| 92 | +describe('Search MCP chat follow-ups', () => { |
| 93 | + beforeAll(async () => { |
| 94 | + const now = new Date() |
| 95 | + await db.insert(user).values( |
| 96 | + [memberId, otherMemberId].map((id) => ({ |
| 97 | + id, |
| 98 | + name: 'Search chat fixture', |
| 99 | + email: `${id}@search-chat.test`, |
| 100 | + emailVerified: true, |
| 101 | + createdAt: now, |
| 102 | + updatedAt: now, |
| 103 | + })) |
| 104 | + ) |
| 105 | + await db.insert(organization).values( |
| 106 | + [organizationId, otherOrganizationId].map((id) => ({ |
| 107 | + id, |
| 108 | + name: 'Search chat fixture', |
| 109 | + slug: `search-chat-${id}`, |
| 110 | + })) |
| 111 | + ) |
| 112 | + mothershipChatPayloadMockFns.mockBuildCopilotRequestPayload.mockResolvedValue({ |
| 113 | + mode: 'assistant', |
| 114 | + }) |
| 115 | + }) |
| 116 | + |
| 117 | + afterAll(async () => { |
| 118 | + await db.delete(copilotChats).where(inArray(copilotChats.userId, [memberId, otherMemberId])) |
| 119 | + await db |
| 120 | + .delete(organization) |
| 121 | + .where(inArray(organization.id, [organizationId, otherOrganizationId])) |
| 122 | + await db.delete(user).where(inArray(user.id, [memberId, otherMemberId])) |
| 123 | + }) |
| 124 | + |
| 125 | + beforeEach(() => { |
| 126 | + mockRunHeadlessCopilotLifecycle.mockReset() |
| 127 | + organizationAuthorizationMockFns.mockAuthorizeOrganizationOperation.mockImplementation( |
| 128 | + async (principal: OAuthAccessTokenPrincipal) => ({ |
| 129 | + userId: principal.userId, |
| 130 | + organizationId, |
| 131 | + }) |
| 132 | + ) |
| 133 | + }) |
| 134 | + |
| 135 | + it('continues the caller’s conversation with the same chat and transcript', async () => { |
| 136 | + mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('The kit is in the suitcase.')) |
| 137 | + const first = await ask('Where is the field kit?') |
| 138 | + if (!first.chatId) throw new Error('Expected a saved conversation') |
| 139 | + |
| 140 | + mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('It is violet.')) |
| 141 | + const followUp = await ask('What colour is it?', first.chatId) |
| 142 | + |
| 143 | + expect(followUp.chatId).toBe(first.chatId) |
| 144 | + expect(mockRunHeadlessCopilotLifecycle).toHaveBeenLastCalledWith( |
| 145 | + expect.anything(), |
| 146 | + expect.objectContaining({ chatId: first.chatId }) |
| 147 | + ) |
| 148 | + expect(await transcript(first.chatId)).toHaveLength(4) |
| 149 | + expect(await liveChats(memberId)).toEqual([{ id: first.chatId }]) |
| 150 | + }) |
| 151 | + |
| 152 | + it.each([ |
| 153 | + ['another member’s conversation', 'other-member'], |
| 154 | + ['a conversation in another organization', 'other-organization'], |
| 155 | + ['a deleted conversation', 'deleted'], |
| 156 | + ['an Agent conversation', 'agent'], |
| 157 | + ['a value that is not a chat ID', 'malformed'], |
| 158 | + ])('refuses %s as not found before running anything', async (_case, kind) => { |
| 159 | + const chatId = generateId() |
| 160 | + if (kind !== 'malformed') |
| 161 | + await db.insert(copilotChats).values({ |
| 162 | + id: chatId, |
| 163 | + userId: kind === 'other-member' ? otherMemberId : memberId, |
| 164 | + organizationId: kind === 'other-organization' ? otherOrganizationId : organizationId, |
| 165 | + type: 'mothership', |
| 166 | + ...(kind === 'deleted' ? { deletedAt: new Date() } : {}), |
| 167 | + ...(kind === 'agent' ? { config: { conversationMode: 'agent' } } : {}), |
| 168 | + }) |
| 169 | + await expect( |
| 170 | + ask('Follow up', kind === 'malformed' ? 'not-a-chat' : chatId) |
| 171 | + ).rejects.toMatchObject({ code: 'not_found' }) |
| 172 | + expect(mockRunHeadlessCopilotLifecycle).not.toHaveBeenCalled() |
| 173 | + }) |
| 174 | + |
| 175 | + it('refuses a follow-up while the conversation is still answering', async () => { |
| 176 | + mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('First answer.')) |
| 177 | + const { chatId } = await ask('First question') |
| 178 | + if (!chatId) throw new Error('Expected a saved conversation') |
| 179 | + |
| 180 | + const running = createDeferred<OrchestratorResult>() |
| 181 | + const started = createDeferred<void>() |
| 182 | + mockRunHeadlessCopilotLifecycle.mockImplementationOnce(async () => { |
| 183 | + started.resolve() |
| 184 | + return running.promise |
| 185 | + }) |
| 186 | + const inFlight = ask('Second question', chatId) |
| 187 | + await started.promise |
| 188 | + |
| 189 | + await expect(ask('Third question', chatId)).rejects.toMatchObject({ code: 'conflict' }) |
| 190 | + running.resolve(answer('Second answer.')) |
| 191 | + await expect(inFlight).resolves.toMatchObject({ chatId }) |
| 192 | + |
| 193 | + mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce(answer('Third answer.')) |
| 194 | + await expect(ask('Third question', chatId)).resolves.toMatchObject({ chatId }) |
| 195 | + expect(await transcript(chatId)).toHaveLength(6) |
| 196 | + }) |
| 197 | + |
| 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') |
| 202 | + |
| 203 | + mockRunHeadlessCopilotLifecycle.mockResolvedValueOnce({ ...answer(''), success: false }) |
| 204 | + await expect(ask('Second question', chatId)).rejects.toThrow('could not finish') |
| 205 | + |
| 206 | + expect(await liveChats(memberId)).toContainEqual({ id: chatId }) |
| 207 | + expect(await transcript(chatId)).toHaveLength(2) |
| 208 | + }) |
| 209 | +}) |
0 commit comments