diff --git a/apps/sim/lib/api/contracts/knowledge/mcp.ts b/apps/sim/lib/api/contracts/knowledge/mcp.ts index b5d6571bbb7..b2b2cf25e75 100644 --- a/apps/sim/lib/api/contracts/knowledge/mcp.ts +++ b/apps/sim/lib/api/contracts/knowledge/mcp.ts @@ -75,19 +75,23 @@ export function liveSearchMcpDefaultTopK(input: z.output read(reference: Reference, filters?: WorkspaceSearchFilters): Promise + /** + * The reference a pasted link names within this account, bound like a search result's, or + * undefined when the link names another provider, site, host or workspace. Not a permission + * check: a located reference is verified like any other before it is read. + */ + locate(link: DocumentLink): Promise /** * Full text of a search result whose provider returned only an excerpt or metadata; `signal` * cancels the read when its preview is no longer wanted. @@ -254,6 +261,11 @@ export async function openLiveAccountSession( ) return readMcp(reference) }, + async locate(link) { + if (link.provider !== provider) return undefined + const located = await locateDocumentLink(link, { client, origin }) + return located && (connectionBinding ? { ...located, connectionBinding } : located) + }, async previewText(document, previewSignal) { if (admin || !client) return undefined return previewNativeText(provider, withRequestSignal(client, previewSignal), document) diff --git a/apps/sim/lib/sim-search/live/application.test.ts b/apps/sim/lib/sim-search/live/application.test.ts index 006547ca81a..4066255b111 100644 --- a/apps/sim/lib/sim-search/live/application.test.ts +++ b/apps/sim/lib/sim-search/live/application.test.ts @@ -1311,6 +1311,122 @@ describe('authorized live retrieval', () => { ).rejects.toMatchObject({ message: expect.stringContaining('next.startOffset') }) expect(mocks.read).not.toHaveBeenCalled() }) + describe('pasted links', () => { + const owner = liveReferenceOwner( + 'reader', + resourceScopeKey(resourceScopeFromOwner({ workspaceId: 'workspace' })) + ) + const read = (documentId: string) => + readLiveDocument.execute({ + principal, + input: { + workspaceId: 'workspace', + documentId, + limit: 3, + resultSecretRegistry: new ResolvedSecretTraceRegistry([]), + }, + }) + const confluence = (id: string) => ({ + ...account, + id, + provider: 'confluence', + providerId: 'confluence', + displayName: id, + }) + + it('reads a Drive link and names it by the ID search mints, which reads back', async () => { + mocks.read.mockResolvedValue({ + ...document, + id: '1AbcDEFghijKLmn', + kind: 'application/vnd.google-apps.document', + }) + const result = await read('https://drive.google.com/file/d/1AbcDEFghijKLmn/view') + expect(mocks.read).toHaveBeenCalledWith( + 'google_drive', + expect.anything(), + { id: '1AbcDEFghijKLmn' }, + expect.anything() + ) + expect(decodeLiveReference(result.documentId)).toEqual({ + account: 'account', + provider: 'google_drive', + id: '1AbcDEFghijKLmn', + kind: 'application/vnd.google-apps.document', + }) + expect(result.chunks[0]?.content).toBe('Evidence') + await expect(read(result.documentId)).resolves.toMatchObject({ + documentId: result.documentId, + }) + }) + + it('verifies a linked document before reading it, like a document ID', async () => { + mocks.service.mockResolvedValue({ + policy: defaultLiveSearchPolicy(), + verify: vi.fn(async () => false), + partial: false, + }) + await expect(read('https://drive.google.com/file/d/1AbcDEFghijKLmn/view')).rejects.toThrow( + 'outside your organization' + ) + expect(mocks.read).not.toHaveBeenCalled() + }) + + it('reads an Atlassian link only from the account on its site', async () => { + mocks.accounts.mockResolvedValue([confluence('site-a'), confluence('site-b')]) + mocks.json + .mockResolvedValueOnce([{ id: 'cloud-a', url: 'https://a.atlassian.net' }]) + .mockResolvedValueOnce([{ id: 'cloud-b', url: 'https://b.atlassian.net' }]) + mocks.read.mockResolvedValue({ ...document, id: '12345', kind: 'page', container: 'cloud-b' }) + const result = await read('https://b.atlassian.net/wiki/spaces/ENG/pages/12345/Launch') + expect(mocks.read).toHaveBeenCalledOnce() + expect(mocks.read).toHaveBeenCalledWith( + 'confluence', + expect.anything(), + { id: '12345', kind: 'page', container: 'cloud-b' }, + expect.anything() + ) + expect(result.documentId).toBe( + encodeLiveReference( + { + account: 'site-b', + provider: 'confluence', + id: '12345', + kind: 'page', + container: 'cloud-b', + }, + owner + ) + ) + }) + + it('reports one account’s specific reason over another account not finding the link', async () => { + mocks.accounts.mockResolvedValue([confluence('site-a'), confluence('site-a-2')]) + mocks.json + .mockResolvedValueOnce([{ id: 'cloud-a', url: 'https://a.atlassian.net' }]) + .mockResolvedValueOnce([{ id: 'cloud-a', url: 'https://a.atlassian.net' }]) + mocks.read + .mockRejectedValueOnce(new NativeSearchError('unavailable', 'Gone', undefined, 404)) + .mockRejectedValueOnce(new NativeSearchError('reconnect', 'The provider denied access.')) + await expect(read('https://a.atlassian.net/wiki/spaces/ENG/pages/7')).rejects.toMatchObject({ + code: 'unauthorized', + message: expect.stringContaining('Reconnect Confluence'), + }) + }) + + it('names the source to connect when no account can open the link', async () => { + await expect(read('https://acme.slack.com/archives/C0123/p1700000000123456')).rejects.toThrow( + 'No connected Slack account' + ) + expect(mocks.resolveAccount).not.toHaveBeenCalled() + }) + + it('refuses a link it cannot read before listing any account', async () => { + await expect(read('https://example.com/about')).rejects.toMatchObject({ + code: 'validation', + }) + expect(mocks.accounts).not.toHaveBeenCalled() + }) + }) describe('live document IDs', () => { const workspaceScope = resourceScopeKey(resourceScopeFromOwner({ workspaceId: 'workspace' })) /** The earlier wire form, spelled out so these tests pin what older conversations hold. */ diff --git a/apps/sim/lib/sim-search/live/application.ts b/apps/sim/lib/sim-search/live/application.ts index 3623352902a..f9b4eeca1b5 100644 --- a/apps/sim/lib/sim-search/live/application.ts +++ b/apps/sim/lib/sim-search/live/application.ts @@ -60,6 +60,7 @@ import { } from '@/lib/sim-search/live/account-session' import { listLiveAccounts, + type ResolvedLiveAccount, resolveListedLiveAccount, resolveLiveAccount, } from '@/lib/sim-search/live/accounts' @@ -72,6 +73,11 @@ import { withImpliedListingBound, } from '@/lib/sim-search/live/dates' import { NativeSearchError } from '@/lib/sim-search/live/http' +import { + type DocumentLink, + LINKABLE_SOURCES, + parseDocumentLinks, +} from '@/lib/sim-search/live/links' import { isManagedSearchMcpProvider } from '@/lib/sim-search/live/managed-mcp-config' import { joinMessages } from '@/lib/sim-search/live/pages' import { loadLiveSearchPolicies } from '@/lib/sim-search/live/policy-store' @@ -1066,6 +1072,212 @@ function liveReadFailure(error: unknown, provider: string, deadline?: AbortSigna return error } +interface AccountReadInput { + owner: ResourceOwner + userId: string + resolved: ResolvedLiveAccount + policies: Record + signal: AbortSignal + filters?: WorkspaceSearchFilters + /** The reference to read within the account's session, or undefined when it holds none. */ + locate(session: LiveAccountSession): ReturnType +} + +/** + * Reads one account's document through the boundary every live read crosses: the reference is + * verified against the member's access and the source settings before its content is fetched, and + * the fetched document against the settings saved now. Undefined when the account holds no + * document the reference could name. + */ +async function readAccountDocument({ + owner, + userId, + resolved, + policies, + signal, + filters, + locate, +}: AccountReadInput) { + const pool = createPinnedConnectionPool() + let session: LiveAccountSession | undefined + try { + const opened = await measureSearchStage('live.session', () => + openLiveAccountSession({ owner, userId, resolved, policies, signal, pool }) + ) + session = opened + const reference = await locate(opened) + if (!reference) return undefined + if (!(await measureSearchStage('live.verify', () => opened.verify(reference)))) + throw new OrchestrationError( + 'not_found', + 'Document is outside your organization’s search scope' + ) + const document = await measureSearchStage('live.read', () => opened.read(reference, filters)) + /** Readers degrade section failures to warnings, so the signal decides cancellation. */ + signal.throwIfAborted() + const current = await measureSearchStage('live.verify', () => opened.verifyCurrent(document)) + /** A verifier may report a check cut short by cancellation as a normal result. */ + signal.throwIfAborted() + if (!current) + throw new OrchestrationError( + 'not_found', + 'Document is outside your organization’s search scope' + ) + return { reference, document } + } finally { + try { + await session?.close() + } finally { + pool.destroy() + } + } +} + +/** Reads the document a live document ID names, from the account the ID names. */ +async function readReferencedDocument( + input: LiveReadInput, + userId: string, + owner: string, + signal: AbortSignal +) { + const reference = readLiveReference(input.documentId, owner) + if ( + (input.filters?.source && input.filters.source !== reference.provider) || + (input.filters?.documentIds && + !includesLiveDocument(input.filters.documentIds, input.documentId)) + ) + throw new OrchestrationError('not_found', 'Document is outside the selected search filters') + annotateSearchDiagnostics({ provider: reference.provider }) + const read = await withSearchProviderDiagnostics({ provider: reference.provider }, async () => { + const [resolved, policies] = await Promise.all([ + measureSearchStage('live.resolve', () => + waitWithAbort(resolveLiveAccount(input, userId, reference.account, signal), signal) + ), + measureSearchStage('live.policies', () => loadLiveSearchPolicies(input)), + ]) + if (resolved.account.provider !== reference.provider) + throw new OrchestrationError('not_found', 'Document account changed') + const read = await readAccountDocument({ + owner: input, + userId, + resolved, + policies, + signal, + filters: input.filters, + locate: async () => reference, + }) + if (!read) throw new OrchestrationError('not_found', 'Document not found') + return { account: resolved.account, document: read.document } + }).catch((error: unknown) => { + /** Cancellation by the caller passes through unclassified. */ + throw input.signal?.aborted ? error : liveReadFailure(error, reference.provider, signal) + }) + return { documentId: input.documentId, reference, ...read } +} + +/** Accounts one link read tries, in listing order, until one of them reads the document. */ +const MAX_LINK_ACCOUNTS = 5 + +/** + * Reads the document a pasted link names from the first of the reader's own accounts that holds + * it. The link only selects a location: each account resolves it within its own grant, and the + * read crosses the same verification as a read by document ID, so a link never reaches a + * document the reader's search could not return. The result is named by the document ID a search + * of that account mints, so a continuation reads by ID. + */ +async function readLinkedDocument( + input: LiveReadInput, + userId: string, + links: DocumentLink[], + owner: string, + signal: AbortSignal +) { + const providers = new Set(links.map((link) => link.provider)) + const sourceNames = [...providers].map(liveProviderName).join(' or ') + const [accounts, policies] = await Promise.all([ + measureSearchStage('live.resolve', () => + waitWithAbort(listLiveAccounts(input, userId), signal) + ), + measureSearchStage('live.policies', () => loadLiveSearchPolicies(input)), + ]).catch((error: unknown) => { + /** Cancellation by the caller passes through unclassified. */ + throw input.signal?.aborted ? error : liveReadFailure(error, links[0]?.provider ?? '', signal) + }) + const matching = accounts.filter( + (account) => + links.some((link) => link.provider === account.provider) && + (!input.filters?.source || input.filters.source === account.provider) + ) + const candidates = matching.slice(0, MAX_LINK_ACCOUNTS) + if (!candidates.length) + throw new OrchestrationError( + 'not_found', + `No connected ${sourceNames} account can open this link. Connect one for Search, or search for the document instead.` + ) + let failure: unknown + for (const account of candidates) { + annotateSearchDiagnostics({ provider: account.provider }) + try { + const read = await withSearchProviderDiagnostics({ provider: account.provider }, async () => + readAccountDocument({ + owner: input, + userId, + resolved: await waitWithAbort( + resolveListedLiveAccount(input, userId, account, signal), + signal + ), + policies, + signal, + filters: input.filters, + async locate(session) { + for (const link of links) { + const located = await session.locate(link) + if (located) return located + } + return undefined + }, + }) + ) + if (!read) continue + /** The reader's own location fields, so the ID matches the one a search of the account mints. */ + const { id, container, kind } = read.document + const reference = { + account: account.id, + provider: account.provider, + ...read.reference, + ...(id ? { id } : {}), + ...(container ? { container } : {}), + ...(kind ? { kind } : {}), + } + return { + documentId: encodeLiveReference(reference, owner), + reference, + account, + document: read.document, + } + } catch (error) { + if (input.signal?.aborted) throw error + const classified = liveReadFailure(error, account.provider, signal) + /** A specific reason from one account says more than another account not holding it. */ + if ( + failure === undefined || + (failure instanceof OrchestrationError && failure.code === 'not_found') + ) + failure = classified + if (signal.aborted) break + } + } + throw ( + failure ?? + new OrchestrationError( + 'not_found', + matching.length > candidates.length + ? `None of the first ${MAX_LINK_ACCOUNTS} of your ${matching.length} connected ${sourceNames} accounts reaches this link. Search for the document instead.` + : `This link is not on a site, workspace or host your connected ${sourceNames} account reaches. Search for the document instead.` + ) + ) +} + const liveDocumentRead = defineAuthorizedKnowledgeUseCase({ operation: knowledgeOperations.readDocument, resolveContext: ({ input }: { input: LiveReadInput }) => resolveKnowledgeOwnerContext(input), @@ -1081,73 +1293,20 @@ const liveDocumentRead = defineAuthorizedKnowledgeUseCase({ 'validation', 'Live documents use chunk index zero; continue using next.startOffset' ) - const reference = readLiveReference( - input.documentId, - liveReferenceOwner(userId, resourceScopeKey(resourceScopeFromOwner(input))) - ) - if ( - (input.filters?.source && input.filters.source !== reference.provider) || - (input.filters?.documentIds && - !includesLiveDocument(input.filters.documentIds, input.documentId)) - ) - throw new OrchestrationError('not_found', 'Document is outside the selected search filters') - /** Cancellation by the caller passes through unclassified. */ - const readFailure = (error: unknown, deadline?: AbortSignal) => - input.signal?.aborted ? error : liveReadFailure(error, reference.provider, deadline) - annotateSearchDiagnostics({ provider: reference.provider }) + const owner = liveReferenceOwner(userId, resourceScopeKey(resourceScopeFromOwner(input))) const deadline = AbortSignal.timeout(READ_DEADLINE_MS) const signal = input.signal ? AbortSignal.any([input.signal, deadline]) : deadline - const { resolved, document } = await withSearchProviderDiagnostics( - { provider: reference.provider }, - async () => { - const [resolved, policies] = await Promise.all([ - measureSearchStage('live.resolve', () => - waitWithAbort(resolveLiveAccount(input, userId, reference.account, signal), signal) - ), - measureSearchStage('live.policies', () => loadLiveSearchPolicies(input)), - ]) - if (resolved.account.provider !== reference.provider) - throw new OrchestrationError('not_found', 'Document account changed') - const pool = createPinnedConnectionPool() - let session: LiveAccountSession | undefined - try { - const opened = await measureSearchStage('live.session', () => - openLiveAccountSession({ owner: input, userId, resolved, policies, signal, pool }) - ) - session = opened - if (!(await measureSearchStage('live.verify', () => opened.verify(reference)))) - throw new OrchestrationError( - 'not_found', - 'Document is outside your organization’s search scope' - ) - const document = await measureSearchStage('live.read', () => - opened.read(reference, input.filters) - ) - /** Readers degrade section failures to warnings, so the signal decides cancellation. */ - signal.throwIfAborted() - const current = await measureSearchStage('live.verify', () => - opened.verifyCurrent(document) - ) - /** A verifier may report a check cut short by cancellation as a normal result. */ - signal.throwIfAborted() - if (!current) - throw new OrchestrationError( - 'not_found', - 'Document is outside your organization’s search scope' - ) - return { resolved, document } - } finally { - try { - await session?.close() - } finally { - pool.destroy() - } - } - } - ).catch((error: unknown) => { - throw readFailure(error, deadline) - }) - if (!matchesLiveFilters(document, input.documentId, reference.provider, input.filters)) + const links = parseDocumentLinks(input.documentId) + if (links && !links.length) + throw new OrchestrationError( + 'validation', + `Sim cannot read this link directly. Links to ${LINKABLE_SOURCES} items read; for anything else, search for the document by its title.` + ) + annotateSearchDiagnostics({ fromLink: Boolean(links) }) + const { documentId, reference, account, document } = links + ? await readLinkedDocument(input, userId, links, owner, signal) + : await readReferencedDocument(input, userId, owner, signal) + if (!matchesLiveFilters(document, documentId, reference.provider, input.filters)) throw new OrchestrationError('not_found', 'Document is outside the selected search filters') const content = safeContent(document.content, input.resultSecretRegistry) const start = input.startOffset ?? 0 @@ -1164,9 +1323,9 @@ const liveDocumentRead = defineAuthorizedKnowledgeUseCase({ hasMore: end < content.length, }) return { - documentId: input.documentId, + documentId, knowledgeBaseId: '', - knowledgeBaseName: resolved.account.displayName, + knowledgeBaseName: account.displayName, documentName: safeContent(document.title, input.resultSecretRegistry), sourceUrl: isKnowledgeSourceUrl(document.url) ? document.url : null, connectorType: reference.provider, diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index aae29c76799..a8993f19cb9 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -116,6 +116,21 @@ async function sites(client: NativeClient) { return array(await client.json('/oauth/token/accessible-resources', { memo: true })) } +/** The cloud ID of the grant's site served at `host`, as a link to one of its pages names it. */ +export async function atlassianSiteId( + client: NativeClient, + host: string +): Promise { + const site = (await sites(client)).find((row) => { + try { + return new URL(string(row.url)).host === host + } catch { + return false + } + }) + return string(site?.id) || undefined +} + /** * One Atlassian site's page; `ranking` marks a page whose order or completeness differs from the * all-terms search. diff --git a/apps/sim/lib/sim-search/live/linear.ts b/apps/sim/lib/sim-search/live/linear.ts index e6aaac0e512..0b2e2acf275 100644 --- a/apps/sim/lib/sim-search/live/linear.ts +++ b/apps/sim/lib/sim-search/live/linear.ts @@ -169,6 +169,33 @@ export async function searchLinear( } } +/** + * The issue a link's key names in the account's own workspace, or undefined when the account's + * workspace is another one: issue keys repeat across Linear workspaces. + */ +export async function linearIssueReference( + client: NativeClient, + workspace: string, + issueKey: string +): Promise | undefined> { + const data = await linearQuery( + client, + ` + query LocateLinearIssue($id: String!) { + issue(id: $id) { id url team { id } } + } + `, + { id: issueKey } + ) + const issue = object(data.issue) + const id = string(issue.id) + const url = linearUrl(issue.url) + if (!UUID.test(id) || !url) return undefined + if (new URL(url).pathname.split('/')[1]?.toLowerCase() !== workspace) return undefined + const team = string(object(issue.team).id) + return { id, kind: 'issue', ...(team ? { container: team } : {}) } +} + export async function readLinear(client: NativeClient, id: string): Promise { if (!UUID.test(id)) throw new NativeSearchError('unavailable', 'Invalid Linear issue reference.') const data = await linearQuery( diff --git a/apps/sim/lib/sim-search/live/links.test.ts b/apps/sim/lib/sim-search/live/links.test.ts new file mode 100644 index 00000000000..ca1ca9e2a27 --- /dev/null +++ b/apps/sim/lib/sim-search/live/links.test.ts @@ -0,0 +1,250 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it, vi } from 'vitest' +import { locateDocumentLink, parseDocumentLinks } from '@/lib/sim-search/live/links' +import type { NativeClient } from '@/lib/sim-search/live/types' + +describe('parseDocumentLinks', () => { + it.each([ + [ + 'a Google Doc opened from a second signed-in account', + 'https://docs.google.com/document/u/1/d/1AbcDEFghijKLmn/edit#heading=h.x', + { + provider: 'google_drive', + reference: { id: '1AbcDEFghijKLmn', kind: 'application/vnd.google-apps.document' }, + }, + ], + [ + 'a Drive file', + 'https://drive.google.com/file/d/1AbcDEFghijKLmn/view?usp=sharing', + { provider: 'google_drive', reference: { id: '1AbcDEFghijKLmn' } }, + ], + [ + 'the Gmail link a search result cites', + 'https://mail.google.com/mail/u/0/#all/18c0ffee12345678', + { provider: 'gmail', reference: { id: '18c0ffee12345678' } }, + ], + [ + 'a Calendar event on a gmail.com calendar', + `https://www.google.com/calendar/event?eid=${Buffer.from('evt_20260101 jane@m').toString('base64url')}`, + { + provider: 'google_calendar', + reference: { id: 'evt_20260101', container: 'jane@gmail.com' }, + }, + ], + [ + 'a Slack thread reply', + 'https://acme.slack.com/archives/C0123ABC/p1700000000123456?thread_ts=1699999999.000100&cid=C0123ABC', + { + provider: 'slack', + reference: { + id: '1700000000.123456', + container: 'C0123ABC', + threadId: '1699999999.000100', + }, + }, + ], + [ + 'a Slack canvas', + 'https://acme.slack.com/docs/T0123/F0456CANVAS', + { provider: 'slack', reference: { id: 'F0456CANVAS', kind: 'file' } }, + ], + [ + 'a pull request tab', + 'https://github.com/acme/api/pull/42/files', + { provider: 'github', reference: { container: 'acme/api', id: '42', kind: 'issues' } }, + ], + [ + 'a commit within a pull request', + 'https://github.com/acme/api/pull/42/commits/abc1234', + { provider: 'github', reference: { container: 'acme/api', id: 'abc1234', kind: 'commits' } }, + ], + [ + 'a file, whose branch and path the repository tells apart', + 'https://github.com/acme/api/blob/release/2026/src/index.ts#L10', + { + provider: 'github', + repository: 'acme/api', + blob: ['release', '2026', 'src', 'index.ts'], + }, + ], + [ + 'a repository clone URL', + 'https://github.com/acme/api.git', + { + provider: 'github', + reference: { container: 'acme/api', id: 'acme/api', kind: 'repositories' }, + }, + ], + [ + 'a Linear issue', + 'https://linear.app/Acme/issue/eng-12/fix-login', + { provider: 'linear', workspace: 'acme', issueKey: 'ENG-12' }, + ], + [ + 'a Notion page', + 'https://www.notion.so/acme/Roadmap-0123456789abcdef0123456789abcdef', + { + provider: 'notion', + reference: { id: '01234567-89ab-cdef-0123-456789abcdef', kind: 'mcp' }, + }, + ], + [ + 'a Fireflies meeting with its title', + 'https://app.fireflies.ai/view/Weekly-sync::01M4BH6WW1J5XC9A1HX83DGGQN', + { provider: 'fireflies', reference: { id: '01M4BH6WW1J5XC9A1HX83DGGQN', kind: 'meeting' } }, + ], + ])('reads %s as the reference its reader takes', (_case, link, expected) => { + expect(parseDocumentLinks(link)).toEqual([expected]) + }) + + it.each([ + [ + 'a Jira issue selected on a board', + 'https://acme.atlassian.net/jira/software/projects/ENG/boards/1?selectedIssue=ENG-7', + [{ provider: 'jira', host: 'acme.atlassian.net', reference: { id: 'ENG-7' } }], + ], + [ + 'a dated Confluence blog post', + 'https://acme.atlassian.net/wiki/spaces/ENG/blog/2026/01/31/98765/Launch', + [ + { + provider: 'confluence', + host: 'acme.atlassian.net', + reference: { id: '98765', kind: 'blogpost' }, + }, + ], + ], + [ + 'a Confluence space overview', + 'https://acme.atlassian.net/wiki/spaces/ENG/overview', + [ + { + provider: 'confluence', + host: 'acme.atlassian.net', + reference: { id: 'ENG', kind: 'space' }, + }, + ], + ], + [ + 'a merge request on a self-hosted GitLab in a subgroup', + 'https://git.acme.dev/platform/infra/api/-/merge_requests/9/diffs', + [ + { + provider: 'gitlab', + host: 'git.acme.dev', + reference: { container: 'platform/infra/api', id: '9', kind: 'merge_requests' }, + }, + ], + ], + ])('reads %s on any host, for the account on that host', (_case, link, expected) => { + expect(parseDocumentLinks(link)).toEqual(expected) + }) + + it('leaves values that are not web links to the document ID path', () => { + expect(parseDocumentLinks('live2:google_drive~account~doc~abc123')).toBeUndefined() + }) + + it.each([ + ['a plain-HTTP link', 'http://docs.google.com/document/d/1AbcDEFghijKLmn/edit'], + ['a link carrying credentials', 'https://user:pass@acme.atlassian.net/browse/ENG-1'], + ['a published copy of a Doc', 'https://docs.google.com/document/d/e/2PACX-1vQabcdefghij/pub'], + ['a Slack channel', 'https://acme.slack.com/archives/C0123ABC'], + ['a GitHub site page', 'https://github.com/orgs/acme/projects'], + ['a GitHub site listing', 'https://github.com/pulls/assigned'], + [ + 'a Gmail conversation without a message ID', + 'https://mail.google.com/mail/u/0/#inbox/FMfcgzQXJ', + ], + ['an unrelated site', 'https://example.com/about'], + ])('names nothing for %s', (_case, link) => { + expect(parseDocumentLinks(link)).toEqual([]) + }) +}) + +describe('locateDocumentLink', () => { + const client = (response: unknown): NativeClient => ({ + json: vi.fn(async () => response), + text: vi.fn(), + bytes: vi.fn(), + }) + + it('places an Atlassian link only on the grant’s site served at its host', async () => { + const [link] = parseDocumentLinks('https://b.atlassian.net/browse/ENG-7') ?? [] + if (!link) throw new Error('Expected a link') + const sites = [ + { id: 'cloud-a', url: 'https://a.atlassian.net' }, + { id: 'cloud-b', url: 'https://B.atlassian.net' }, + ] + const origin = 'https://api.atlassian.com' + await expect(locateDocumentLink(link, { client: client(sites), origin })).resolves.toEqual({ + id: 'ENG-7', + container: 'cloud-b', + }) + await expect( + locateDocumentLink(link, { client: client(sites.slice(0, 1)), origin }) + ).resolves.toBeUndefined() + }) + + it('places a GitLab link only on the account’s own host', async () => { + const [link] = parseDocumentLinks('https://git.acme.dev/team/api/-/issues/3') ?? [] + if (!link) throw new Error('Expected a link') + await expect( + locateDocumentLink(link, { client: null, origin: 'https://gitlab.com' }) + ).resolves.toBeUndefined() + await expect( + locateDocumentLink(link, { client: null, origin: 'https://git.acme.dev' }) + ).resolves.toEqual({ container: 'team/api', id: '3', kind: 'issues' }) + }) + + it('reads a file link on the default branch, whose name may hold slashes, and only there', async () => { + const [link] = + parseDocumentLinks('https://github.com/acme/api/blob/release/2026/src/a.ts') ?? [] + if (!link) throw new Error('Expected a link') + const origin = 'https://api.github.com' + const repository = (branch: string) => client({ full_name: 'Acme/api', default_branch: branch }) + await expect( + locateDocumentLink(link, { client: repository('release/2026'), origin }) + ).resolves.toEqual({ id: 'src/a.ts', container: 'Acme/api', kind: 'code' }) + await expect(locateDocumentLink(link, { client: repository('main'), origin })).rejects.toThrow( + 'default branch (main)' + ) + }) + + it('names the branch of a GitLab file link, as a GitLab source pins one', async () => { + const [link] = parseDocumentLinks('https://git.acme.dev/team/api/-/blob/main/src/a.ts') ?? [] + if (!link) throw new Error('Expected a link') + await expect( + locateDocumentLink(link, { + client: client({ id: 42, default_branch: 'main' }), + origin: 'https://git.acme.dev', + }) + ).resolves.toEqual({ id: 'src/a.ts', container: '42', kind: 'code', revision: 'main' }) + }) + + it('refuses a Linear key that names an issue in another workspace', async () => { + const [link] = parseDocumentLinks('https://linear.app/acme/issue/ENG-12') ?? [] + if (!link) throw new Error('Expected a link') + const issue = (workspace: string) => ({ + data: { + issue: { + id: '00000000-0000-4000-8000-000000000001', + url: `https://linear.app/${workspace}/issue/ENG-12/title`, + team: { id: 'team' }, + }, + }, + }) + const origin = 'https://api.linear.app' + await expect( + locateDocumentLink(link, { client: client(issue('other')), origin }) + ).resolves.toBeUndefined() + await expect( + locateDocumentLink(link, { client: client(issue('acme')), origin }) + ).resolves.toEqual({ + id: '00000000-0000-4000-8000-000000000001', + kind: 'issue', + container: 'team', + }) + }) +}) diff --git a/apps/sim/lib/sim-search/live/links.ts b/apps/sim/lib/sim-search/live/links.ts new file mode 100644 index 00000000000..f36f5e8e422 --- /dev/null +++ b/apps/sim/lib/sim-search/live/links.ts @@ -0,0 +1,386 @@ +import { parseGitHubRepository } from '@/lib/oauth/github-repository' +import { atlassianSiteId } from '@/lib/sim-search/live/atlassian' +import { NativeSearchError, object, string } from '@/lib/sim-search/live/http' +import { linearIssueReference } from '@/lib/sim-search/live/linear' +import { notionResource } from '@/lib/sim-search/live/notion-mcp' +import type { NativeClient, NativeDocument } from '@/lib/sim-search/live/types' +import { encodeGitLabResourceId } from '@/tools/gitlab/utils' + +/** The location fields a live document ID carries, as each provider's reader expects them. */ +export type LinkedReference = Pick< + NativeDocument, + 'id' | 'container' | 'kind' | 'revision' | 'threadId' +> + +/** + * A provider document a pasted link names, as far as the link alone can tell. Atlassian links + * name their site by host rather than by the cloud ID reads take, GitLab links name a host that + * must be the account's own, Linear links name an issue by its key rather than its UUID, and a + * file link's branch and path share one run of segments, so those finish against the account that + * reads them. + */ +export type DocumentLink = + | { + provider: + | 'google_drive' + | 'gmail' + | 'google_calendar' + | 'slack' + | 'github' + | 'notion' + | 'fireflies' + reference: LinkedReference + } + | { + provider: 'jira' | 'confluence' | 'gitlab' + host: string + reference: LinkedReference + } + | { provider: 'linear'; workspace: string; issueKey: string } + | { + provider: 'github' | 'gitlab' + /** The host a GitLab link names; GitHub links are always github.com. */ + host?: string + repository: string + /** The segments after `blob`: a branch, which may itself contain slashes, then the path. */ + blob: string[] + } + +/** Providers whose links {@link parseDocumentLinks} recognizes, for the caller's error message. */ +export const LINKABLE_SOURCES = + 'Google Docs, Sheets, Slides and Drive files, Gmail, Google Calendar events, Slack messages and files, Jira issues, Confluence pages, GitHub, GitLab, Linear, Notion and Fireflies' + +const DRIVE_ID = /^[\w-]{10,}$/ +const GOOGLE_EDITOR_KINDS: Record = { + document: 'application/vnd.google-apps.document', + spreadsheets: 'application/vnd.google-apps.spreadsheet', + presentation: 'application/vnd.google-apps.presentation', +} +const JIRA_KEY = /^[A-Z][A-Z\d_]*-\d+$/ +const NUMERIC_ID = /^\d+$/ +/** First path segments on github.com that are site pages, not repository owners. */ +const GITHUB_RESERVED_OWNERS = new Set([ + 'apps', + 'codespaces', + 'collections', + 'dashboard', + 'enterprises', + 'explore', + 'features', + 'issues', + 'login', + 'marketplace', + 'new', + 'notifications', + 'organizations', + 'orgs', + 'pulls', + 'search', + 'settings', + 'sponsors', + 'topics', + 'users', +]) + +function pathSegments(url: URL): string[] { + return url.pathname + .split('/') + .filter(Boolean) + .map((part) => { + try { + return decodeURIComponent(part) + } catch { + return part + } + }) +} + +function googleDriveLink(url: URL): DocumentLink | undefined { + const parts = pathSegments(url) + if (url.hostname === 'docs.google.com') { + const kind = GOOGLE_EDITOR_KINDS[parts[0] ?? ''] + /** `/u/1/d/ID` selects a signed-in Google account; `/d/e/ID` is a published copy, not the file. */ + const rest = parts[1] === 'u' ? parts.slice(3) : parts.slice(1) + const id = rest[0] === 'd' ? rest[1] : undefined + if (!kind || !id || !DRIVE_ID.test(id)) return undefined + return { provider: 'google_drive', reference: { id, kind } } + } + const id = parts[0] === 'file' && parts[1] === 'd' ? parts[2] : url.searchParams.get('id') + if (!id || !DRIVE_ID.test(id) || !['file', 'open', 'uc'].includes(parts[0] ?? '')) + return undefined + return { provider: 'google_drive', reference: { id } } +} + +/** A message ID in the fragment, as Sim's own Gmail links and classic Gmail URLs carry it. */ +function gmailLink(url: URL): DocumentLink | undefined { + const id = url.hash.split('/').at(-1)?.toLowerCase() + if (!url.pathname.startsWith('/mail/') || !id || !/^[\da-f]{16}$/.test(id)) return undefined + return { provider: 'gmail', reference: { id } } +} + +/** `eid` is base64 of the event ID and its calendar's ID; `@m` abbreviates `@gmail.com`. */ +function calendarLink(url: URL): DocumentLink | undefined { + const eid = url.searchParams.get('eid') + if (!eid || !/^[\w-]+={0,2}$/.test(eid)) return undefined + const [id, calendar, ...extra] = Buffer.from(eid, 'base64url').toString('utf8').split(' ') + if (!id || !calendar || extra.length || !/^[\w-]+$/.test(id) || !calendar.includes('@')) + return undefined + const container = calendar.endsWith('@m') ? `${calendar.slice(0, -2)}@gmail.com` : calendar + return { provider: 'google_calendar', reference: { id, container } } +} + +/** Message permalinks carry the timestamp without its dot; files and canvases carry the file ID. */ +function slackLink(url: URL): DocumentLink | undefined { + const parts = pathSegments(url) + if (parts[0] === 'archives' && parts.length === 3) { + const [, channel, message] = parts + const digits = /^p(\d{16})$/.exec(message ?? '')?.[1] + if (!channel || !/^[A-Z\d]+$/.test(channel) || !digits) return undefined + const threadId = url.searchParams.get('thread_ts') ?? undefined + return { + provider: 'slack', + reference: { + id: `${digits.slice(0, 10)}.${digits.slice(10)}`, + container: channel, + ...(threadId && /^\d+\.\d+$/.test(threadId) ? { threadId } : {}), + }, + } + } + const file = parts[0] === 'files' || parts[0] === 'docs' ? parts[2] : undefined + if (!file || !/^F[A-Z\d]+$/.test(file)) return undefined + return { provider: 'slack', reference: { id: file, kind: 'file' } } +} + +/** + * The path of a file link on `branch`, or undefined when the link names another branch or commit. + * Reads and their source checks cover the default branch only, as search does. + */ +function pathOnBranch(blob: string[], branch: string): string | undefined { + const branchParts = branch.split('/') + const path = blob.slice(branchParts.length) + if ( + !branch || + !path.length || + branchParts.some((part, index) => blob[index] !== part) || + path.some((part) => part === '.' || part === '..') + ) + return undefined + return path.join('/') +} + +function githubRepository(owner: string, name: string): string | undefined { + try { + const { owner: parsedOwner, repo } = parseGitHubRepository(`${owner}/${name}`) + return `${parsedOwner}/${repo}` + } catch { + return undefined + } +} + +function githubLink(url: URL): DocumentLink | undefined { + const [owner, name, section, ...rest] = pathSegments(url) + if (!owner || !name || GITHUB_RESERVED_OWNERS.has(owner.toLowerCase())) return undefined + const repository = githubRepository(owner, name) + if (!repository) return undefined + const link = (reference: LinkedReference): DocumentLink => ({ + provider: 'github', + reference: { container: repository, ...reference }, + }) + if (!section) return link({ id: repository, kind: 'repositories' }) + if ((section === 'issues' || section === 'pull') && NUMERIC_ID.test(rest[0] ?? '')) { + const commit = section === 'pull' && rest[1] === 'commits' ? rest[2] : undefined + return commit ? githubCommit(commit, link) : link({ id: rest[0] ?? '', kind: 'issues' }) + } + if (section === 'commit') return githubCommit(rest[0], link) + if (section === 'blob') return { provider: 'github', repository, blob: rest } + return undefined +} + +function githubCommit( + sha: string | undefined, + link: (reference: LinkedReference) => DocumentLink +): DocumentLink | undefined { + return sha && /^[\da-f]{7,40}$/i.test(sha) ? link({ id: sha, kind: 'commits' }) : undefined +} + +/** GitLab separates a project's path from its pages with `/-/`, on gitlab.com and self-hosted. */ +function gitlabLink(url: URL): DocumentLink | undefined { + const parts = pathSegments(url) + const separator = parts.indexOf('-') + if (separator < 1 || parts.slice(0, separator).some((part) => part === '.' || part === '..')) + return undefined + const project = parts.slice(0, separator).join('/') + const [section, ...rest] = parts.slice(separator + 1) + const link = (reference: LinkedReference): DocumentLink => ({ + provider: 'gitlab', + host: url.host, + reference: { container: project, ...reference }, + }) + const iid = rest[0] + if (section === 'issues' || section === 'merge_requests') + return iid && NUMERIC_ID.test(iid) + ? link({ id: iid, kind: section === 'merge_requests' ? 'merge_requests' : 'issues' }) + : undefined + if (section === 'blob') + return { provider: 'gitlab', host: url.host, repository: project, blob: rest } + if (section === 'wikis' && rest.length) return link({ id: rest.join('/'), kind: 'wiki' }) + return undefined +} + +function jiraLink(url: URL): DocumentLink | undefined { + const parts = pathSegments(url) + const key = parts[0] === 'browse' ? parts[1] : url.searchParams.get('selectedIssue') + if (!key || !JIRA_KEY.test(key)) return undefined + return { provider: 'jira', host: url.host, reference: { id: key } } +} + +function confluenceLink(url: URL): DocumentLink | undefined { + const parts = pathSegments(url) + if (parts[0] !== 'wiki') return undefined + const link = (reference: LinkedReference): DocumentLink => ({ + provider: 'confluence', + host: url.host, + reference, + }) + if (parts[1] === 'pages' && parts[2] === 'viewpage.action') { + const id = url.searchParams.get('pageId') + return id && NUMERIC_ID.test(id) ? link({ id, kind: 'page' }) : undefined + } + if (parts[1] !== 'spaces' || !parts[2]) return undefined + const [section, ...rest] = parts.slice(3) + if (section === 'pages') { + const id = rest[0] === 'edit-v2' ? rest[1] : rest[0] + return id && NUMERIC_ID.test(id) ? link({ id, kind: 'page' }) : undefined + } + if (section === 'blog') { + /** Blog post paths put the publication date (`2026/01/31`) before the post ID. */ + const dated = /^\d{4}$/.test(rest[0] ?? '') && /^\d{2}$/.test(rest[1] ?? '') + const id = dated ? rest[3] : rest[0] + return id && NUMERIC_ID.test(id) ? link({ id, kind: 'blogpost' }) : undefined + } + if (section === undefined || section === 'overview') return link({ id: parts[2], kind: 'space' }) + return undefined +} + +function linearLink(url: URL): DocumentLink | undefined { + const [workspace, section, issueKey] = pathSegments(url) + if (!workspace || section !== 'issue' || !issueKey || !JIRA_KEY.test(issueKey.toUpperCase())) + return undefined + return { + provider: 'linear', + workspace: workspace.toLowerCase(), + issueKey: issueKey.toUpperCase(), + } +} + +/** Fireflies' own links end in the meeting ID, after its title and `::` when it has one. */ +function firefliesLink(url: URL): DocumentLink | undefined { + const [section, slug, ...rest] = pathSegments(url) + const id = slug?.split('::').at(-1) + if (section !== 'view' || rest.length || !id || !/^[\w-]{1,200}$/.test(id)) return undefined + return { provider: 'fireflies', reference: { id, kind: 'meeting' } } +} + +function notionLink(value: string): DocumentLink | undefined { + const resource = notionResource(value) + return resource && { provider: 'notion', reference: { id: resource.id, kind: 'mcp' } } +} + +/** Parsers for hosts that serve one provider's documents. */ +const HOST_PARSERS = new Map DocumentLink | undefined>([ + ['docs.google.com', googleDriveLink], + ['drive.google.com', googleDriveLink], + ['mail.google.com', gmailLink], + ['calendar.google.com', calendarLink], + ['www.google.com', calendarLink], + ['github.com', githubLink], + ['www.github.com', githubLink], + ['linear.app', linearLink], + ['app.fireflies.ai', firefliesLink], +]) + +/** + * The provider documents a pasted link may name, or undefined when `value` is not a web link. + * An empty list means the link names nothing Sim can read directly, such as a folder, channel or + * site page. Hosts that can be self-hosted or custom (Atlassian, GitLab) are recognized by path, + * so a link can name candidates of more than one provider; each is matched against the reader's + * own accounts. + */ +export function parseDocumentLinks(value: string): DocumentLink[] | undefined { + if (!/^https?:\/\//i.test(value)) return undefined + let url: URL + try { + url = new URL(value) + } catch { + return [] + } + if (url.protocol !== 'https:' || url.username || url.password) return [] + const parse = + HOST_PARSERS.get(url.hostname) ?? (url.hostname.endsWith('.slack.com') ? slackLink : undefined) + if (parse) return [parse(url)].filter((link) => link !== undefined) + const notion = notionLink(value) + if (notion) return [notion] + return [jiraLink(url), confluenceLink(url), gitlabLink(url)].filter((link) => link !== undefined) +} + +/** + * The location within one account that `link` names, finishing what the link alone cannot say + * with the account's provider client, or undefined when the account cannot hold it: another + * Atlassian site, GitLab host, or Linear workspace. + */ +export async function locateDocumentLink( + link: DocumentLink, + account: { client: NativeClient | null; origin: string } +): Promise { + if ('blob' in link) return locateFile(link, account) + switch (link.provider) { + case 'jira': + case 'confluence': { + if (!account.client) return undefined + const container = await atlassianSiteId(account.client, link.host) + return container ? { ...link.reference, container } : undefined + } + case 'gitlab': + return new URL(account.origin).host === link.host ? link.reference : undefined + case 'linear': + return account.client + ? linearIssueReference(account.client, link.workspace, link.issueKey) + : undefined + default: + return link.reference + } +} + +/** A file link's path on the repository's default branch, read from the account's own API. */ +async function locateFile( + link: Extract, + account: { client: NativeClient | null; origin: string } +): Promise { + if (!account.client) return undefined + if (link.provider === 'gitlab' && new URL(account.origin).host !== link.host) return undefined + const row = object( + await account.client.json( + link.provider === 'github' + ? `/repos/${link.repository}` + : `/api/v4/projects/${encodeGitLabResourceId(link.repository)}`, + { memo: true } + ) + ) + const branch = string(row.default_branch) + const path = pathOnBranch(link.blob, branch) + if (!path) + throw new NativeSearchError( + 'unavailable', + `Sim reads repository files on the default branch (${branch || 'unknown'}), and this link names another branch or commit. Open the file on the default branch, or search for it.` + ) + return { + id: path, + container: + link.provider === 'github' + ? string(row.full_name) || link.repository + : string(row.id) || link.repository, + kind: 'code', + /** GitLab sources pin their branch, and file IDs from a GitLab search name it. */ + ...(link.provider === 'gitlab' ? { revision: branch } : {}), + } +} diff --git a/apps/sim/lib/sim-search/live/notion-mcp.ts b/apps/sim/lib/sim-search/live/notion-mcp.ts index b9d095267bf..dd0ad5ca05b 100644 --- a/apps/sim/lib/sim-search/live/notion-mcp.ts +++ b/apps/sim/lib/sim-search/live/notion-mcp.ts @@ -18,7 +18,7 @@ function pageId(value: string): string | undefined { return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`.toLowerCase() } -function notionResource(value: string): { id: string; url: string } | undefined { +export function notionResource(value: string): { id: string; url: string } | undefined { const id = pageId(value) if (id) return { id, url: `https://www.notion.so/${id.replaceAll('-', '')}` } try {