From 37332c24b3eb537c8dabb7626c7e51a8db635c6d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 11:17:16 -0800 Subject: [PATCH 1/9] feat(search-mcp): read_document reads pasted source links --- apps/sim/lib/api/contracts/knowledge/mcp.ts | 11 +- apps/sim/lib/knowledge/mcp/server.ts | 2 +- apps/sim/lib/knowledge/search/diagnostics.ts | 2 + .../lib/sim-search/live/account-session.ts | 12 + .../lib/sim-search/live/application.test.ts | 110 +++++++ apps/sim/lib/sim-search/live/application.ts | 278 ++++++++++++---- apps/sim/lib/sim-search/live/atlassian.ts | 15 + apps/sim/lib/sim-search/live/github.ts | 8 +- apps/sim/lib/sim-search/live/linear.ts | 27 ++ apps/sim/lib/sim-search/live/links.test.ts | 223 +++++++++++++ apps/sim/lib/sim-search/live/links.ts | 310 ++++++++++++++++++ apps/sim/lib/sim-search/live/notion-mcp.ts | 2 +- apps/sim/lib/sim-search/live/providers.ts | 2 +- 13 files changed, 928 insertions(+), 74 deletions(-) create mode 100644 apps/sim/lib/sim-search/live/links.test.ts create mode 100644 apps/sim/lib/sim-search/live/links.ts diff --git a/apps/sim/lib/api/contracts/knowledge/mcp.ts b/apps/sim/lib/api/contracts/knowledge/mcp.ts index b5d6571bbb7..85b86f28a2c 100644 --- a/apps/sim/lib/api/contracts/knowledge/mcp.ts +++ b/apps/sim/lib/api/contracts/knowledge/mcp.ts @@ -75,19 +75,24 @@ 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..20cff46998e 100644 --- a/apps/sim/lib/sim-search/live/application.test.ts +++ b/apps/sim/lib/sim-search/live/application.test.ts @@ -1311,6 +1311,116 @@ 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 link from the account holding it and names it by an ID that reads back', async () => { + const result = await read('https://docs.google.com/document/d/1AbcDEFghijKLmn/edit') + expect(mocks.read).toHaveBeenCalledWith( + 'google_drive', + expect.anything(), + { id: '1AbcDEFghijKLmn', kind: 'application/vnd.google-apps.document' }, + 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' }]) + 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 the reason an account gave over another account not holding the link', 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.mockRejectedValue( + 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..76617555f22 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,199 @@ function liveReadFailure(error: unknown, provider: string, deadline?: AbortSigna return error } +type LocatedReference = Awaited> + +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): Promise +} + +/** + * 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 { resolved, 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', () => listLiveAccounts(input, userId)), + measureSearchStage('live.policies', () => loadLiveSearchPolicies(input)), + ]) + const candidates = accounts + .filter( + (account) => + providers.has(account.provider) && + (!input.filters?.source || input.filters.source === account.provider) + ) + .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 + const reference = { account: account.id, provider: account.provider, ...read.reference } + return { + documentId: encodeLiveReference(reference, owner), + reference, + resolved: { 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', + `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 +1280,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, resolved, 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,7 +1310,7 @@ const liveDocumentRead = defineAuthorizedKnowledgeUseCase({ hasMore: end < content.length, }) return { - documentId: input.documentId, + documentId, knowledgeBaseId: '', knowledgeBaseName: resolved.account.displayName, documentName: safeContent(document.title, input.resultSecretRegistry), diff --git a/apps/sim/lib/sim-search/live/atlassian.ts b/apps/sim/lib/sim-search/live/atlassian.ts index aae29c76799..a69b778fdf1 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.toLowerCase() + } 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/github.ts b/apps/sim/lib/sim-search/live/github.ts index 92efd385e48..003f83b755a 100644 --- a/apps/sim/lib/sim-search/live/github.ts +++ b/apps/sim/lib/sim-search/live/github.ts @@ -368,7 +368,8 @@ export async function readGitHub( client: NativeClient, id: string, repository?: string, - kind?: string + kind?: string, + revision?: string ): Promise { if ( !repository || @@ -381,7 +382,9 @@ export async function readGitHub( if (id.split('/').some((part) => part === '..' || part === '.')) throw new NativeSearchError('unavailable', 'Invalid file path.') const row = object( - await client.json(`${path}/contents/${id.split('/').map(segment).join('/')}`) + await client.json(`${path}/contents/${id.split('/').map(segment).join('/')}`, { + ...(revision ? { query: { ref: revision } } : {}), + }) ) if (row.encoding !== 'base64') throw new NativeSearchError( @@ -392,6 +395,7 @@ export async function readGitHub( id, container: repository, kind, + ...(revision ? { revision } : {}), title: string(row.name), url: string(row.html_url), content: Buffer.from(string(row.content), 'base64').toString('utf8'), 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..26667c18b99 --- /dev/null +++ b/apps/sim/lib/sim-search/live/links.test.ts @@ -0,0 +1,223 @@ +/** + * @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 on a branch', + 'https://github.com/acme/api/blob/release/src/index.ts#L10', + { + provider: 'github', + reference: { container: 'acme/api', id: 'src/index.ts', kind: 'code', revision: 'release' }, + }, + ], + [ + '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 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('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..3a48f891167 --- /dev/null +++ b/apps/sim/lib/sim-search/live/links.ts @@ -0,0 +1,310 @@ +import { atlassianSiteId } from '@/lib/sim-search/live/atlassian' +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' + +/** 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, and Linear links name an issue by its key rather than its UUID, 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 } + +/** 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+$/ +const GITHUB_NAME = /^[\w.-]+$/ +/** First path segments on github.com that are site pages, not repository owners. */ +const GITHUB_RESERVED_OWNERS = new Set([ + 'apps', + 'collections', + 'enterprises', + 'features', + 'login', + 'marketplace', + 'notifications', + 'orgs', + '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[2] : parts[0] === 'docs' ? parts[2] : undefined + if (!file || !/^F[A-Z\d]+$/.test(file)) return undefined + return { provider: 'slack', reference: { id: file, kind: 'file' } } +} + +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 = `${owner}/${name.replace(/\.git$/, '')}` + if (!GITHUB_NAME.test(owner) || !GITHUB_NAME.test(repository.split('/')[1] ?? '')) + 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' && rest.length >= 2) { + const [revision, ...path] = rest + if (!revision || path.some((part) => part === '.' || part === '..')) return undefined + return link({ id: path.join('/'), kind: 'code', revision }) + } + 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) 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 }, + }) + if (section === 'issues' || section === 'work_items') + return NUMERIC_ID.test(rest[0] ?? '') ? link({ id: rest[0] ?? '', kind: 'issues' }) : undefined + if (section === 'merge_requests') + return NUMERIC_ID.test(rest[0] ?? '') + ? link({ id: rest[0] ?? '', kind: 'merge_requests' }) + : undefined + if (section === 'blob' && rest.length >= 2) { + const [revision, ...path] = rest + if (!revision || path.some((part) => part === '.' || part === '..')) return undefined + return link({ id: path.join('/'), kind: 'code', revision }) + } + 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' } } +} + +/** + * 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 host = url.hostname.toLowerCase() + if (host === 'docs.google.com' || host === 'drive.google.com') + return [googleDriveLink(url)].filter((link) => link !== undefined) + if (host === 'mail.google.com') return [gmailLink(url)].filter((link) => link !== undefined) + if (host === 'calendar.google.com' || host === 'www.google.com') + return [calendarLink(url)].filter((link) => link !== undefined) + if (host.endsWith('.slack.com')) return [slackLink(url)].filter((link) => link !== undefined) + if (host === 'github.com' || host === 'www.github.com') + return [githubLink(url)].filter((link) => link !== undefined) + if (host === 'linear.app') return [linearLink(url)].filter((link) => link !== undefined) + if (host === 'app.fireflies.ai') return [firefliesLink(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 { + 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 + } +} 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 { diff --git a/apps/sim/lib/sim-search/live/providers.ts b/apps/sim/lib/sim-search/live/providers.ts index bdbb14c1b41..8d17c3ab8e9 100644 --- a/apps/sim/lib/sim-search/live/providers.ts +++ b/apps/sim/lib/sim-search/live/providers.ts @@ -229,7 +229,7 @@ export const LIVE_SEARCH_PROVIDERS = { }, search: searchGitHub, read: (client, reference) => - readGitHub(client, reference.id, reference.container, reference.kind), + readGitHub(client, reference.id, reference.container, reference.kind, reference.revision), }, jama: { guide: { From ab85e488c5217ab39a7436eb7c70fddb2465083e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 11:24:53 -0800 Subject: [PATCH 2/9] improvement(search-mcp): simplify link parsing and reuse the GitHub repository parser --- apps/sim/lib/sim-search/live/application.ts | 12 ++-- apps/sim/lib/sim-search/live/atlassian.ts | 2 +- apps/sim/lib/sim-search/live/links.ts | 76 +++++++++++++-------- 3 files changed, 53 insertions(+), 37 deletions(-) diff --git a/apps/sim/lib/sim-search/live/application.ts b/apps/sim/lib/sim-search/live/application.ts index 76617555f22..74f181b4550 100644 --- a/apps/sim/lib/sim-search/live/application.ts +++ b/apps/sim/lib/sim-search/live/application.ts @@ -1072,8 +1072,6 @@ function liveReadFailure(error: unknown, provider: string, deadline?: AbortSigna return error } -type LocatedReference = Awaited> - interface AccountReadInput { owner: ResourceOwner userId: string @@ -1082,7 +1080,7 @@ interface AccountReadInput { signal: AbortSignal filters?: WorkspaceSearchFilters /** The reference to read within the account's session, or undefined when it holds none. */ - locate(session: LiveAccountSession): Promise + locate(session: LiveAccountSession): ReturnType } /** @@ -1169,7 +1167,7 @@ async function readReferencedDocument( locate: async () => reference, }) if (!read) throw new OrchestrationError('not_found', 'Document not found') - return { resolved, document: read.document } + 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) @@ -1241,7 +1239,7 @@ async function readLinkedDocument( return { documentId: encodeLiveReference(reference, owner), reference, - resolved: { account }, + account, document: read.document, } } catch (error) { @@ -1290,7 +1288,7 @@ const liveDocumentRead = defineAuthorizedKnowledgeUseCase({ `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, resolved, document } = 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)) @@ -1312,7 +1310,7 @@ const liveDocumentRead = defineAuthorizedKnowledgeUseCase({ return { 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 a69b778fdf1..a8993f19cb9 100644 --- a/apps/sim/lib/sim-search/live/atlassian.ts +++ b/apps/sim/lib/sim-search/live/atlassian.ts @@ -123,7 +123,7 @@ export async function atlassianSiteId( ): Promise { const site = (await sites(client)).find((row) => { try { - return new URL(string(row.url)).host === host.toLowerCase() + return new URL(string(row.url)).host === host } catch { return false } diff --git a/apps/sim/lib/sim-search/live/links.ts b/apps/sim/lib/sim-search/live/links.ts index 3a48f891167..62a55435dc4 100644 --- a/apps/sim/lib/sim-search/live/links.ts +++ b/apps/sim/lib/sim-search/live/links.ts @@ -1,3 +1,4 @@ +import { parseGitHubRepository } from '@/lib/oauth/github-repository' import { atlassianSiteId } from '@/lib/sim-search/live/atlassian' import { linearIssueReference } from '@/lib/sim-search/live/linear' import { notionResource } from '@/lib/sim-search/live/notion-mcp' @@ -46,7 +47,6 @@ const GOOGLE_EDITOR_KINDS: Record = { } const JIRA_KEY = /^[A-Z][A-Z\d_]*-\d+$/ const NUMERIC_ID = /^\d+$/ -const GITHUB_NAME = /^[\w.-]+$/ /** First path segments on github.com that are site pages, not repository owners. */ const GITHUB_RESERVED_OWNERS = new Set([ 'apps', @@ -128,17 +128,33 @@ function slackLink(url: URL): DocumentLink | undefined { }, } } - const file = parts[0] === 'files' ? parts[2] : parts[0] === 'docs' ? parts[2] : undefined + 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' } } } +/** A repository file at a revision: the first segment after `blob` names it, the rest the path. */ +function blobReference(rest: string[]): LinkedReference | undefined { + const [revision, ...path] = rest + if (!revision || !path.length || path.some((part) => part === '.' || part === '..')) + return undefined + return { id: path.join('/'), kind: 'code', revision } +} + +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 = `${owner}/${name.replace(/\.git$/, '')}` - if (!GITHUB_NAME.test(owner) || !GITHUB_NAME.test(repository.split('/')[1] ?? '')) - return undefined + const repository = githubRepository(owner, name) + if (!repository) return undefined const link = (reference: LinkedReference): DocumentLink => ({ provider: 'github', reference: { container: repository, ...reference }, @@ -149,10 +165,9 @@ function githubLink(url: URL): DocumentLink | undefined { return commit ? githubCommit(commit, link) : link({ id: rest[0] ?? '', kind: 'issues' }) } if (section === 'commit') return githubCommit(rest[0], link) - if (section === 'blob' && rest.length >= 2) { - const [revision, ...path] = rest - if (!revision || path.some((part) => part === '.' || part === '..')) return undefined - return link({ id: path.join('/'), kind: 'code', revision }) + if (section === 'blob') { + const blob = blobReference(rest) + return blob && link(blob) } return undefined } @@ -176,16 +191,14 @@ function gitlabLink(url: URL): DocumentLink | undefined { host: url.host, reference: { container: project, ...reference }, }) - if (section === 'issues' || section === 'work_items') - return NUMERIC_ID.test(rest[0] ?? '') ? link({ id: rest[0] ?? '', kind: 'issues' }) : undefined - if (section === 'merge_requests') - return NUMERIC_ID.test(rest[0] ?? '') - ? link({ id: rest[0] ?? '', kind: 'merge_requests' }) + const iid = rest[0] + if (section === 'issues' || section === 'work_items' || section === 'merge_requests') + return iid && NUMERIC_ID.test(iid) + ? link({ id: iid, kind: section === 'merge_requests' ? 'merge_requests' : 'issues' }) : undefined - if (section === 'blob' && rest.length >= 2) { - const [revision, ...path] = rest - if (!revision || path.some((part) => part === '.' || part === '..')) return undefined - return link({ id: path.join('/'), kind: 'code', revision }) + if (section === 'blob') { + const blob = blobReference(rest) + return blob && link(blob) } if (section === 'wikis' && rest.length) return link({ id: rest.join('/'), kind: 'wiki' }) return undefined @@ -250,6 +263,19 @@ function notionLink(value: string): DocumentLink | undefined { 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 @@ -266,17 +292,9 @@ export function parseDocumentLinks(value: string): DocumentLink[] | undefined { return [] } if (url.protocol !== 'https:' || url.username || url.password) return [] - const host = url.hostname.toLowerCase() - if (host === 'docs.google.com' || host === 'drive.google.com') - return [googleDriveLink(url)].filter((link) => link !== undefined) - if (host === 'mail.google.com') return [gmailLink(url)].filter((link) => link !== undefined) - if (host === 'calendar.google.com' || host === 'www.google.com') - return [calendarLink(url)].filter((link) => link !== undefined) - if (host.endsWith('.slack.com')) return [slackLink(url)].filter((link) => link !== undefined) - if (host === 'github.com' || host === 'www.github.com') - return [githubLink(url)].filter((link) => link !== undefined) - if (host === 'linear.app') return [linearLink(url)].filter((link) => link !== undefined) - if (host === 'app.fireflies.ai') return [firefliesLink(url)].filter((link) => link !== undefined) + 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) From 60cac82e7b2d1bcc16ee9ab3593c9815592be57c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 11:26:14 -0800 Subject: [PATCH 3/9] improvement(search-mcp): tighten link read tests and comments --- apps/sim/lib/api/contracts/knowledge/mcp.ts | 1 - apps/sim/lib/sim-search/live/application.test.ts | 14 +++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/apps/sim/lib/api/contracts/knowledge/mcp.ts b/apps/sim/lib/api/contracts/knowledge/mcp.ts index 85b86f28a2c..b2b2cf25e75 100644 --- a/apps/sim/lib/api/contracts/knowledge/mcp.ts +++ b/apps/sim/lib/api/contracts/knowledge/mcp.ts @@ -75,7 +75,6 @@ export function liveSearchMcpDefaultTopK(input: z.output { displayName: id, }) - it('reads a link from the account holding it and names it by an ID that reads back', async () => { + it('reads a Google Doc link and names it by an ID that reads back', async () => { const result = await read('https://docs.google.com/document/d/1AbcDEFghijKLmn/edit') expect(mocks.read).toHaveBeenCalledWith( 'google_drive', @@ -1393,14 +1393,14 @@ describe('authorized live retrieval', () => { ) }) - it('reports the reason an account gave over another account not holding the link', async () => { - mocks.accounts.mockResolvedValue([confluence('site-a'), confluence('site-b')]) + 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-b', url: 'https://b.atlassian.net' }]) - mocks.read.mockRejectedValue( - new NativeSearchError('reconnect', 'The provider denied access.') - ) + .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'), From 16859ae9aedf0f5340617586b891a615cf45fb66 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 11:33:26 -0800 Subject: [PATCH 4/9] fix(search-mcp): resolve file links on the default branch and mint reader-confirmed IDs --- .../lib/sim-search/live/application.test.ts | 12 ++- apps/sim/lib/sim-search/live/application.ts | 13 ++- apps/sim/lib/sim-search/live/github.ts | 8 +- apps/sim/lib/sim-search/live/links.test.ts | 21 ++++- apps/sim/lib/sim-search/live/links.ts | 82 ++++++++++++++----- apps/sim/lib/sim-search/live/providers.ts | 2 +- 6 files changed, 104 insertions(+), 34 deletions(-) diff --git a/apps/sim/lib/sim-search/live/application.test.ts b/apps/sim/lib/sim-search/live/application.test.ts index bc23bb2c0ed..4066255b111 100644 --- a/apps/sim/lib/sim-search/live/application.test.ts +++ b/apps/sim/lib/sim-search/live/application.test.ts @@ -1334,12 +1334,17 @@ describe('authorized live retrieval', () => { displayName: id, }) - it('reads a Google Doc link and names it by an ID that reads back', async () => { - const result = await read('https://docs.google.com/document/d/1AbcDEFghijKLmn/edit') + 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', kind: 'application/vnd.google-apps.document' }, + { id: '1AbcDEFghijKLmn' }, expect.anything() ) expect(decodeLiveReference(result.documentId)).toEqual({ @@ -1371,6 +1376,7 @@ describe('authorized live retrieval', () => { 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( diff --git a/apps/sim/lib/sim-search/live/application.ts b/apps/sim/lib/sim-search/live/application.ts index 74f181b4550..d436c7d9a1c 100644 --- a/apps/sim/lib/sim-search/live/application.ts +++ b/apps/sim/lib/sim-search/live/application.ts @@ -1201,7 +1201,7 @@ async function readLinkedDocument( const candidates = accounts .filter( (account) => - providers.has(account.provider) && + links.some((link) => link.provider === account.provider) && (!input.filters?.source || input.filters.source === account.provider) ) .slice(0, MAX_LINK_ACCOUNTS) @@ -1235,7 +1235,16 @@ async function readLinkedDocument( }) ) if (!read) continue - const reference = { account: account.id, provider: account.provider, ...read.reference } + /** 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, diff --git a/apps/sim/lib/sim-search/live/github.ts b/apps/sim/lib/sim-search/live/github.ts index 003f83b755a..92efd385e48 100644 --- a/apps/sim/lib/sim-search/live/github.ts +++ b/apps/sim/lib/sim-search/live/github.ts @@ -368,8 +368,7 @@ export async function readGitHub( client: NativeClient, id: string, repository?: string, - kind?: string, - revision?: string + kind?: string ): Promise { if ( !repository || @@ -382,9 +381,7 @@ export async function readGitHub( if (id.split('/').some((part) => part === '..' || part === '.')) throw new NativeSearchError('unavailable', 'Invalid file path.') const row = object( - await client.json(`${path}/contents/${id.split('/').map(segment).join('/')}`, { - ...(revision ? { query: { ref: revision } } : {}), - }) + await client.json(`${path}/contents/${id.split('/').map(segment).join('/')}`) ) if (row.encoding !== 'base64') throw new NativeSearchError( @@ -395,7 +392,6 @@ export async function readGitHub( id, container: repository, kind, - ...(revision ? { revision } : {}), title: string(row.name), url: string(row.html_url), content: Buffer.from(string(row.content), 'base64').toString('utf8'), diff --git a/apps/sim/lib/sim-search/live/links.test.ts b/apps/sim/lib/sim-search/live/links.test.ts index 26667c18b99..8dc8eca9166 100644 --- a/apps/sim/lib/sim-search/live/links.test.ts +++ b/apps/sim/lib/sim-search/live/links.test.ts @@ -61,11 +61,12 @@ describe('parseDocumentLinks', () => { { provider: 'github', reference: { container: 'acme/api', id: 'abc1234', kind: 'commits' } }, ], [ - 'a file on a branch', - 'https://github.com/acme/api/blob/release/src/index.ts#L10', + 'a file, whose branch and path the repository tells apart', + 'https://github.com/acme/api/blob/release/2026/src/index.ts#L10', { provider: 'github', - reference: { container: 'acme/api', id: 'src/index.ts', kind: 'code', revision: 'release' }, + repository: 'acme/api', + blob: ['release', '2026', 'src', 'index.ts'], }, ], [ @@ -196,6 +197,20 @@ describe('locateDocumentLink', () => { ).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('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') diff --git a/apps/sim/lib/sim-search/live/links.ts b/apps/sim/lib/sim-search/live/links.ts index 62a55435dc4..55aa163886d 100644 --- a/apps/sim/lib/sim-search/live/links.ts +++ b/apps/sim/lib/sim-search/live/links.ts @@ -1,20 +1,19 @@ import { parseGitHubRepository } from '@/lib/oauth/github-repository' import { atlassianSiteId } from '@/lib/sim-search/live/atlassian' +import { NativeSearchError, object, segment, 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' /** 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' -> +export type LinkedReference = Pick /** * 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, and Linear links name an issue by its key rather than its UUID, so - * those finish against the account that reads them. + * 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 = | { @@ -34,6 +33,14 @@ export type DocumentLink = 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 = @@ -133,12 +140,21 @@ function slackLink(url: URL): DocumentLink | undefined { return { provider: 'slack', reference: { id: file, kind: 'file' } } } -/** A repository file at a revision: the first segment after `blob` names it, the rest the path. */ -function blobReference(rest: string[]): LinkedReference | undefined { - const [revision, ...path] = rest - if (!revision || !path.length || path.some((part) => part === '.' || part === '..')) +/** + * 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 { id: path.join('/'), kind: 'code', revision } + return path.join('/') } function githubRepository(owner: string, name: string): string | undefined { @@ -165,10 +181,7 @@ function githubLink(url: URL): DocumentLink | undefined { return commit ? githubCommit(commit, link) : link({ id: rest[0] ?? '', kind: 'issues' }) } if (section === 'commit') return githubCommit(rest[0], link) - if (section === 'blob') { - const blob = blobReference(rest) - return blob && link(blob) - } + if (section === 'blob') return { provider: 'github', repository, blob: rest } return undefined } @@ -196,10 +209,8 @@ function gitlabLink(url: URL): DocumentLink | undefined { return iid && NUMERIC_ID.test(iid) ? link({ id: iid, kind: section === 'merge_requests' ? 'merge_requests' : 'issues' }) : undefined - if (section === 'blob') { - const blob = blobReference(rest) - return blob && link(blob) - } + 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 } @@ -309,6 +320,7 @@ 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': { @@ -326,3 +338,35 @@ export async function locateDocumentLink( 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/${segment(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.path_with_namespace) || link.repository, + kind: 'code', + } +} diff --git a/apps/sim/lib/sim-search/live/providers.ts b/apps/sim/lib/sim-search/live/providers.ts index 8d17c3ab8e9..bdbb14c1b41 100644 --- a/apps/sim/lib/sim-search/live/providers.ts +++ b/apps/sim/lib/sim-search/live/providers.ts @@ -229,7 +229,7 @@ export const LIVE_SEARCH_PROVIDERS = { }, search: searchGitHub, read: (client, reference) => - readGitHub(client, reference.id, reference.container, reference.kind, reference.revision), + readGitHub(client, reference.id, reference.container, reference.kind), }, jama: { guide: { From e03de85350813c7bbe96b1d8ab63c52720f41054 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 11:58:36 -0800 Subject: [PATCH 5/9] fix(search-mcp): pin GitLab file links to their branch and bound link setup by the read deadline --- apps/sim/lib/sim-search/live/application.ts | 9 +++++++-- apps/sim/lib/sim-search/live/links.ts | 9 +++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/apps/sim/lib/sim-search/live/application.ts b/apps/sim/lib/sim-search/live/application.ts index d436c7d9a1c..79b44f551f8 100644 --- a/apps/sim/lib/sim-search/live/application.ts +++ b/apps/sim/lib/sim-search/live/application.ts @@ -1195,9 +1195,14 @@ async function readLinkedDocument( 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', () => listLiveAccounts(input, userId)), + 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 candidates = accounts .filter( (account) => diff --git a/apps/sim/lib/sim-search/live/links.ts b/apps/sim/lib/sim-search/live/links.ts index 55aa163886d..3ed0c2172c0 100644 --- a/apps/sim/lib/sim-search/live/links.ts +++ b/apps/sim/lib/sim-search/live/links.ts @@ -6,7 +6,10 @@ import { notionResource } from '@/lib/sim-search/live/notion-mcp' import type { NativeClient, NativeDocument } from '@/lib/sim-search/live/types' /** The location fields a live document ID carries, as each provider's reader expects them. */ -export type LinkedReference = Pick +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 @@ -205,7 +208,7 @@ function gitlabLink(url: URL): DocumentLink | undefined { reference: { container: project, ...reference }, }) const iid = rest[0] - if (section === 'issues' || section === 'work_items' || section === 'merge_requests') + if (section === 'issues' || section === 'merge_requests') return iid && NUMERIC_ID.test(iid) ? link({ id: iid, kind: section === 'merge_requests' ? 'merge_requests' : 'issues' }) : undefined @@ -368,5 +371,7 @@ async function locateFile( ? string(row.full_name) || link.repository : string(row.path_with_namespace) || link.repository, kind: 'code', + /** GitLab sources pin their branch, and file IDs from a GitLab search name it. */ + ...(link.provider === 'gitlab' ? { revision: branch } : {}), } } From e83e69ac7a26e39d4952682848489323f2b2f2a0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 11:58:50 -0800 Subject: [PATCH 6/9] test(search-mcp): cover the GitLab file link branch --- apps/sim/lib/sim-search/live/links.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/apps/sim/lib/sim-search/live/links.test.ts b/apps/sim/lib/sim-search/live/links.test.ts index 8dc8eca9166..5cfde651aa6 100644 --- a/apps/sim/lib/sim-search/live/links.test.ts +++ b/apps/sim/lib/sim-search/live/links.test.ts @@ -211,6 +211,17 @@ describe('locateDocumentLink', () => { ) }) + 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({ path_with_namespace: 'team/api', default_branch: 'main' }), + origin: 'https://git.acme.dev', + }) + ).resolves.toEqual({ id: 'src/a.ts', container: 'team/api', 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') From d4ef6f54d79ba465093745773080752cbb988db8 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 12:05:35 -0800 Subject: [PATCH 7/9] fix(search-mcp): name GitLab file links by project ID and report the link account cap --- apps/sim/lib/sim-search/live/application.ts | 17 +++++++++-------- apps/sim/lib/sim-search/live/links.test.ts | 4 ++-- apps/sim/lib/sim-search/live/links.ts | 2 +- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/apps/sim/lib/sim-search/live/application.ts b/apps/sim/lib/sim-search/live/application.ts index 79b44f551f8..f9b4eeca1b5 100644 --- a/apps/sim/lib/sim-search/live/application.ts +++ b/apps/sim/lib/sim-search/live/application.ts @@ -1203,13 +1203,12 @@ async function readLinkedDocument( /** Cancellation by the caller passes through unclassified. */ throw input.signal?.aborted ? error : liveReadFailure(error, links[0]?.provider ?? '', signal) }) - const candidates = accounts - .filter( - (account) => - links.some((link) => link.provider === account.provider) && - (!input.filters?.source || input.filters.source === account.provider) - ) - .slice(0, MAX_LINK_ACCOUNTS) + 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', @@ -1272,7 +1271,9 @@ async function readLinkedDocument( failure ?? new OrchestrationError( 'not_found', - `This link is not on a site, workspace or host your connected ${sourceNames} account reaches. Search for the document instead.` + 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.` ) ) } diff --git a/apps/sim/lib/sim-search/live/links.test.ts b/apps/sim/lib/sim-search/live/links.test.ts index 5cfde651aa6..0c968d1589d 100644 --- a/apps/sim/lib/sim-search/live/links.test.ts +++ b/apps/sim/lib/sim-search/live/links.test.ts @@ -216,10 +216,10 @@ describe('locateDocumentLink', () => { if (!link) throw new Error('Expected a link') await expect( locateDocumentLink(link, { - client: client({ path_with_namespace: 'team/api', default_branch: 'main' }), + client: client({ id: 42, default_branch: 'main' }), origin: 'https://git.acme.dev', }) - ).resolves.toEqual({ id: 'src/a.ts', container: 'team/api', kind: 'code', revision: 'main' }) + ).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 () => { diff --git a/apps/sim/lib/sim-search/live/links.ts b/apps/sim/lib/sim-search/live/links.ts index 3ed0c2172c0..56e1a8fb319 100644 --- a/apps/sim/lib/sim-search/live/links.ts +++ b/apps/sim/lib/sim-search/live/links.ts @@ -369,7 +369,7 @@ async function locateFile( container: link.provider === 'github' ? string(row.full_name) || link.repository - : string(row.path_with_namespace) || 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 } : {}), From b4a1838acb31f77274fc942f8ba7dafc7eafe1b4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 12:11:20 -0800 Subject: [PATCH 8/9] improvement(search-mcp): encode GitLab project paths with the GitLab resource helper --- apps/sim/lib/sim-search/live/links.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/sim-search/live/links.ts b/apps/sim/lib/sim-search/live/links.ts index 56e1a8fb319..19796c84581 100644 --- a/apps/sim/lib/sim-search/live/links.ts +++ b/apps/sim/lib/sim-search/live/links.ts @@ -1,9 +1,10 @@ import { parseGitHubRepository } from '@/lib/oauth/github-repository' import { atlassianSiteId } from '@/lib/sim-search/live/atlassian' -import { NativeSearchError, object, segment, string } from '@/lib/sim-search/live/http' +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< @@ -199,7 +200,8 @@ function githubCommit( function gitlabLink(url: URL): DocumentLink | undefined { const parts = pathSegments(url) const separator = parts.indexOf('-') - if (separator < 1) return undefined + 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 => ({ @@ -353,7 +355,7 @@ async function locateFile( await account.client.json( link.provider === 'github' ? `/repos/${link.repository}` - : `/api/v4/projects/${segment(link.repository)}`, + : `/api/v4/projects/${encodeGitLabResourceId(link.repository)}`, { memo: true } ) ) From df69a22dcbf81633d3343551988a97d9d34e0ccc Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 12:17:05 -0800 Subject: [PATCH 9/9] improvement(search-mcp): reserve more GitHub site routes in link parsing --- apps/sim/lib/sim-search/live/links.test.ts | 1 + apps/sim/lib/sim-search/live/links.ts | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/apps/sim/lib/sim-search/live/links.test.ts b/apps/sim/lib/sim-search/live/links.test.ts index 0c968d1589d..ca1ca9e2a27 100644 --- a/apps/sim/lib/sim-search/live/links.test.ts +++ b/apps/sim/lib/sim-search/live/links.test.ts @@ -152,6 +152,7 @@ describe('parseDocumentLinks', () => { ['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', diff --git a/apps/sim/lib/sim-search/live/links.ts b/apps/sim/lib/sim-search/live/links.ts index 19796c84581..f36f5e8e422 100644 --- a/apps/sim/lib/sim-search/live/links.ts +++ b/apps/sim/lib/sim-search/live/links.ts @@ -61,13 +61,20 @@ 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',