|
| 1 | +/** Real sync jobs, PostgreSQL, storage, indexing and authorized search; Slack and embedding responses are synthetic. */ |
| 2 | +import { mkdtempSync } from 'node:fs' |
| 3 | +import { rm } from 'node:fs/promises' |
| 4 | +import { tmpdir } from 'node:os' |
| 5 | +import path from 'node:path' |
| 6 | +import { db } from '@sim/db' |
| 7 | +import { |
| 8 | + document, |
| 9 | + embedding, |
| 10 | + knowledgeConnector, |
| 11 | + organization, |
| 12 | + user, |
| 13 | + workspace, |
| 14 | +} from '@sim/db/schema' |
| 15 | +import { generateId } from '@sim/utils/id' |
| 16 | +import { and, eq, inArray } from 'drizzle-orm' |
| 17 | +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' |
| 18 | + |
| 19 | +const fixture = vi.hoisted(() => ({ storageRoot: '', embeddingCalls: 0 })) |
| 20 | +vi.mock('@/lib/uploads/core/setup.server', () => ({ |
| 21 | + get UPLOAD_DIR_SERVER() { |
| 22 | + return fixture.storageRoot |
| 23 | + }, |
| 24 | +})) |
| 25 | +vi.mock('@/lib/embeddings', async () => ({ |
| 26 | + ...(await import('@/lib/embeddings/client')), |
| 27 | + assertKnowledgeEmbeddingCapacity: async () => {}, |
| 28 | + embedKnowledge: async (texts: string[]) => { |
| 29 | + fixture.embeddingCalls++ |
| 30 | + return { |
| 31 | + embeddings: texts.map(() => [1, ...Array<number>(1535).fill(0)]), |
| 32 | + totalTokens: texts.length, |
| 33 | + billableTokens: 0, |
| 34 | + isBYOK: true, |
| 35 | + modelName: 'text-embedding-3-small', |
| 36 | + pricingId: 'text-embedding-3-small', |
| 37 | + } |
| 38 | + }, |
| 39 | +})) |
| 40 | + |
| 41 | +import { resolveBillingAttribution } from '@/lib/billing/core/billing-attribution' |
| 42 | +import { |
| 43 | + createKnowledgeAclFixtureIds, |
| 44 | + seedKnowledgeAclFixture, |
| 45 | +} from '@/lib/knowledge/__integration__/seed-source-access-fixture' |
| 46 | +import { searchKnowledge } from '@/lib/knowledge/application/search' |
| 47 | +import * as connectorTokens from '@/lib/knowledge/connectors/access-token' |
| 48 | +import { executeConnectorSyncJob } from '@/background/knowledge-connector-sync' |
| 49 | + |
| 50 | +const TEAM = 'T0FIXTURE' |
| 51 | +const CHANNEL = 'C0GENERAL' |
| 52 | +const ROOT = '1700000100.000100' |
| 53 | +const REPLY = '1700000200.000100' |
| 54 | +const EXTERNAL_ID = `slack:v4:${TEAM}:${CHANNEL}:${ROOT}` |
| 55 | +const EMPTY_REASON = 'Document contains no extractable text' |
| 56 | + |
| 57 | +describe('Slack empty threads through sync jobs, indexing and search', () => { |
| 58 | + const ids = createKnowledgeAclFixtureIds() |
| 59 | + const documentId = generateId() |
| 60 | + let billing: Awaited<ReturnType<typeof resolveBillingAttribution>> |
| 61 | + let replyText = '' |
| 62 | + let incomplete = false |
| 63 | + let missingRoot = false |
| 64 | + const channel = { id: CHANNEL, name: 'general', is_archived: false } |
| 65 | + const root = () => ({ type: 'message', ts: ROOT, thread_ts: ROOT, text: '', reply_count: 1 }) |
| 66 | + |
| 67 | + async function providerFetch(input: string | URL | Request, init?: RequestInit) { |
| 68 | + const url = new URL( |
| 69 | + typeof input === 'string' ? input : input instanceof URL ? input.href : input.url |
| 70 | + ) |
| 71 | + expect(url.origin).toBe('https://slack.com') |
| 72 | + expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer fixture-slack-token') |
| 73 | + const method = url.pathname.split('/').at(-1) |
| 74 | + switch (method) { |
| 75 | + case 'auth.test': |
| 76 | + return Response.json({ ok: true, team_id: TEAM }) |
| 77 | + case 'conversations.list': |
| 78 | + return Response.json({ ok: true, channels: [channel] }) |
| 79 | + case 'conversations.info': |
| 80 | + return Response.json({ ok: true, channel }) |
| 81 | + case 'conversations.history': |
| 82 | + return Response.json({ ok: true, messages: [root()] }) |
| 83 | + case 'conversations.replies': |
| 84 | + if (missingRoot) return Response.json({ ok: true, messages: [] }) |
| 85 | + if (!url.searchParams.has('cursor')) { |
| 86 | + return Response.json({ |
| 87 | + ok: true, |
| 88 | + messages: [root()], |
| 89 | + has_more: true, |
| 90 | + response_metadata: { next_cursor: 'reply' }, |
| 91 | + }) |
| 92 | + } |
| 93 | + return Response.json({ |
| 94 | + ok: true, |
| 95 | + messages: [{ type: 'message', ts: REPLY, thread_ts: ROOT, text: replyText }], |
| 96 | + is_limited: incomplete, |
| 97 | + }) |
| 98 | + case 'chat.getPermalink': |
| 99 | + return Response.json({ |
| 100 | + ok: true, |
| 101 | + permalink: `https://fixture.slack.com/archives/${CHANNEL}/p${ROOT.replace('.', '')}`, |
| 102 | + }) |
| 103 | + default: |
| 104 | + throw new Error('Unexpected fixture Slack endpoint') |
| 105 | + } |
| 106 | + } |
| 107 | + async function sync() { |
| 108 | + return executeConnectorSyncJob({ |
| 109 | + connectorId: ids.connectorId, |
| 110 | + requestId: 'slack-empty-fixture', |
| 111 | + fullSync: true, |
| 112 | + billingAttribution: billing, |
| 113 | + }) |
| 114 | + } |
| 115 | + async function row() { |
| 116 | + const [stored] = await db |
| 117 | + .select() |
| 118 | + .from(document) |
| 119 | + .where(and(eq(document.connectorId, ids.connectorId), eq(document.externalId, EXTERNAL_ID))) |
| 120 | + expect(stored?.id).toBe(documentId) |
| 121 | + return stored! |
| 122 | + } |
| 123 | + async function vectors() { |
| 124 | + return db |
| 125 | + .select({ content: embedding.content }) |
| 126 | + .from(embedding) |
| 127 | + .where(eq(embedding.documentId, documentId)) |
| 128 | + } |
| 129 | + async function search() { |
| 130 | + const result = await searchKnowledge.execute({ |
| 131 | + principal: { kind: 'session', userId: ids.aliceId, sessionId: 'slack-empty-fixture' }, |
| 132 | + input: { |
| 133 | + workspaceId: ids.workspaceId, |
| 134 | + knowledgeBaseIds: [ids.knowledgeBaseId], |
| 135 | + query: 'Orion', |
| 136 | + searchMode: 'hybrid', |
| 137 | + topK: 10, |
| 138 | + }, |
| 139 | + }) |
| 140 | + return result.results.map((result) => result.documentId) |
| 141 | + } |
| 142 | + beforeAll(async () => { |
| 143 | + fixture.storageRoot = mkdtempSync(path.join(tmpdir(), 'sim-slack-empty-')) |
| 144 | + await seedKnowledgeAclFixture(ids) |
| 145 | + billing = await resolveBillingAttribution({ |
| 146 | + actorUserId: ids.aliceId, |
| 147 | + workspaceId: ids.workspaceId, |
| 148 | + }) |
| 149 | + await db |
| 150 | + .update(knowledgeConnector) |
| 151 | + .set({ |
| 152 | + connectorType: 'slack', |
| 153 | + sourceConfig: { channel: CHANNEL, maxMessages: 0 }, |
| 154 | + accessMode: 'workspace', |
| 155 | + status: 'active', |
| 156 | + syncLockToken: null, |
| 157 | + }) |
| 158 | + .where(eq(knowledgeConnector.id, ids.connectorId)) |
| 159 | + vi.spyOn(connectorTokens, 'resolveConnectorAccessToken').mockResolvedValue({ |
| 160 | + accessToken: 'fixture-slack-token', |
| 161 | + }) |
| 162 | + vi.stubGlobal('fetch', providerFetch) |
| 163 | + await db.insert(document).values({ |
| 164 | + id: documentId, |
| 165 | + knowledgeBaseId: ids.knowledgeBaseId, |
| 166 | + connectorId: ids.connectorId, |
| 167 | + externalId: EXTERNAL_ID, |
| 168 | + filename: 'Thread.txt', |
| 169 | + mimeType: 'text/plain', |
| 170 | + fileUrl: '', |
| 171 | + fileSize: 0, |
| 172 | + processingStatus: 'failed', |
| 173 | + processingError: 'Synthetic previous source failure', |
| 174 | + }) |
| 175 | + }) |
| 176 | + afterAll(async () => { |
| 177 | + await db.delete(workspace).where(eq(workspace.id, ids.workspaceId)) |
| 178 | + await db.delete(organization).where(eq(organization.id, ids.organizationId)) |
| 179 | + await db.delete(user).where(inArray(user.id, [ids.aliceId, ids.bobId])) |
| 180 | + await rm(fixture.storageRoot, { recursive: true, force: true }) |
| 181 | + vi.restoreAllMocks() |
| 182 | + vi.unstubAllGlobals() |
| 183 | + await db.$client.end() |
| 184 | + }) |
| 185 | + |
| 186 | + it('completes empty-thread syncs, recovers reply edits and removes stale searchable text', async () => { |
| 187 | + expect(await sync()).toMatchObject({ |
| 188 | + outcome: 'completed', |
| 189 | + docsFailed: 0, |
| 190 | + docsSkipped: 1, |
| 191 | + processingDispatch: { requested: 0, failed: 0 }, |
| 192 | + }) |
| 193 | + expect(await row()).toMatchObject({ |
| 194 | + processingStatus: 'failed', |
| 195 | + processingError: EMPTY_REASON, |
| 196 | + storageKey: null, |
| 197 | + }) |
| 198 | + expect(await vectors()).toEqual([]) |
| 199 | + expect(fixture.embeddingCalls).toBe(0) |
| 200 | + expect(await sync()).toMatchObject({ outcome: 'completed', docsFailed: 0 }) |
| 201 | + expect(fixture.embeddingCalls).toBe(0) |
| 202 | + |
| 203 | + replyText = 'Orion launch is scheduled for Friday.' |
| 204 | + expect(await sync()).toMatchObject({ outcome: 'completed', docsFailed: 0, docsUpdated: 1 }) |
| 205 | + expect(await row()).toMatchObject({ processingStatus: 'completed', processingError: null }) |
| 206 | + expect((await vectors()).map((row) => row.content).join(' ')).toContain(replyText) |
| 207 | + expect(await search()).toContain(documentId) |
| 208 | + const embedded = fixture.embeddingCalls |
| 209 | + expect(await sync()).toMatchObject({ outcome: 'completed', docsUnchanged: 1 }) |
| 210 | + expect(fixture.embeddingCalls).toBe(embedded) |
| 211 | + |
| 212 | + replyText = '' |
| 213 | + expect(await sync()).toMatchObject({ outcome: 'completed', docsFailed: 0, docsSkipped: 1 }) |
| 214 | + expect(await row()).toMatchObject({ processingError: EMPTY_REASON, storageKey: null }) |
| 215 | + expect(await vectors()).toEqual([]) |
| 216 | + expect(fixture.embeddingCalls).toBe(embedded) |
| 217 | + expect(await search()).not.toContain(documentId) |
| 218 | + |
| 219 | + replyText = 'Orion launch moved to Monday.' |
| 220 | + expect(await sync()).toMatchObject({ outcome: 'completed', docsUpdated: 1 }) |
| 221 | + expect(await search()).toContain(documentId) |
| 222 | + const restored = await vectors() |
| 223 | + incomplete = true |
| 224 | + replyText = '' |
| 225 | + await expect(sync()).rejects.toThrow('1 source failures') |
| 226 | + expect(await vectors()).toEqual(restored) |
| 227 | + expect((await row()).storageKey).not.toBeNull() |
| 228 | + incomplete = false |
| 229 | + missingRoot = true |
| 230 | + await expect(sync()).rejects.toThrow('1 source failures') |
| 231 | + expect(await vectors()).toEqual(restored) |
| 232 | + }, 60000) |
| 233 | +}) |
0 commit comments