diff --git a/apps/sim/lib/sim-search/live/account-session.ts b/apps/sim/lib/sim-search/live/account-session.ts index de9e634b4ec..5c08a20da92 100644 --- a/apps/sim/lib/sim-search/live/account-session.ts +++ b/apps/sim/lib/sim-search/live/account-session.ts @@ -276,13 +276,12 @@ export async function openLiveAccountSession( return connectionBinding ? { ...page, documents: page.documents.map(bind) } : page }, async activity(request) { - if (admin || !client) + if (!client) throw new NativeSearchError('unavailable', 'This source does not report activity.') - const page = await activityNativeProvider(provider, client, { - ...request, - policy: boundary.policy, - signal: request.signal ?? signal, - }) + const scoped = { ...request, policy: boundary.policy, signal: request.signal ?? signal } + const page = admin + ? await admin.activity(scoped) + : await activityNativeProvider(provider, client, scoped) if (!connectionBinding) return page return { ...page, diff --git a/apps/sim/lib/sim-search/live/activity-paging.integration.ts b/apps/sim/lib/sim-search/live/activity-paging.integration.ts index 53423e1bf57..684bcc2d0e0 100644 --- a/apps/sim/lib/sim-search/live/activity-paging.integration.ts +++ b/apps/sim/lib/sim-search/live/activity-paging.integration.ts @@ -194,3 +194,16 @@ it('names the connected sources it does not cover once, not as a status each', a expect(result.unsupported?.sources).toEqual(['notion', 'coda']) expect(result.sources.map(({ source }) => source)).toEqual(['slack']) }) + +it('reads a GitLab administrator source, whose entries are the viewer’s own verified events', async () => { + fakes.accounts = [ + { + account: { ...account('gitlab-source', 'gitlab'), type: 'admin_source' }, + items: items('gitlab', 2, 3, 5), + readSize: 3, + }, + ] + const result = await listMyActivity.execute({ principal, input: { organizationId } }) + expect(result.items.map(({ title }) => title)).toEqual(['gitlab-0', 'gitlab-1']) + expect(result.unsupported).toBeUndefined() +}) diff --git a/apps/sim/lib/sim-search/live/activity-providers.test.ts b/apps/sim/lib/sim-search/live/activity-providers.test.ts index 264e9a295e7..6c5eab5895b 100644 --- a/apps/sim/lib/sim-search/live/activity-providers.test.ts +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it, vi } from 'vitest' import { atlassianActivity } from '@/lib/sim-search/live/atlassian' import { githubActivity } from '@/lib/sim-search/live/github' +import { gitLabActivity, gitLabMemberActivity } from '@/lib/sim-search/live/gitlab-activity' import { calendarActivity, driveActivity, gmailActivity } from '@/lib/sim-search/live/google' import { linearActivity } from '@/lib/sim-search/live/linear' import { slackActivity } from '@/lib/sim-search/live/slack' @@ -627,3 +628,151 @@ describe('Linear activity format', () => { await expect(linearActivity(api, WINDOW)).rejects.toThrow('unsupported result format') }) }) + +describe('GitLab activity', () => { + const event = (id: number, at: string, project: number, fields: Record) => ({ + id, + project_id: project, + created_at: at, + ...fields, + }) + /** Answers the member's events a page at a time and each project's lookup. */ + const gitlab = (pages: Record[][], projects: number[] = [42]) => + client((path, options) => { + if (path === '/api/v4/user') return { id: 7 } + if (path === '/api/v4/users/7/events') return pages[Number(options?.query?.page) - 1] ?? [] + const project = /^\/api\/v4\/projects\/(\d+)$/.exec(path)?.[1] + if (project && projects.includes(Number(project))) + return { web_url: `https://git.example.com/team/p${project}` } + return undefined + }) + + it('reports what the member opened, commented on, approved and pushed, leaving out internal notes and diff comment text', async () => { + const api = gitlab([ + [ + event(5, '2026-11-07T10:00:00Z', 42, { + action_name: 'opened', + target_type: 'MergeRequest', + target_iid: 3, + target_title: 'Retry uploads', + }), + event(4, '2026-11-06T10:00:00Z', 42, { + action_name: 'commented on', + target_type: 'DiffNote', + target_title: 'Retry uploads', + note: { body: 'Rename this file', noteable_type: 'MergeRequest', noteable_iid: 3 }, + }), + event(3, '2026-11-05T10:00:00Z', 42, { + action_name: 'commented on', + target_type: 'Note', + note: { body: 'Secret', noteable_type: 'Issue', noteable_iid: 9, internal: true }, + }), + event(2, '2026-11-04T10:00:00Z', 42, { + action_name: 'approved', + target_type: 'MergeRequest', + target_iid: 3, + }), + event(1, '2026-11-03T10:00:00Z', 42, { + action_name: 'pushed', + push_data: { ref_type: 'branch', commit_to: 'a'.repeat(40), commit_title: 'Fix' }, + }), + ], + ]) + const [stream] = (await gitLabMemberActivity(api, WINDOW)).streams + expect( + stream?.events.map(({ document, action }) => [ + document.kind, + document.id, + action, + document.url, + ]) + ).toEqual([ + ['merge_requests', '3', 'created', 'https://git.example.com/team/p42/-/merge_requests/3'], + ['merge_requests', '3', 'commented', 'https://git.example.com/team/p42/-/merge_requests/3'], + ['merge_requests', '3', 'involved', 'https://git.example.com/team/p42/-/merge_requests/3'], + [ + 'commits', + 'a'.repeat(40), + 'committed', + `https://git.example.com/team/p42/-/commit/${'a'.repeat(40)}`, + ], + ]) + expect(stream?.events[1]?.document.content).not.toContain('Rename this file') + expect(stream?.more).toBe(false) + }) + + it('reads past events newer than the bound and reports where it stopped when it reaches none', async () => { + const newer = Array.from({ length: 20 }, (_, index) => + event( + 100 - index, + `2026-11-08T0${Math.floor(index / 10)}:00:${String(index % 10).padStart(2, '0')}Z`, + 42, + { + action_name: 'updated', + target_type: 'Issue', + target_iid: index, + } + ) + ) + const api = gitlab([newer.slice(0, 15), newer.slice(15, 20)]) + const [stream] = ( + await gitLabMemberActivity(api, { ...WINDOW, end: '2026-11-07T23:59:59.000Z', limit: 15 }) + ).streams + expect(stream?.events).toEqual([]) + expect(stream?.more).toBe(false) + const full = gitlab([newer.slice(0, 15), newer.slice(0, 15), newer.slice(0, 15)]) + const [capped] = ( + await gitLabMemberActivity(full, { ...WINDOW, end: '2026-11-07T23:59:59.000Z', limit: 15 }) + ).streams + expect(capped?.more).toBe(true) + expect(Date.parse(capped?.scannedTo ?? '')).toBeGreaterThan(Date.parse('2026-11-07T23:59:59Z')) + }) + + it('stops at an event whose project it cannot look up yet, so the next page resumes there', async () => { + const rows = [42, 43, 44, 45, 46, 47].map((project, index) => + event(10 - index, `2026-11-0${7 - index}T10:00:00Z`, project, { + action_name: 'opened', + target_type: 'Issue', + target_iid: index + 1, + }) + ) + const api = gitlab([rows], [42, 43, 44, 45, 46, 47]) + const [stream] = (await gitLabMemberActivity(api, WINDOW)).streams + expect(stream?.events).toHaveLength(5) + expect(stream).toMatchObject({ more: true, scannedTo: '2026-11-02T10:00:00.000Z' }) + }) + + it('leaves out events in projects or collections an administrator source does not serve', async () => { + const api = client((path) => + path === '/api/v4/users/7/events' + ? [ + event(3, '2026-11-06T10:00:00Z', 42, { + action_name: 'opened', + target_type: 'Issue', + target_iid: 1, + }), + event(2, '2026-11-05T10:00:00Z', 99, { + action_name: 'opened', + target_type: 'MergeRequest', + target_iid: 2, + }), + event(1, '2026-11-04T10:00:00Z', 42, { + action_name: 'opened', + target_type: 'MergeRequest', + target_iid: 3, + }), + ] + : undefined + ) + const [stream] = ( + await gitLabActivity(api, WINDOW, { + path: '/api/v4/users/7/events', + kinds: new Set(['merge_requests']), + projectUrl: async (id) => (id === '42' ? 'https://git.example.com/team/p42' : undefined), + }) + ).streams + expect(stream?.events.map(({ document }) => [document.container, document.id])).toEqual([ + ['42', '3'], + ]) + }) +}) diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index f7db90c3d2d..6db2badbd25 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -266,7 +266,8 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ const readable = (account: LiveAccount) => supportsActivity(account.provider) && account.type !== 'managed_mcp' && - account.type !== 'admin_source' + /** GitLab's administrator sources read the viewer's own events, verified per project. */ + (account.type !== 'admin_source' || account.provider === 'gitlab') const eligible = accounts.filter(readable) const selected = cursor ? eligible.filter((account) => cursor.accounts[account.id]) diff --git a/apps/sim/lib/sim-search/live/gitlab-activity.ts b/apps/sim/lib/sim-search/live/gitlab-activity.ts new file mode 100644 index 00000000000..d14f04aee83 --- /dev/null +++ b/apps/sim/lib/sim-search/live/gitlab-activity.ts @@ -0,0 +1,208 @@ +import { oldestInstant } from '@/lib/sim-search/live/activity-page' +import { gitLabDocumentUrl } from '@/lib/sim-search/live/gitlab' +import { array, NativeSearchError, object, string } from '@/lib/sim-search/live/http' +import type { + NativeActivityEvent, + NativeActivityInput, + NativeActivityPage, + NativeClient, +} from '@/lib/sim-search/live/types' + +/** Event pages one call reads to reach the window, bounding a person with heavy recent activity. */ +const GITLAB_EVENT_PAGES = 3 +/** Events per page; each surviving event costs its verification a request, within the budget. */ +const GITLAB_EVENT_PAGE_SIZE = 15 +/** Projects a member account looks up per call to link its events; later events wait a page. */ +const GITLAB_ACTIVITY_PROJECT_LOOKUPS = 5 + +/** GitLab's action names, as the shared activity actions name what the person did. */ +const GITLAB_ACTIONS: Record = { + opened: 'created', + created: 'created', + pushed: 'committed', + 'pushed to': 'committed', + 'pushed new': 'committed', + closed: 'edited', + reopened: 'edited', + updated: 'edited', + merged: 'edited', + accepted: 'edited', + approved: 'involved', + 'commented on': 'commented', +} + +/** One calendar day, as the events API takes its exclusive `after` and `before` bounds. */ +const day = (time: number) => new Date(time).toISOString().slice(0, 10) +const DAY_MS = 86_400_000 + +/** Where one account's GitLab activity comes from and which of its projects it serves. */ +interface GitLabActivitySource { + /** The events listing: the token owner's own, or one person's for an administrator's token. */ + path: string + /** The collections the source serves; events naming any other are left out. */ + kinds?: ReadonlySet + /** + * The web URL of a project the source serves, `undefined` for a project it does not serve, or + * `null` for one this call cannot look up: the call stops there and a later page resumes at it. + */ + projectUrl(projectId: string): Promise +} + +/** + * What one GitLab event did to a document, or null for events that name nothing activity reports: + * an issue or merge request the person opened, changed, approved or commented on (internal and + * system notes are left out), or the commit a branch push ended at. + */ +function activityEvent(row: Record): NativeActivityEvent | null { + const at = Date.parse(string(row.created_at)) + const action = GITLAB_ACTIONS[string(row.action_name)] + if (!Number.isFinite(at) || !action) return null + const target = string(row.target_type) + const note = object(row.note) + const push = object(row.push_data) + let kind: string + let id: string + let title = string(row.target_title) + let content = title + if (target === 'Issue' || target === 'MergeRequest') { + kind = target === 'Issue' ? 'issues' : 'merge_requests' + id = string(row.target_iid) + } else if (target === 'Note' || target === 'DiffNote' || target === 'DiscussionNote') { + if (note.internal === true || note.confidential === true || note.system === true) return null + const noteable = string(note.noteable_type) + if (noteable !== 'Issue' && noteable !== 'MergeRequest') return null + kind = noteable === 'Issue' ? 'issues' : 'merge_requests' + id = string(note.noteable_iid) + /** + * A diff comment's file may sit outside a source's code scope, which a read of the merge + * request hides; activity names the comment without its text. + */ + if (target !== 'DiffNote') content = string(note.body) + } else if (push.commit_to && push.ref_type === 'branch') { + kind = 'commits' + id = string(push.commit_to) + title = string(push.commit_title) || id.slice(0, 8) + content = title + } else return null + if (!id) return null + return { + document: { + id, + container: string(row.project_id), + kind, + /** Each event is its own entry, though several name the same issue or merge request. */ + dedupeKey: `event:${string(row.id)}`, + title: title || `${kind === 'issues' ? 'Issue #' : '!'}${id}`, + url: '', + content, + modifiedAt: new Date(at).toISOString(), + }, + at: new Date(at).toISOString(), + action, + collaborators: [], + } +} + +/** + * The person's own GitLab contributions, newest first by when they acted: one stream read from + * GitLab's events, at most a few pages a call. Events newer than the bound are read past; a call + * that reads only those reports where it stopped, past the bound, so the listing stops this + * account instead of reading the same events again. A call that stops at an event whose project + * it cannot look up yet reports that event's instant, so the next page reads it again. + */ +export async function gitLabActivity( + client: NativeClient, + input: NativeActivityInput, + source: GitLabActivitySource +): Promise { + const start = Date.parse(input.start) + const end = Date.parse(input.end) + const pageSize = Math.min(GITLAB_EVENT_PAGE_SIZE, Math.max(1, input.limit)) + const events: NativeActivityEvent[] = [] + const read: string[] = [] + let more = false + let reachedBound = false + let stoppedAt: string | undefined + for (let page = 1; page <= GITLAB_EVENT_PAGES && !reachedBound; page++) { + const response = await client.json(source.path, { + query: { + after: day(start - DAY_MS), + before: day(end + DAY_MS), + sort: 'desc', + per_page: String(pageSize), + page: String(page), + }, + signal: input.signal, + }) + if (!Array.isArray(response) || response.length > pageSize) + throw new NativeSearchError('unavailable', 'GitLab returned an invalid event listing.') + const rows = array(response) + more = rows.length === pageSize + for (const row of rows) { + const at = Date.parse(string(row.created_at)) + if (!Number.isFinite(at)) continue + read.push(string(row.created_at)) + if (at > end) continue + reachedBound = true + if (at < start) { + more = false + break + } + const event = activityEvent(row) + if (!event || (source.kinds && !source.kinds.has(event.document.kind ?? ''))) continue + const projectUrl = await source.projectUrl(event.document.container ?? '') + if (projectUrl === null) { + stoppedAt = event.at + break + } + if (!projectUrl) continue + event.document.url = gitLabDocumentUrl(projectUrl, event.document.kind, event.document.id) + events.push(event) + } + if (stoppedAt) return { streams: [{ events, more: true, scannedTo: stoppedAt }] } + if (!more) break + } + const scannedTo = oldestInstant(read) + return { + streams: [{ events, more: more && Boolean(scannedTo), ...(scannedTo ? { scannedTo } : {}) }], + } +} + +/** + * The connected member's own GitLab activity, from their user's events: the token owner's own + * listing (`/events`) leaves out merge requests. Each event's project is looked up once for its + * link, at most {@link GITLAB_ACTIVITY_PROJECT_LOOKUPS} projects a call. + */ +export async function gitLabMemberActivity( + client: NativeClient, + input: NativeActivityInput +): Promise { + const user = string( + object(await client.json('/api/v4/user', { memo: true, signal: input.signal })).id + ) + if (!/^\d+$/.test(user)) + throw new NativeSearchError('unavailable', 'GitLab did not identify the connected user.') + const lookups = new Map>() + return gitLabActivity(client, input, { + path: `/api/v4/users/${user}/events`, + async projectUrl(projectId) { + if (!/^\d+$/.test(projectId)) return undefined + let lookup = lookups.get(projectId) + if (!lookup) { + if (lookups.size >= GITLAB_ACTIVITY_PROJECT_LOOKUPS) return null + lookup = client + .json(`/api/v4/projects/${projectId}`, { memo: true, signal: input.signal }) + .then( + (project) => string(object(project).web_url) || undefined, + /** A project deleted since, or no longer visible to the member, links nothing. */ + (error: unknown) => { + if (error instanceof NativeSearchError && error.httpStatus === 404) return undefined + throw error + } + ) + lookups.set(projectId, lookup) + } + return lookup + }, + }) +} diff --git a/apps/sim/lib/sim-search/live/gitlab-admin.ts b/apps/sim/lib/sim-search/live/gitlab-admin.ts index 026e45529db..9559f38dfc9 100644 --- a/apps/sim/lib/sim-search/live/gitlab-admin.ts +++ b/apps/sim/lib/sim-search/live/gitlab-admin.ts @@ -30,6 +30,7 @@ import { resolveGitLabPerson, searchGitLab, } from '@/lib/sim-search/live/gitlab' +import { gitLabActivity } from '@/lib/sim-search/live/gitlab-activity' import { array, isCommitSha, @@ -41,6 +42,8 @@ import { import { collectNativePages, joinMessages } from '@/lib/sim-search/live/pages' import type { LiveAccount, + NativeActivityInput, + NativeActivityPage, NativeClient, NativeDocument, NativePage, @@ -204,7 +207,14 @@ async function gitLabPerson( involving: string | undefined ): Promise { if (!involving) return undefined - const email = involving === 'me' ? userTokenEmail(own) : involving + return involving === 'me' + ? viewerGitLabPerson(client, own) + : resolveGitLabPerson(client, involving) +} + +/** The viewer's GitLab user, found by their verified organization email, never the token's. */ +function viewerGitLabPerson(client: NativeClient, own: string): Promise { + const email = userTokenEmail(own) if (!email) throw new NativeSearchError('unavailable', 'GitLab search requires a verified email.') return resolveGitLabPerson(client, email) } @@ -437,6 +447,16 @@ async function createProjectSession( } return { verify, + /** The viewer's own contributions to the project; each entry is verified like a search result. */ + async activity(request: NativeActivityInput): Promise { + const person = await viewerGitLabPerson(client, own) + const projectUrl = `https://${normalizeGitLabHost(string(config.host))}/${projectPath.split('/').map(segment).join('/')}` + return gitLabActivity(client, request, { + path: `/api/v4/users/${person.id}/events`, + kinds: new Set(kinds), + projectUrl: async (id) => (id === project ? projectUrl : undefined), + }) + }, async search(search: NativeSearchInput) { if (search.native?.project && ![project, projectPath].includes(search.native.project)) return { documents: [] } @@ -775,6 +795,21 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { return project ? (await permittedProjects([project]))[0] : undefined } return { + /** The viewer's own contributions to the group's projects; each entry is verified later. */ + async activity(request: NativeActivityInput): Promise { + const person = await viewerGitLabPerson(client, own) + const urls = new Map( + (await fallbackProjects()).map((project) => [ + String(project.id), + `https://${metadata.host}/${project.path.split('/').map(segment).join('/')}`, + ]) + ) + return gitLabActivity(client, request, { + path: `/api/v4/users/${person.id}/events`, + kinds: new Set(gitLabSourceKinds(source.config)), + projectUrl: async (id) => urls.get(id), + }) + }, async verify(reference: Reference, evidence?: Record) { const project = await referencedProject(reference.container) return project ? (await session(project)).verify(reference, evidence) : false diff --git a/apps/sim/lib/sim-search/live/providers.ts b/apps/sim/lib/sim-search/live/providers.ts index 0ebac587800..5bea28ef116 100644 --- a/apps/sim/lib/sim-search/live/providers.ts +++ b/apps/sim/lib/sim-search/live/providers.ts @@ -9,6 +9,7 @@ import { readCoda, searchCoda } from '@/lib/sim-search/live/coda' import { readFlow, searchFlow } from '@/lib/sim-search/live/flow' import { githubActivity, readGitHub, searchGitHub } from '@/lib/sim-search/live/github' import { readGitLab, searchGitLab } from '@/lib/sim-search/live/gitlab' +import { gitLabMemberActivity } from '@/lib/sim-search/live/gitlab-activity' import { calendarActivity, driveActivity, @@ -305,6 +306,7 @@ export const LIVE_SEARCH_PROVIDERS = { 'expecting date filters or sorting on code or wiki results, oldest-first commits, and relying on advanced-search operators (quotes, |, -) on instances that may only have basic search. Commit search across a group needs advanced search; set project to search the commits of one project. Read a merge request for its discussion and diff, and a commit for its diff.', }, search: (client, input) => searchGitLab(client, input), + activity: gitLabMemberActivity, read: (client, reference) => readGitLab(client, reference.id, reference.container, reference.kind, reference.revision), },