The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add Fathom discovery and backfill (#25251)
nitin2ca246695ed4
diff --git a/packages/twenty-apps/public/fathom/CHANGELOG.md b/packages/twenty-apps/public/fathom/CHANGELOG.mdindex 4dd1aa2fc8a..d090b3a9fe2 100644--- a/packages/twenty-apps/public/fathom/CHANGELOG.md+++ b/packages/twenty-apps/public/fathom/CHANGELOG.md@@ -7,3 +7,7 @@ All notable changes to this application are documented in this file.- Add per-user Fathom OAuth and signed webhook registration.- Sync new Fathom recordings into idempotent Twenty Call Recordings.- Delete registered Fathom webhooks when the app is uninstalled.+- Import the last 31 days of recordings when a Fathom account is connected+ and accept manual history imports, paced per connected account.+- Add the Sync Fathom Call and List Fathom Calls By Participant workflow and AI+ actions.diff --git a/packages/twenty-apps/public/fathom/README.md b/packages/twenty-apps/public/fathom/README.mdindex d5b66dfbaf4..4d764fd8e82 100644--- a/packages/twenty-apps/public/fathom/README.md+++ b/packages/twenty-apps/public/fathom/README.md@@ -1,6 +1,6 @@# Fathom-**Bring new Fathom meeting recordings, transcripts, and insights into Twenty.**+**Bring Fathom meeting recordings, transcripts, and insights into Twenty.**## What you get@@ -8,6 +8,10 @@- Transcripts, summaries, and action items- Links to matching calendar events when the match is unambiguous- Automatic sync for new recordings+- A 31-day import when a Fathom account is connected, and manual imports of+ older history+- Workflow and AI actions to sync one recording or list recordings by+ participant## Requirementsdiff --git a/packages/twenty-apps/public/fathom/SETUP.md b/packages/twenty-apps/public/fathom/SETUP.mdindex 3736ac55a76..726f9858512 100644--- a/packages/twenty-apps/public/fathom/SETUP.md+++ b/packages/twenty-apps/public/fathom/SETUP.md@@ -51,7 +51,18 @@ to the workspace that made the connection, so no per-workspace domain is needed.yarn twenty dev```-5. Open [http://localhost:2020](http://localhost:2020), log in with the default development credentials: `[email protected]` / `[email protected]`, and connect Fathom from Settings. The connection hook registers the signed webhook.+5. Open [http://localhost:2020](http://localhost:2020), log in with the default development credentials: `[email protected]` / `[email protected]`, and connect Fathom from Settings. The connection hook registers the signed webhook and starts a 31-day import.++6. Import older history when needed with an authenticated request:++ ```bash+ curl -X POST https://<development-host>/s/fathom/backfill \+ -H "Authorization: Bearer <api-key-or-access-token>" \+ -H "Content-Type: application/json" \+ -d '{"days": 30}'+ ```++ The import runs through the requesting user's Fathom connection.## Verifying your setupdiff --git a/packages/twenty-apps/public/fathom/src/__tests__/deployed-functions.integration-test.ts b/packages/twenty-apps/public/fathom/src/__tests__/deployed-functions.integration-test.tsnew file mode 100644index 00000000000..3c87c3ee84c--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/__tests__/deployed-functions.integration-test.ts@@ -0,0 +1,136 @@+import * as fs from 'fs';+import * as path from 'path';++import { MetadataApiClient } from 'twenty-client-sdk/metadata';+import { functionExecute } from 'twenty-sdk/cli';+import { describe, expect, it } from 'vitest';++// These scenarios run the functions the way the server runs them: deployed,+// in the app runtime, against the real connection store and job queue. No+// Fathom account is connected on the test workspace, so every path ends at+// the connection lookup, after the bundle, the SDK calls and the input+// validation have run for real.+const APP_PATH = process.cwd();++const executeDeployedFunction = async (+ functionName: string,+ payload: Record<string, unknown>,+) => {+ const result = await functionExecute({+ appPath: APP_PATH,+ functionName,+ payload,+ });++ if (!result.success) {+ throw new Error(+ `Could not execute ${functionName}: ${result.error.message}`,+ );+ }++ return result.data;+};++const buildRoutePayload = (body: Record<string, unknown>) => ({+ headers: {},+ queryStringParameters: {},+ pathParameters: {},+ body,+ isBase64Encoded: false,+ requestContext: { http: { method: 'POST', path: '/fathom/backfill' } },+});++const readManifestLogicFunctionNames = (): string[] => {+ const manifest = JSON.parse(+ fs.readFileSync(+ path.join(APP_PATH, '.twenty', 'output', 'manifest.json'),+ 'utf8',+ ),+ ) as { logicFunctions: { name: string }[] };++ return manifest.logicFunctions.map((logicFunction) => logicFunction.name);+};++describe('Fathom app deployed functions', () => {+ it('deploys every logic function the manifest declares', async () => {+ const deployedFunctionsResult = await new MetadataApiClient().query({+ findManyLogicFunctions: { id: true, name: true },+ });+ const deployedFunctionNames: string[] =+ deployedFunctionsResult.findManyLogicFunctions.map(+ (logicFunction: { name: string }) => logicFunction.name,+ );++ for (const manifestFunctionName of readManifestLogicFunctionNames()) {+ expect(deployedFunctionNames).toContain(manifestFunctionName);+ }+ });++ it('rejects a backfill window outside the allowed range before touching the queue', async () => {+ const execution = await executeDeployedFunction(+ 'fathom-backfill',+ buildRoutePayload({ days: 0 }),+ );++ expect(execution.status).toBe('SUCCESS');+ expect(execution.data).toEqual({+ success: false,+ error: expect.stringContaining('between 1 and'),+ });+ });++ it('reports the missing Fathom connection from the deployed backfill route', async () => {+ const execution = await executeDeployedFunction(+ 'fathom-backfill',+ buildRoutePayload({ days: 30 }),+ );++ expect(execution.status).toBe('SUCCESS');+ expect(execution.data).toEqual({+ success: false,+ error: expect.stringContaining('Fathom is not connected'),+ });+ });++ it('rejects invalid workflow action input before looking up a connection', async () => {+ const listExecution = await executeDeployedFunction(+ 'fathom-list-calls-by-participant',+ { participantEmail: ' ' },+ );+ const syncExecution = await executeDeployedFunction('fathom-sync-call', {+ recordingId: '42',+ });++ expect(listExecution.status).toBe('SUCCESS');+ expect(listExecution.data).toEqual({+ success: false,+ error: 'participantEmail is required',+ });+ expect(syncExecution.status).toBe('SUCCESS');+ expect(syncExecution.data).toEqual({+ success: false,+ error: 'recordingId must be an integer',+ });+ });++ it('reports the missing Fathom connection from the deployed workflow actions', async () => {+ const listExecution = await executeDeployedFunction(+ 'fathom-list-calls-by-participant',+ { participantEmail: '[email protected]' },+ );+ const syncExecution = await executeDeployedFunction('fathom-sync-call', {+ recordingId: 42,+ });++ expect(listExecution.status).toBe('SUCCESS');+ expect(listExecution.data).toEqual({+ success: false,+ error: expect.stringContaining('Fathom is not connected'),+ });+ expect(syncExecution.status).toBe('SUCCESS');+ expect(syncExecution.data).toEqual({+ success: false,+ error: expect.stringContaining('Fathom is not connected'),+ });+ });+});diff --git a/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-meeting-pages.util.ts b/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-meeting-pages.util.tsnew file mode 100644index 00000000000..dc55715f9c8--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-meeting-pages.util.ts@@ -0,0 +1,18 @@+import { type Meeting } from 'fathom-typescript/sdk/models/shared';++// Mirrors listMeetings: the page for a cursor is the response itself, and each+// page names the cursor of the next one.+export const buildFathomMeetingPages =+ (meetingPages: Meeting[][]) =>+ async ({ cursor }: { cursor?: string }) => {+ const pageIndex = cursor === undefined ? 0 : Number(cursor);+ const isLastPage = pageIndex >= meetingPages.length - 1;++ return {+ result: {+ items: meetingPages[pageIndex] ?? [],+ limit: null,+ nextCursor: isLastPage ? null : String(pageIndex + 1),+ },+ };+ };diff --git a/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-meeting.util.ts b/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-meeting.util.tsnew file mode 100644index 00000000000..de1e204f672--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-meeting.util.ts@@ -0,0 +1,41 @@+import { type Meeting } from 'fathom-typescript/sdk/models/shared';++export const buildFathomMeeting = ({+ recordingId,+ recorderEmail = '[email protected]',+ inviteeEmails = [],+ recordingStartTime = '2026-08-20T10:00:00.000Z',+}: {+ recordingId: number;+ recorderEmail?: string;+ inviteeEmails?: string[];+ recordingStartTime?: string;+}): Meeting => ({+ title: `Recording ${recordingId}`,+ meetingTitle: `Meeting ${recordingId}`,+ meetingType: null,+ recordingId,+ url: `https://fathom.video/calls/${recordingId}`,+ meetingUrl: 'https://meet.example.com/customer-call',+ shareUrl: `https://fathom.video/share/${recordingId}`,+ createdAt: new Date(recordingStartTime),+ scheduledStartTime: new Date(recordingStartTime),+ scheduledEndTime: new Date(Date.parse(recordingStartTime) + 30 * 60_000),+ recordingStartTime: new Date(recordingStartTime),+ recordingEndTime: new Date(Date.parse(recordingStartTime) + 30 * 60_000),+ calendarInviteesDomainsType: 'one_or_more_external',+ sharedWith: 'single_team',+ transcriptLanguage: 'en',+ calendarInvitees: inviteeEmails.map((email) => ({+ name: email,+ email,+ emailDomain: email.split('@')[1],+ isExternal: true,+ })),+ recordedBy: {+ name: recorderEmail,+ email: recorderEmail,+ emailDomain: recorderEmail.split('@')[1],+ team: 'Sales',+ },+});diff --git a/packages/twenty-apps/public/fathom/src/__tests__/utils/logic-function-execution-context.util.ts b/packages/twenty-apps/public/fathom/src/__tests__/utils/logic-function-execution-context.util.tsnew file mode 100644index 00000000000..ff1c7602af8--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/__tests__/utils/logic-function-execution-context.util.ts@@ -0,0 +1,11 @@+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';++export const buildLogicFunctionExecutionContext = (+ userWorkspaceId: string | null,+): LogicFunctionExecutionContext => ({+ retryCount: 0,+ maxRetries: 3,+ workspaceId: 'workspace-1',+ userWorkspaceId,+ workspaceMemberId: null,+});diff --git a/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts b/packages/twenty-apps/public/fathom/src/constants/fathom.constant.tsindex a870418a99a..339e70ba8d1 100644--- a/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts+++ b/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts@@ -2,3 +2,14 @@ export const FATHOM_PROVIDER_NAME = 'fathom';export const FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER = 'connectionId';export const CALENDAR_EVENT_PAGE_SIZE = 200;export const MAX_CALENDAR_EVENT_PAGES = 10;+export const FATHOM_BACKFILL_ROUTE_PATH = '/fathom/backfill';+export const FATHOM_BACKFILL_MAX_WINDOW_DAYS = 3_650;+export const FATHOM_INITIAL_BACKFILL_DAYS = 31;+export const FATHOM_BACKFILL_BATCH_SIZE = 5;+export const FATHOM_BACKFILL_BATCH_STAGGER_MILLISECONDS = 20_000;+export const FATHOM_BACKFILL_JOB_RETRY_LIMIT = 3;+export const FATHOM_REQUEST_RETRY_MAX_ELAPSED_MILLISECONDS = 10_000;+export const MAX_FATHOM_MEETING_PAGES = 20;+export const MAX_FATHOM_BACKFILL_PAGES = 1_000;+export const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1_000;+export const CALL_RECORDING_IDS_PER_QUERY = 200;diff --git a/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.tsindex d908644cc12..200ea69d16a 100644--- a/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts+++ b/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts@@ -17,3 +17,13 @@ export const FATHOM_WEBHOOK_UNIVERSAL_IDENTIFIER ='4047fcd1-8581-4188-bf35-e3e49a6235ca';export const FATHOM_UNINSTALL_UNIVERSAL_IDENTIFIER ='2f0b2b98-6ec1-4a3f-95bb-b2adf4bd4e33';+export const FATHOM_BACKFILL_UNIVERSAL_IDENTIFIER =+ 'b4ee8f0c-59e8-4586-8e5a-b2aca5624cbe';+export const FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER =+ '5c2ca1f0-0b68-4dc3-b7f8-3c14c618a334';+export const FATHOM_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER =+ 'f94eacc8-c611-4453-a865-e4650953ccec';+export const FATHOM_SYNC_CALL_UNIVERSAL_IDENTIFIER =+ '606e8b64-d659-4e45-a292-0cafb08c06ed';+export const FATHOM_LIST_CALLS_BY_PARTICIPANT_UNIVERSAL_IDENTIFIER =+ '24e37c59-c458-4cf9-9021-e16f904d62c1';diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-list-calls-by-participant.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-list-calls-by-participant.test.tsnew file mode 100644index 00000000000..ac30311ab20--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-list-calls-by-participant.test.ts@@ -0,0 +1,129 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildFathomMeeting } from 'src/__tests__/utils/build-fathom-meeting.util';+import { buildFathomMeetingPages } from 'src/__tests__/utils/build-fathom-meeting-pages.util';+import { buildLogicFunctionExecutionContext } from 'src/__tests__/utils/logic-function-execution-context.util';++const mocks = vi.hoisted(() => ({+ listFathomConnectionsForRequest: vi.fn(),+ listMeetings: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', () => ({+ jsonSchemaToInputSchema: () => [],+}));++vi.mock('fathom-typescript', () => ({+ Fathom: class Fathom {+ listMeetings = mocks.listMeetings;+ },+}));++vi.mock(+ 'src/logic-functions/utils/list-fathom-connections-for-request.util',+ () => ({+ listFathomConnectionsForRequest: mocks.listFathomConnectionsForRequest,+ }),+);++const { fathomListCallsByParticipantHandler } =+ await import('src/logic-functions/fathom-list-calls-by-participant');++const CONTEXT = buildLogicFunctionExecutionContext('user-workspace-1');++const buildMeetingWith = (recordingId: number, startedAt: string) =>+ buildFathomMeeting({+ recordingId,+ inviteeEmails: ['[email protected]', '[email protected]'],+ recordingStartTime: startedAt,+ });++describe('fathomListCallsByParticipantHandler', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ mocks.listFathomConnectionsForRequest.mockResolvedValue([+ { id: 'connection-1', accessToken: 'token' },+ ]);+ });++ it('returns the calls whose invitees include the email, most recent first', async () => {+ mocks.listMeetings.mockImplementation(+ buildFathomMeetingPages([+ [+ {+ ...buildMeetingWith(1, '2026-08-18T10:00:00.000Z'),+ meetingUrl: null,+ },+ buildFathomMeeting({+ recordingId: 2,+ inviteeEmails: ['[email protected]'],+ }),+ buildMeetingWith(3, '2026-08-21T10:00:00.000Z'),+ ],+ ]),+ );++ expect(+ await fathomListCallsByParticipantHandler(+ { participantEmail: ' [email protected] ' },+ CONTEXT,+ ),+ ).toEqual({+ success: true,+ count: 2,+ calls: [+ {+ recordingId: 3,+ title: 'Meeting 3',+ startedAt: '2026-08-21T10:00:00.000Z',+ durationMinutes: 30,+ participants: ['[email protected]', '[email protected]'],+ recordedBy: '[email protected]',+ fathomUrl: 'https://fathom.video/calls/3',+ meetingUrl: 'https://meet.example.com/customer-call',+ },+ expect.not.objectContaining({ meetingUrl: expect.anything() }),+ ],+ });+ });++ it('merges the calls seen by several connected accounts without duplicates', async () => {+ mocks.listFathomConnectionsForRequest.mockResolvedValue([+ { id: 'connection-1', accessToken: 'token-1' },+ { id: 'connection-2', accessToken: 'token-2' },+ ]);+ mocks.listMeetings+ .mockImplementationOnce(+ buildFathomMeetingPages([+ [buildMeetingWith(1, '2026-08-18T10:00:00.000Z')],+ ]),+ )+ .mockImplementationOnce(+ buildFathomMeetingPages([+ [+ buildMeetingWith(1, '2026-08-18T10:00:00.000Z'),+ buildMeetingWith(2, '2026-08-19T10:00:00.000Z'),+ ],+ ]),+ );++ expect(+ await fathomListCallsByParticipantHandler(+ { participantEmail: '[email protected]' },+ buildLogicFunctionExecutionContext(null),+ ),+ ).toEqual(+ expect.objectContaining({+ count: 2,+ calls: [+ expect.objectContaining({ recordingId: 2 }),+ expect.objectContaining({ recordingId: 1 }),+ ],+ }),+ );+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-register-connection.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-register-connection.test.tsindex b9040af793f..f4c17f9cd5d 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-register-connection.test.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-register-connection.test.ts@@ -4,10 +4,12 @@ import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';import { buildFathomNotFoundError } from 'src/__tests__/utils/build-fathom-not-found-error.util';import { buildFathomServerError } from 'src/__tests__/utils/build-fathom-server-error.util';+import { FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';const sdkMocks = vi.hoisted(() => ({createWebhook: vi.fn(),deleteWebhook: vi.fn(),+ enqueueJobs: vi.fn(),getConnection: vi.fn(),kvGet: vi.fn(),kvSet: vi.fn(),@@ -20,6 +22,7 @@ vi.mock('twenty-sdk/define', () => ({vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({...(await importOriginal<typeof import('twenty-sdk/logic-function')>()),kv: { get: sdkMocks.kvGet, set: sdkMocks.kvSet },+ enqueueJobs: sdkMocks.enqueueJobs,getConnection: sdkMocks.getConnection,}));@@ -40,17 +43,36 @@ const HOOK_PAYLOAD = {};const failRegistrationWrite = (error: Error) => {- sdkMocks.kvSet.mockImplementation((key: string) =>- key.startsWith('fathom-webhook:')- ? Promise.reject(error)- : Promise.resolve(),- );+ let hasFailed = false;++ sdkMocks.kvSet.mockImplementation((key: string) => {+ if (hasFailed || !key.startsWith('fathom-webhook:')) {+ return Promise.resolve();+ }++ hasFailed = true;++ return Promise.reject(error);+ });};const INACTIVE_REGISTRATION = {webhookId: 'stale-webhook',secret: 'secret',isActive: false,+ isInitialBackfillEnqueued: true,+};++const ACTIVE_REGISTRATION = {+ ...INACTIVE_REGISTRATION,+ webhookId: 'existing-webhook',+ isActive: true,+};++const INITIAL_BACKFILL_JOB = {+ logicFunctionUniversalIdentifier: FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+ payloads: [{ connectedAccountId: 'connection-1', days: 31 }],+ retryLimit: 3,};describe('fathomRegisterConnectionHandler', () => {@@ -64,6 +86,7 @@ describe('fathomRegisterConnectionHandler', () => {id: 'webhook-1',secret: 'secret-1',});+ sdkMocks.enqueueJobs.mockResolvedValue({ enqueued: true });});it('claims the connection and registers a webhook pointing at the server route', async () => {@@ -86,6 +109,38 @@ describe('fathomRegisterConnectionHandler', () => {webhookId: 'webhook-1',secret: 'secret-1',isActive: true,+ isInitialBackfillEnqueued: false,+ });+ });++ it('starts the initial import once the registration is stored', async () => {+ await fathomRegisterConnectionHandler(HOOK_PAYLOAD);++ expect(sdkMocks.enqueueJobs).toHaveBeenCalledWith(INITIAL_BACKFILL_JOB);+ expect(sdkMocks.kvSet).toHaveBeenLastCalledWith(+ 'fathom-webhook:connection-1',+ expect.objectContaining({+ webhookId: 'webhook-1',+ isInitialBackfillEnqueued: true,+ }),+ );+ });++ it('enqueues the initial import on retry when the active registration is still missing it', async () => {+ sdkMocks.kvGet.mockResolvedValue({+ ...ACTIVE_REGISTRATION,+ isInitialBackfillEnqueued: false,+ });++ expect(await fathomRegisterConnectionHandler(HOOK_PAYLOAD)).toEqual({+ success: true,+ webhookId: 'existing-webhook',+ });+ expect(sdkMocks.createWebhook).not.toHaveBeenCalled();+ expect(sdkMocks.enqueueJobs).toHaveBeenCalledWith(INITIAL_BACKFILL_JOB);+ expect(sdkMocks.kvSet).toHaveBeenCalledWith('fathom-webhook:connection-1', {+ ...ACTIVE_REGISTRATION,+ isInitialBackfillEnqueued: true,});});@@ -120,6 +175,7 @@ describe('fathomRegisterConnectionHandler', () => {webhookId: 'webhook-1',secret: 'secret-1',isActive: true,+ isInitialBackfillEnqueued: false,});expect(await fathomRegisterConnectionHandler(HOOK_PAYLOAD)).toEqual({@@ -139,17 +195,15 @@ describe('fathomRegisterConnectionHandler', () => {});it('reuses the webhook of an already active registration', async () => {- sdkMocks.kvGet.mockResolvedValue({- ...INACTIVE_REGISTRATION,- webhookId: 'existing-webhook',- isActive: true,- });+ sdkMocks.kvGet.mockResolvedValue(ACTIVE_REGISTRATION);expect(await fathomRegisterConnectionHandler(HOOK_PAYLOAD)).toEqual({success: true,webhookId: 'existing-webhook',});expect(sdkMocks.createWebhook).not.toHaveBeenCalled();+ expect(sdkMocks.enqueueJobs).not.toHaveBeenCalled();+ expect(sdkMocks.kvSet).not.toHaveBeenCalled();});it('replaces an inactive registration whose webhook Fathom already dropped', async () => {diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-batch.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-batch.tsnew file mode 100644index 00000000000..fd35c51c735--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-batch.ts@@ -0,0 +1,77 @@+import { CoreApiClient } from 'twenty-client-sdk/core';+import { defineLogicFunction } from 'twenty-sdk/define';+import {+ getConnection,+ RetryableLogicFunctionError,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'src/utils/is-defined';++import { FATHOM_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { type SerializedFathomMeeting } from 'src/logic-functions/types/serialized-fathom-meeting.type';+import { createFathomClient } from 'src/logic-functions/utils/create-fathom-client.util';+import { hydrateFathomMeeting } from 'src/logic-functions/utils/hydrate-fathom-meeting.util';+import { isTransientFathomError } from 'src/logic-functions/utils/is-transient-fathom-error.util';+import { syncFathomMeetingToCallRecording } from 'src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util';+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';++export const fathomBackfillBatchHandler = async (payload: {+ connectedAccountId: string;+ meetings: SerializedFathomMeeting[];+}) => {+ const connection = await getConnection(payload.connectedAccountId);+ const fathomClient = createFathomClient(connection.accessToken);+ const coreApiClient = new CoreApiClient({ runAs: 'application' });+ const results = [];++ // Sequential on purpose: the batch is the unit of pacing against Fathom.+ for (const serializedMeeting of payload.meetings) {+ const meeting = await hydrateFathomMeeting({+ fathomClient,+ serializedMeeting,+ }).catch((error: unknown) => {+ // Only a RetryableLogicFunctionError makes the platform retry, so a rate+ // limit or a Fathom outage is rethrown as one.+ if (isTransientFathomError(error)) {+ throw new RetryableLogicFunctionError(toErrorMessage(error));+ }++ // One unreadable recording must not cost the rest of the batch.+ console.error(+ `[fathom] skipped recording ${serializedMeeting.recordingId}: ${toErrorMessage(error)}`,+ );++ return undefined;+ });++ if (!isDefined(meeting)) {+ continue;+ }++ // A failed upsert retries the whole batch. The replay re-fetches the+ // meetings already imported, which costs calls but cannot duplicate+ // records: the CallRecording id is derived from the recording.+ results.push(+ await syncFathomMeetingToCallRecording({ coreApiClient, meeting }).catch(+ (error: unknown) => {+ throw new RetryableLogicFunctionError(toErrorMessage(error));+ },+ ),+ );+ }++ return {+ success: true,+ importedMeetingCount: results.length,+ failedMeetingCount: payload.meetings.length - results.length,+ results,+ };+};++export default defineLogicFunction({+ universalIdentifier: FATHOM_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER,+ name: 'fathom-backfill-batch',+ description:+ 'Fetches the transcript and summary of one paced batch of Fathom meetings and upserts their CallRecordings.',+ timeoutSeconds: 300,+ handler: fathomBackfillBatchHandler,+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-worker.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-worker.tsnew file mode 100644index 00000000000..57a7d4b9293--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill-worker.ts@@ -0,0 +1,127 @@+import { isNonEmptyString } from '@sniptt/guards';+import { CoreApiClient } from 'twenty-client-sdk/core';+import { defineLogicFunction } from 'twenty-sdk/define';+import { getConnection } from 'twenty-sdk/logic-function';+import { isDefined } from 'src/utils/is-defined';++import {+ FATHOM_BACKFILL_BATCH_SIZE,+ MAX_FATHOM_BACKFILL_PAGES,+ MILLISECONDS_PER_DAY,+} from 'src/constants/fathom.constant';+import {+ FATHOM_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER,+ FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';+import { type FathomBackfillWorkerPayload } from 'src/logic-functions/types/fathom-backfill-worker-payload.type';+import { createFathomClient } from 'src/logic-functions/utils/create-fathom-client.util';+import { excludeDeletedFathomMeetings } from 'src/logic-functions/utils/exclude-deleted-fathom-meetings.util';+import { enqueueFathomJobOrThrow } from 'src/logic-functions/utils/enqueue-fathom-job-or-throw.util';+import { listFathomMeetingPage } from 'src/logic-functions/utils/list-fathom-meeting-page.util';+import { reserveFathomBackfillBatchSlots } from 'src/logic-functions/utils/reserve-fathom-backfill-batch-slots.util';+import { serializeFathomMeeting } from 'src/logic-functions/utils/serialize-fathom-meeting.util';+import { chunkIntoBatches } from 'src/utils/chunk-into-batches.util';++const getCreatedAfter = ({+ payload,+ now,+}: {+ payload: FathomBackfillWorkerPayload;+ now: number;+}): string => {+ if (isNonEmptyString(payload.createdAfter)) {+ return payload.createdAfter;+ }++ if (isDefined(payload.days) && Number.isInteger(payload.days)) {+ return new Date(now - payload.days * MILLISECONDS_PER_DAY).toISOString();+ }++ throw new Error('Fathom backfill worker requires a days window');+};++export const fathomBackfillWorkerHandler = async (+ payload: FathomBackfillWorkerPayload,+) => {+ if (!isNonEmptyString(payload.connectedAccountId)) {+ throw new Error('Fathom backfill worker requires a connectedAccountId');+ }++ const createdAfter = getCreatedAfter({ payload, now: Date.now() });+ const pageIndex = payload.pageIndex ?? 0;+ const connection = await getConnection(payload.connectedAccountId);+ const meetingPage = await listFathomMeetingPage({+ fathomClient: createFathomClient(connection.accessToken),+ createdAfter,+ cursor: payload.cursor,+ });+ const serializedMeetings = meetingPage.meetings.map(serializeFathomMeeting);+ const importableMeetings = await excludeDeletedFathomMeetings({+ coreApiClient: new CoreApiClient({ runAs: 'application' }),+ meetings: serializedMeetings,+ });+ const meetingBatches = chunkIntoBatches(+ importableMeetings,+ FATHOM_BACKFILL_BATCH_SIZE,+ );+ const { batchDelays, continuationDelay } =+ await reserveFathomBackfillBatchSlots({+ connectedAccountId: payload.connectedAccountId,+ batchCount: meetingBatches.length,+ });++ for (const [batchIndex, meetings] of meetingBatches.entries()) {+ await enqueueFathomJobOrThrow({+ logicFunctionUniversalIdentifier:+ FATHOM_BACKFILL_BATCH_UNIVERSAL_IDENTIFIER,+ payload: { connectedAccountId: payload.connectedAccountId, meetings },+ delayMs: batchDelays[batchIndex],+ });+ }++ // A cursor that repeats or cycles would chain this worker forever; the page+ // bound is far above any real history and only exists to end such a chain.+ const hasMoreMeetings =+ isNonEmptyString(meetingPage.nextCursor) &&+ meetingPage.nextCursor !== payload.cursor;+ const isPageBoundReached = pageIndex + 1 >= MAX_FATHOM_BACKFILL_PAGES;++ if (hasMoreMeetings && isPageBoundReached) {+ console.error(+ `[fathom] backfill for connected account ${payload.connectedAccountId} stopped after ${MAX_FATHOM_BACKFILL_PAGES} pages with cursor ${meetingPage.nextCursor} still pending`,+ );+ }++ if (hasMoreMeetings && !isPageBoundReached) {+ await enqueueFathomJobOrThrow({+ logicFunctionUniversalIdentifier:+ FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+ payload: {+ connectedAccountId: payload.connectedAccountId,+ createdAfter,+ cursor: meetingPage.nextCursor,+ pageIndex: pageIndex + 1,+ },+ delayMs: continuationDelay,+ });+ }++ return {+ success: true,+ createdAfter,+ discoveredMeetingCount: meetingPage.meetings.length,+ skippedDeletedMeetingCount:+ serializedMeetings.length - importableMeetings.length,+ enqueuedBatchCount: meetingBatches.length,+ hasMoreMeetings: hasMoreMeetings && !isPageBoundReached,+ };+};++export default defineLogicFunction({+ universalIdentifier: FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+ name: 'fathom-backfill-worker',+ description:+ "Discovers one page of Fathom meetings, schedules paced import batches, and continues from Fathom's cursor.",+ timeoutSeconds: 120,+ handler: fathomBackfillWorkerHandler,+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill.tsnew file mode 100644index 00000000000..544927a603a--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-backfill.ts@@ -0,0 +1,65 @@+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';+import { isDefined } from 'src/utils/is-defined';++import {+ FATHOM_BACKFILL_MAX_WINDOW_DAYS,+ FATHOM_BACKFILL_ROUTE_PATH,+} from 'src/constants/fathom.constant';+import { FATHOM_BACKFILL_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { enqueueFathomBackfillWorker } from 'src/logic-functions/utils/enqueue-fathom-backfill-worker.util';+import { findFathomConnectionForRequester } from 'src/logic-functions/utils/find-fathom-connection-for-requester.util';++type FathomBackfillResult =+ | { success: true; connectedAccountId: string; days: number }+ | { success: false; error: string };++export const fathomBackfillHandler = async (+ routePayload: RoutePayload<{ days?: unknown }>,+ context: LogicFunctionExecutionContext,+): Promise<FathomBackfillResult> => {+ const days = routePayload.body?.days;++ if (+ typeof days !== 'number' ||+ !Number.isInteger(days) ||+ days < 1 ||+ days > FATHOM_BACKFILL_MAX_WINDOW_DAYS+ ) {+ return {+ success: false,+ error: `Fathom backfill requires a days window between 1 and ${FATHOM_BACKFILL_MAX_WINDOW_DAYS}`,+ };+ }++ const connection = await findFathomConnectionForRequester(context);++ if (!isDefined(connection)) {+ return {+ success: false,+ error:+ 'Fathom is not connected for this user. Open the Fathom app settings and add a connection first.',+ };+ }++ await enqueueFathomBackfillWorker({+ connectedAccountId: connection.id,+ days,+ });++ return { success: true, connectedAccountId: connection.id, days };+};++export default defineLogicFunction({+ universalIdentifier: FATHOM_BACKFILL_UNIVERSAL_IDENTIFIER,+ name: 'fathom-backfill',+ description:+ "Starts a Fathom history import through the requesting user's connected account.",+ timeoutSeconds: 15,+ handler: fathomBackfillHandler,+ httpRouteTriggerSettings: {+ path: FATHOM_BACKFILL_ROUTE_PATH,+ httpMethod: 'POST',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-list-calls-by-participant.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-list-calls-by-participant.tsnew file mode 100644index 00000000000..d336a4026ec--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-list-calls-by-participant.ts@@ -0,0 +1,148 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type Meeting } from 'fathom-typescript/sdk/models/shared';+import { defineLogicFunction } from 'twenty-sdk/define';+import {+ type InputJsonSchema,+ jsonSchemaToInputSchema,+ type LogicFunctionExecutionContext,+} from 'twenty-sdk/logic-function';++import { FATHOM_LIST_CALLS_BY_PARTICIPANT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { type FathomCallSummary } from 'src/logic-functions/types/fathom-call-summary.type';+import { createFathomClient } from 'src/logic-functions/utils/create-fathom-client.util';+import { doesFathomMeetingIncludeInvitee } from 'src/logic-functions/utils/does-fathom-meeting-include-invitee.util';+import { listFathomConnectionsForRequest } from 'src/logic-functions/utils/list-fathom-connections-for-request.util';+import { listFathomMeetings } from 'src/logic-functions/utils/list-fathom-meetings.util';+import { mapFathomMeetingToCallSummary } from 'src/logic-functions/utils/map-fathom-meeting-to-call-summary.util';++const DEFAULT_RESULT_LIMIT = 10;+const MAXIMUM_RESULT_LIMIT = 50;++const fathomListCallsByParticipantInputSchema: InputJsonSchema = {+ type: 'object',+ properties: {+ participantEmail: {+ type: 'string',+ label: 'Participant email',+ description:+ 'Email address of a calendar invitee. Returns the Fathom recordings whose invitees include this email, most recent first.',+ },+ limit: {+ type: 'integer',+ label: 'Maximum number of calls',+ description: `Optional. Defaults to ${DEFAULT_RESULT_LIMIT}, capped at ${MAXIMUM_RESULT_LIMIT}.`,+ minimum: 1,+ maximum: MAXIMUM_RESULT_LIMIT,+ },+ },+ required: ['participantEmail'],+ additionalProperties: false,+};++type FathomListCallsByParticipantResult =+ | { success: true; count: number; calls: FathomCallSummary[] }+ | { success: false; error: string };++const clampLimit = (limit: unknown): number =>+ typeof limit === 'number' && Number.isFinite(limit)+ ? Math.max(1, Math.min(MAXIMUM_RESULT_LIMIT, Math.trunc(limit)))+ : DEFAULT_RESULT_LIMIT;++export const fathomListCallsByParticipantHandler = async (+ parameters: { participantEmail?: unknown; limit?: unknown },+ context: LogicFunctionExecutionContext,+): Promise<FathomListCallsByParticipantResult> => {+ const participantEmail =+ typeof parameters.participantEmail === 'string'+ ? parameters.participantEmail.trim().toLowerCase()+ : '';++ if (!isNonEmptyString(participantEmail)) {+ return { success: false, error: 'participantEmail is required' };+ }++ const limit = clampLimit(parameters.limit);+ const connections = await listFathomConnectionsForRequest(context);++ if (connections.length === 0) {+ return {+ success: false,+ error:+ 'Fathom is not connected for this user. Open the Fathom app settings and add a connection first.',+ };+ }++ const hasParticipant = (meeting: Meeting): boolean =>+ doesFathomMeetingIncludeInvitee({+ meeting,+ normalizedInviteeEmail: participantEmail,+ });+ const matchingMeetingsByRecordingId = new Map<number, Meeting>();++ for (const connection of connections) {+ const meetings = await listFathomMeetings({+ fathomClient: createFathomClient(connection.accessToken),+ stopWhen: (listedMeetings) =>+ listedMeetings.filter(hasParticipant).length >= limit,+ });++ for (const meeting of meetings.filter(hasParticipant)) {+ matchingMeetingsByRecordingId.set(meeting.recordingId, meeting);+ }+ }++ const calls = [...matchingMeetingsByRecordingId.values()]+ .sort(+ (firstMeeting, secondMeeting) =>+ secondMeeting.recordingStartTime.getTime() -+ firstMeeting.recordingStartTime.getTime(),+ )+ .slice(0, limit)+ .map(mapFathomMeetingToCallSummary);++ return { success: true, count: calls.length, calls };+};++export default defineLogicFunction({+ universalIdentifier: FATHOM_LIST_CALLS_BY_PARTICIPANT_UNIVERSAL_IDENTIFIER,+ name: 'fathom-list-calls-by-participant',+ description:+ 'List accessible Fathom recordings whose calendar invitees include a given email. Returns each recording ID, title, start time, duration, participants, recorder, Fathom URL and meeting URL. Use the recordingId with Sync Fathom Call.',+ timeoutSeconds: 30,+ handler: fathomListCallsByParticipantHandler,+ toolTriggerSettings: {+ inputSchema: fathomListCallsByParticipantInputSchema,+ },+ workflowActionTriggerSettings: {+ label: 'List Fathom Calls By Participant',+ inputSchema: jsonSchemaToInputSchema(+ fathomListCallsByParticipantInputSchema,+ ),+ outputSchema: [+ {+ type: 'object',+ properties: {+ success: { type: 'boolean' },+ error: { type: 'string' },+ count: { type: 'number' },+ calls: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ recordingId: { type: 'number' },+ title: { type: 'string' },+ startedAt: { type: 'string' },+ durationMinutes: { type: 'number' },+ participants: { type: 'array', items: { type: 'string' } },+ recordedBy: { type: 'string' },+ fathomUrl: { type: 'string' },+ meetingUrl: { type: 'string' },+ },+ },+ },+ },+ },+ ],+ },+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-register-connection.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-register-connection.tsindex 92ed80b1d24..6e4c5f29687 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-register-connection.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-register-connection.ts@@ -7,11 +7,13 @@ import {} from 'twenty-sdk/logic-function';import { isDefined } from 'src/utils/is-defined';+import { FATHOM_INITIAL_BACKFILL_DAYS } from 'src/constants/fathom.constant';import { FATHOM_REGISTER_CONNECTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';import { type FathomConnectionHookPayload } from 'src/logic-functions/types/fathom-connection-hook-payload.type';import { type FathomWebhookRegistration } from 'src/logic-functions/types/fathom-webhook-registration.type';import { createFathomClient } from 'src/logic-functions/utils/create-fathom-client.util';import { deleteStaleFathomWebhook } from 'src/logic-functions/utils/delete-stale-fathom-webhook.util';+import { enqueueFathomBackfillWorker } from 'src/logic-functions/utils/enqueue-fathom-backfill-worker.util';import { getFathomConnectionClaimKey } from 'src/logic-functions/utils/get-fathom-connection-claim-key.util';import { getFathomWebhookDestinationUrl } from 'src/logic-functions/utils/get-fathom-webhook-destination-url.util';import { getFathomWebhookRegistrationKey } from 'src/logic-functions/utils/get-fathom-webhook-registration-key.util';@@ -19,6 +21,31 @@ import { isTransientFathomError } from 'src/logic-functions/utils/is-transient-fimport { storeFathomWebhookRegistration } from 'src/logic-functions/utils/store-fathom-webhook-registration.util';import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';+// The hook retries as a whole, so the flag keeps a retry after a failed enqueue+// from skipping the import behind the already active registration.+const enqueueInitialBackfillOnce = async ({+ connectedAccountId,+ registrationKey,+ registration,+}: {+ connectedAccountId: string;+ registrationKey: string;+ registration: FathomWebhookRegistration;+}): Promise<void> => {+ if (registration.isInitialBackfillEnqueued) {+ return;+ }++ await enqueueFathomBackfillWorker({+ connectedAccountId,+ days: FATHOM_INITIAL_BACKFILL_DAYS,+ });+ await kv.set(registrationKey, {+ ...registration,+ isInitialBackfillEnqueued: true,+ });+};+export const fathomRegisterConnectionHandler = async (payload: FathomConnectionHookPayload,): Promise<{ success: true; webhookId: string }> => {@@ -43,6 +70,12 @@ export const fathomRegisterConnectionHandler = async (await kv.get<FathomWebhookRegistration>(registrationKey);if (existingRegistration?.isActive) {+ await enqueueInitialBackfillOnce({+ connectedAccountId: payload.connectedAccountId,+ registrationKey,+ registration: existingRegistration,+ });+return { success: true, webhookId: existingRegistration.webhookId };}@@ -80,15 +113,23 @@ export const fathomRegisterConnectionHandler = async (throw error;});+ const registration: FathomWebhookRegistration = {+ webhookId: webhook.id,+ secret: webhook.secret,+ isActive: true,+ isInitialBackfillEnqueued: false,+ };+await storeFathomWebhookRegistration({fathomClient,connectedAccountId: payload.connectedAccountId,registrationKey,- registration: {- webhookId: webhook.id,- secret: webhook.secret,- isActive: true,- },+ registration,+ });+ await enqueueInitialBackfillOnce({+ connectedAccountId: payload.connectedAccountId,+ registrationKey,+ registration,});return { success: true, webhookId: webhook.id };@@ -98,7 +139,7 @@ export default defineLogicFunction({universalIdentifier: FATHOM_REGISTER_CONNECTION_UNIVERSAL_IDENTIFIER,name: 'fathom-register-connection',description:- "Registers a Fathom webhook using the connected account's permissions.",+ "Registers a Fathom webhook using the connected account's permissions and starts the initial history import.",timeoutSeconds: 30,handler: fathomRegisterConnectionHandler,});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-sync-call.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-sync-call.tsnew file mode 100644index 00000000000..b2b8ffeb644--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-sync-call.ts@@ -0,0 +1,119 @@+import { CoreApiClient } from 'twenty-client-sdk/core';+import { defineLogicFunction } from 'twenty-sdk/define';+import {+ type InputJsonSchema,+ jsonSchemaToInputSchema,+ type LogicFunctionExecutionContext,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'src/utils/is-defined';++import { FATHOM_SYNC_CALL_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { createFathomClient } from 'src/logic-functions/utils/create-fathom-client.util';+import { hydrateFathomMeeting } from 'src/logic-functions/utils/hydrate-fathom-meeting.util';+import { listFathomConnectionsForRequest } from 'src/logic-functions/utils/list-fathom-connections-for-request.util';+import { listFathomMeetings } from 'src/logic-functions/utils/list-fathom-meetings.util';+import { serializeFathomMeeting } from 'src/logic-functions/utils/serialize-fathom-meeting.util';+import { syncFathomMeetingToCallRecording } from 'src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util';++const fathomSyncCallInputSchema: InputJsonSchema = {+ type: 'object',+ properties: {+ recordingId: {+ type: 'integer',+ label: 'Fathom recording ID',+ description:+ 'The numeric recording_id of the Fathom meeting, as returned by List Fathom Calls By Participant or shown at the end of the Fathom call URL.',+ },+ },+ required: ['recordingId'],+ additionalProperties: false,+};++type FathomSyncCallResult =+ | {+ success: true;+ recordingId: number;+ callRecordingId: string;+ calendarEventId?: string;+ created: boolean;+ }+ | { success: false; error: string };++export const fathomSyncCallHandler = async (+ parameters: { recordingId?: unknown },+ context: LogicFunctionExecutionContext,+): Promise<FathomSyncCallResult> => {+ const recordingId = parameters.recordingId;++ if (typeof recordingId !== 'number' || !Number.isSafeInteger(recordingId)) {+ return { success: false, error: 'recordingId must be an integer' };+ }++ const connections = await listFathomConnectionsForRequest(context);++ if (connections.length === 0) {+ return {+ success: false,+ error:+ 'Fathom is not connected for this user. Open the Fathom app settings and add a connection first.',+ };+ }++ for (const connection of connections) {+ const fathomClient = createFathomClient(connection.accessToken);+ const meetings = await listFathomMeetings({+ fathomClient,+ stopWhen: (listedMeetings) =>+ listedMeetings.some((meeting) => meeting.recordingId === recordingId),+ });+ const meeting = meetings.find(+ (listedMeeting) => listedMeeting.recordingId === recordingId,+ );++ if (!isDefined(meeting)) {+ continue;+ }++ const syncResult = await syncFathomMeetingToCallRecording({+ coreApiClient: new CoreApiClient({ runAs: 'application' }),+ meeting: await hydrateFathomMeeting({+ fathomClient,+ serializedMeeting: serializeFathomMeeting(meeting),+ }),+ });++ return { success: true, recordingId, ...syncResult };+ }++ return {+ success: false,+ error: `No accessible Fathom recording found for ${recordingId}`,+ };+};++export default defineLogicFunction({+ universalIdentifier: FATHOM_SYNC_CALL_UNIVERSAL_IDENTIFIER,+ name: 'fathom-sync-call',+ description:+ 'Sync one Fathom recording into a CallRecording on demand: fetches its transcript, summary and action items and upserts them onto the record linked to the matching CalendarEvent. Useful to recover a missed webhook or to sync from a workflow.',+ timeoutSeconds: 60,+ handler: fathomSyncCallHandler,+ toolTriggerSettings: { inputSchema: fathomSyncCallInputSchema },+ workflowActionTriggerSettings: {+ label: 'Sync Fathom Call',+ inputSchema: jsonSchemaToInputSchema(fathomSyncCallInputSchema),+ outputSchema: [+ {+ type: 'object',+ properties: {+ success: { type: 'boolean' },+ error: { type: 'string' },+ recordingId: { type: 'number' },+ callRecordingId: { type: 'string' },+ calendarEventId: { type: 'string' },+ created: { type: 'boolean' },+ },+ },+ ],+ },+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-backfill-worker-payload.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-backfill-worker-payload.type.tsnew file mode 100644index 00000000000..fbd9856379f--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-backfill-worker-payload.type.ts@@ -0,0 +1,7 @@+export type FathomBackfillWorkerPayload = {+ connectedAccountId: string;+ days?: number;+ createdAfter?: string;+ cursor?: string;+ pageIndex?: number;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-call-summary.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-call-summary.type.tsnew file mode 100644index 00000000000..40622f592af--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-call-summary.type.ts@@ -0,0 +1,10 @@+export type FathomCallSummary = {+ recordingId: number;+ title: string;+ startedAt: string;+ durationMinutes: number;+ participants: string[];+ recordedBy: string;+ fathomUrl: string;+ meetingUrl?: string;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-meeting-lister.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-meeting-lister.type.tsnew file mode 100644index 00000000000..d4caad0d2cf--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-meeting-lister.type.ts@@ -0,0 +1,10 @@+import { type ListMeetingsRequest } from 'fathom-typescript/sdk/models/operations';+import { type MeetingListResponse } from 'fathom-typescript/sdk/models/shared';++// The page utilities read one response at a time, so a test double does not+// have to implement the SDK's async page iterator.+export type FathomMeetingLister = {+ listMeetings: (+ request: ListMeetingsRequest,+ ) => Promise<{ result: MeetingListResponse }>;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-webhook-registration.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-webhook-registration.type.tsindex 5bad12c8b13..a4f5b0b86d8 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-webhook-registration.type.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-webhook-registration.type.ts@@ -2,4 +2,5 @@ export type FathomWebhookRegistration = {webhookId: string;secret: string;isActive: boolean;+ isInitialBackfillEnqueued: boolean;};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/serialized-fathom-meeting.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/serialized-fathom-meeting.type.tsnew file mode 100644index 00000000000..e038e494cae--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/serialized-fathom-meeting.type.ts@@ -0,0 +1,20 @@+import { type Meeting } from 'fathom-typescript/sdk/models/shared';++// Job payloads travel as JSON, so the Date fields of a Meeting are carried as+// ISO strings and the artifacts fetched separately are left out.+export type SerializedFathomMeeting = Omit<+ Meeting,+ | 'createdAt'+ | 'scheduledStartTime'+ | 'scheduledEndTime'+ | 'recordingStartTime'+ | 'recordingEndTime'+ | 'transcript'+ | 'defaultSummary'+> & {+ createdAt: string;+ scheduledStartTime: string;+ scheduledEndTime: string;+ recordingStartTime: string;+ recordingEndTime: string;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/list-fathom-connections-for-request.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/list-fathom-connections-for-request.test.tsnew file mode 100644index 00000000000..5cd161fd266--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/list-fathom-connections-for-request.test.ts@@ -0,0 +1,47 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { listFathomConnectionsForRequest } from 'src/logic-functions/utils/list-fathom-connections-for-request.util';++const sdkMocks = vi.hoisted(() => ({+ listConnections: vi.fn(),+}));++vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<typeof import('twenty-sdk/logic-function')>()),+ listConnections: sdkMocks.listConnections,+}));++const buildConnection = (id: string, userWorkspaceId: string) => ({+ id,+ visibility: 'user',+ userWorkspaceId,+ accessToken: `token-${id}`,+});++const CONNECTIONS = [+ buildConnection('connection-1', 'user-workspace-1'),+ buildConnection('connection-2', 'user-workspace-2'),+];++describe('listFathomConnectionsForRequest', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ sdkMocks.listConnections.mockResolvedValue(CONNECTIONS);+ });++ it('returns every connected account for a run with nobody behind it', async () => {+ const sharedConnection = {+ ...buildConnection('connection-shared', 'user-workspace-1'),+ visibility: 'workspace',+ };++ sdkMocks.listConnections.mockResolvedValue([+ sharedConnection,+ ...CONNECTIONS,+ ]);++ expect(+ await listFathomConnectionsForRequest({ userWorkspaceId: null }),+ ).toEqual([sharedConnection, ...CONNECTIONS]);+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/list-fathom-meetings.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/list-fathom-meetings.test.tsnew file mode 100644index 00000000000..fab5abee28d--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/list-fathom-meetings.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it, vi } from 'vitest';++import { buildFathomMeeting } from 'src/__tests__/utils/build-fathom-meeting.util';+import { buildFathomMeetingPages } from 'src/__tests__/utils/build-fathom-meeting-pages.util';+import { MAX_FATHOM_MEETING_PAGES } from 'src/constants/fathom.constant';+import { listFathomMeetings } from 'src/logic-functions/utils/list-fathom-meetings.util';++describe('listFathomMeetings', () => {+ it('stops paging as soon as the caller is satisfied', async () => {+ const listMeetings = vi.fn(+ buildFathomMeetingPages([+ [buildFathomMeeting({ recordingId: 1 })],+ [buildFathomMeeting({ recordingId: 2 })],+ ]),+ );++ const meetings = await listFathomMeetings({+ fathomClient: { listMeetings },+ stopWhen: (listedMeetings) =>+ listedMeetings.some((meeting) => meeting.recordingId === 1),+ });++ expect(meetings.map((meeting) => meeting.recordingId)).toEqual([1]);+ expect(listMeetings).toHaveBeenCalledTimes(1);+ });++ it('gives up instead of walking an unbounded history', async () => {+ const listMeetings = vi.fn(async () => ({+ result: { items: [], limit: null, nextCursor: 'more' },+ }));++ await expect(+ listFathomMeetings({ fathomClient: { listMeetings } }),+ ).rejects.toThrow(`exceeded ${MAX_FATHOM_MEETING_PAGES} pages`);+ expect(listMeetings).toHaveBeenCalledTimes(MAX_FATHOM_MEETING_PAGES);+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fathom-client.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fathom-client.util.tsindex 59360af64b1..f85bd52fe44 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fathom-client.util.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fathom-client.util.ts@@ -1,4 +1,19 @@import { Fathom } from 'fathom-typescript';+import { FATHOM_REQUEST_RETRY_MAX_ELAPSED_MILLISECONDS } from 'src/constants/fathom.constant';++// The SDK default retries 429s for five minutes, past every function timeout here.export const createFathomClient = (accessToken: string): Fathom =>- new Fathom({ security: { bearerAuth: accessToken } });+ new Fathom({+ security: { bearerAuth: accessToken },+ retryConfig: {+ strategy: 'backoff',+ backoff: {+ initialInterval: 500,+ maxInterval: 10_000,+ exponent: 1.5,+ maxElapsedTime: FATHOM_REQUEST_RETRY_MAX_ELAPSED_MILLISECONDS,+ },+ retryConnectionErrors: false,+ },+ });diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/does-fathom-meeting-include-invitee.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/does-fathom-meeting-include-invitee.util.tsnew file mode 100644index 00000000000..79c57880865--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/does-fathom-meeting-include-invitee.util.ts@@ -0,0 +1,12 @@+import { type Meeting } from 'fathom-typescript/sdk/models/shared';++export const doesFathomMeetingIncludeInvitee = ({+ meeting,+ normalizedInviteeEmail,+}: {+ meeting: Pick<Meeting, 'calendarInvitees'>;+ normalizedInviteeEmail: string;+}): boolean =>+ meeting.calendarInvitees.some(+ (invitee) => invitee.email?.trim().toLowerCase() === normalizedInviteeEmail,+ );diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-fathom-backfill-worker.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-fathom-backfill-worker.util.tsnew file mode 100644index 00000000000..3e2861e5893--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-fathom-backfill-worker.util.ts@@ -0,0 +1,15 @@+import { FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { enqueueFathomJobOrThrow } from 'src/logic-functions/utils/enqueue-fathom-job-or-throw.util';++export const enqueueFathomBackfillWorker = async ({+ connectedAccountId,+ days,+}: {+ connectedAccountId: string;+ days: number;+}): Promise<void> =>+ enqueueFathomJobOrThrow({+ logicFunctionUniversalIdentifier:+ FATHOM_BACKFILL_WORKER_UNIVERSAL_IDENTIFIER,+ payload: { connectedAccountId, days },+ });diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-fathom-job-or-throw.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-fathom-job-or-throw.util.tsnew file mode 100644index 00000000000..dc83d4f7a95--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/enqueue-fathom-job-or-throw.util.ts@@ -0,0 +1,24 @@+import { enqueueJobs, type EnqueueJobsInput } from 'twenty-sdk/logic-function';++import { FATHOM_BACKFILL_JOB_RETRY_LIMIT } from 'src/constants/fathom.constant';++// enqueueJobs applies one delayMs to every payload of a call, so each+// staggered batch goes through its own call.+export const enqueueFathomJobOrThrow = async ({+ payload,+ ...options+}: Pick<EnqueueJobsInput, 'logicFunctionUniversalIdentifier' | 'delayMs'> & {+ payload: Record<string, unknown>;+}): Promise<void> => {+ const enqueueResult = await enqueueJobs({+ ...options,+ payloads: [payload],+ retryLimit: FATHOM_BACKFILL_JOB_RETRY_LIMIT,+ });++ if (!enqueueResult.enqueued) {+ throw new Error(+ `Failed to enqueue Fathom job ${options.logicFunctionUniversalIdentifier}`,+ );+ }+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/exclude-deleted-fathom-meetings.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/exclude-deleted-fathom-meetings.util.tsnew file mode 100644index 00000000000..7a184a7b86c--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/exclude-deleted-fathom-meetings.util.ts@@ -0,0 +1,35 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { type SerializedFathomMeeting } from 'src/logic-functions/types/serialized-fathom-meeting.type';+import { computeCallRecordingIdForFathomMeeting } from 'src/logic-functions/utils/compute-call-recording-id-for-fathom-meeting.util';+import { listDeletedCallRecordingIds } from 'src/logic-functions/utils/list-deleted-call-recording-ids.util';++// A recording someone deleted stays deleted: its CallRecording id is derived+// from the Fathom recording, so importing it again would collide with the+// tombstone that still holds that id.+export const excludeDeletedFathomMeetings = async ({+ coreApiClient,+ meetings,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ meetings: SerializedFathomMeeting[];+}): Promise<SerializedFathomMeeting[]> => {+ const identifiedMeetings = meetings.map((meeting) => ({+ meeting,+ callRecordingId: computeCallRecordingIdForFathomMeeting(+ meeting.recordingId,+ ),+ }));+ const deletedCallRecordingIds = await listDeletedCallRecordingIds({+ coreApiClient,+ callRecordingIds: identifiedMeetings.map(+ ({ callRecordingId }) => callRecordingId,+ ),+ });++ return identifiedMeetings+ .filter(+ ({ callRecordingId }) => !deletedCallRecordingIds.has(callRecordingId),+ )+ .map(({ meeting }) => meeting);+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/find-fathom-connection-for-requester.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/find-fathom-connection-for-requester.util.tsnew file mode 100644index 00000000000..5c7c94c7043--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/find-fathom-connection-for-requester.util.ts@@ -0,0 +1,12 @@+import {+ type AppConnection,+ findConnectionForRequest,+ type LogicFunctionExecutionContext,+} from 'twenty-sdk/logic-function';++import { listFathomConnections } from 'src/logic-functions/utils/list-fathom-connections.util';++export const findFathomConnectionForRequester = async (+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+): Promise<AppConnection | null> =>+ findConnectionForRequest(await listFathomConnections(), context);diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-backfill-schedule-key.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-backfill-schedule-key.util.tsnew file mode 100644index 00000000000..3644176f79d--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-backfill-schedule-key.util.ts@@ -0,0 +1,3 @@+export const getFathomBackfillScheduleKey = (+ connectedAccountId: string,+): string => `fathom-backfill-schedule:${connectedAccountId}`;diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-meeting-title.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-meeting-title.util.tsnew file mode 100644index 00000000000..ec5882870e6--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-meeting-title.util.ts@@ -0,0 +1,10 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type Meeting } from 'fathom-typescript/sdk/models/shared';++export const getFathomMeetingTitle = (+ meeting: Pick<Meeting, 'meetingTitle' | 'title'>,+): string => {+ const meetingTitle = meeting.meetingTitle?.trim();++ return isNonEmptyString(meetingTitle) ? meetingTitle : meeting.title.trim();+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/hydrate-fathom-meeting.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/hydrate-fathom-meeting.util.tsnew file mode 100644index 00000000000..125e7efb697--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/hydrate-fathom-meeting.util.ts@@ -0,0 +1,36 @@+import { type Fathom } from 'fathom-typescript';+import { type Meeting } from 'fathom-typescript/sdk/models/shared';++import { type SerializedFathomMeeting } from 'src/logic-functions/types/serialized-fathom-meeting.type';++export const hydrateFathomMeeting = async ({+ fathomClient,+ serializedMeeting,+}: {+ fathomClient: Pick<Fathom, 'getRecordingTranscript' | 'getRecordingSummary'>;+ serializedMeeting: SerializedFathomMeeting;+}): Promise<Meeting> => {+ const [transcriptResponse, summaryResponse] = await Promise.all([+ fathomClient.getRecordingTranscript({+ recordingId: serializedMeeting.recordingId,+ }),+ fathomClient.getRecordingSummary({+ recordingId: serializedMeeting.recordingId,+ }),+ ]);++ return {+ ...serializedMeeting,+ createdAt: new Date(serializedMeeting.createdAt),+ scheduledStartTime: new Date(serializedMeeting.scheduledStartTime),+ scheduledEndTime: new Date(serializedMeeting.scheduledEndTime),+ recordingStartTime: new Date(serializedMeeting.recordingStartTime),+ recordingEndTime: new Date(serializedMeeting.recordingEndTime),+ transcript:+ 'transcript' in transcriptResponse+ ? transcriptResponse.transcript+ : undefined,+ defaultSummary:+ 'summary' in summaryResponse ? summaryResponse.summary : undefined,+ };+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-deleted-call-recording-ids.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-deleted-call-recording-ids.util.tsnew file mode 100644index 00000000000..4b339ed995c--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-deleted-call-recording-ids.util.ts@@ -0,0 +1,49 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { CALL_RECORDING_IDS_PER_QUERY } from 'src/constants/fathom.constant';++// Ids are unique, so one page per chunk already returns every match.+export const listDeletedCallRecordingIds = async ({+ coreApiClient,+ callRecordingIds,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ callRecordingIds: string[];+}): Promise<Set<string>> => {+ const deletedCallRecordingIds = new Set<string>();++ for (+ let queryStart = 0;+ queryStart < callRecordingIds.length;+ queryStart += CALL_RECORDING_IDS_PER_QUERY+ ) {+ const queriedCallRecordingIds = callRecordingIds.slice(+ queryStart,+ queryStart + CALL_RECORDING_IDS_PER_QUERY,+ );++ const queryResult = await coreApiClient.query({+ callRecordings: {+ __args: {+ filter: {+ id: { in: queriedCallRecordingIds },+ deletedAt: { is: 'NOT_NULL' },+ },+ first: queriedCallRecordingIds.length,+ },+ edges: { node: { id: true } },+ },+ });++ for (const edge of queryResult.callRecordings?.edges ?? []) {+ const id = edge?.node?.id;++ if (isNonEmptyString(id)) {+ deletedCallRecordingIds.add(id);+ }+ }+ }++ return deletedCallRecordingIds;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-connections-for-request.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-connections-for-request.util.tsnew file mode 100644index 00000000000..dddabfaa360--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-connections-for-request.util.ts@@ -0,0 +1,25 @@+import {+ type AppConnection,+ findConnectionForRequest,+ type LogicFunctionExecutionContext,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'src/utils/is-defined';++import { listFathomConnections } from 'src/logic-functions/utils/list-fathom-connections.util';++// A person acts through their own Fathom account. A run with nobody behind it+// (database-event or cron workflow) sees the union of the connected accounts,+// which is what the webhooks already sync into the shared CallRecording object.+export const listFathomConnectionsForRequest = async (+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+): Promise<AppConnection[]> => {+ const connections = await listFathomConnections();++ if (!isDefined(context.userWorkspaceId)) {+ return connections;+ }++ const requesterConnection = findConnectionForRequest(connections, context);++ return isDefined(requesterConnection) ? [requesterConnection] : [];+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-connections.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-connections.util.tsnew file mode 100644index 00000000000..f4ba824a5db--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-connections.util.ts@@ -0,0 +1,6 @@+import { type AppConnection, listConnections } from 'twenty-sdk/logic-function';++import { FATHOM_PROVIDER_NAME } from 'src/constants/fathom.constant';++export const listFathomConnections = (): Promise<AppConnection[]> =>+ listConnections({ providerName: FATHOM_PROVIDER_NAME });diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-meeting-page.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-meeting-page.util.tsnew file mode 100644index 00000000000..86d2961f47c--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-meeting-page.util.ts@@ -0,0 +1,27 @@+import { type Meeting } from 'fathom-typescript/sdk/models/shared';+import { isDefined } from 'src/utils/is-defined';++import { type FathomMeetingLister } from 'src/logic-functions/types/fathom-meeting-lister.type';++export type FathomMeetingPage = {+ meetings: Meeting[];+ nextCursor: string | null;+};++export const listFathomMeetingPage = async ({+ fathomClient,+ createdAfter,+ cursor,+}: {+ fathomClient: FathomMeetingLister;+ createdAfter?: string;+ cursor?: string;+}): Promise<FathomMeetingPage> => {+ const { result } = await fathomClient.listMeetings({+ ...(isDefined(createdAfter) ? { createdAfter } : {}),+ ...(isDefined(cursor) ? { cursor } : {}),+ includeActionItems: true,+ });++ return { meetings: result.items, nextCursor: result.nextCursor };+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-meetings.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-meetings.util.tsnew file mode 100644index 00000000000..050f1c709cf--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-fathom-meetings.util.ts@@ -0,0 +1,42 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type Meeting } from 'fathom-typescript/sdk/models/shared';++import { MAX_FATHOM_MEETING_PAGES } from 'src/constants/fathom.constant';+import { type FathomMeetingLister } from 'src/logic-functions/types/fathom-meeting-lister.type';+import { listFathomMeetingPage } from 'src/logic-functions/utils/list-fathom-meeting-page.util';++// Fathom has no endpoint for one meeting, so on-demand lookups walk the list+// until the caller has what it needs; the page cap keeps a miss inside the+// logic function timeout.+export const listFathomMeetings = async ({+ fathomClient,+ createdAfter,+ stopWhen,+}: {+ fathomClient: FathomMeetingLister;+ createdAfter?: string;+ stopWhen?: (meetings: Meeting[]) => boolean;+}): Promise<Meeting[]> => {+ const meetings: Meeting[] = [];+ let cursor: string | undefined = undefined;++ for (let page = 0; page < MAX_FATHOM_MEETING_PAGES; page++) {+ const meetingPage = await listFathomMeetingPage({+ fathomClient,+ createdAfter,+ cursor,+ });++ meetings.push(...meetingPage.meetings);++ if (stopWhen?.(meetings) || !isNonEmptyString(meetingPage.nextCursor)) {+ return meetings;+ }++ cursor = meetingPage.nextCursor;+ }++ throw new Error(+ `Fathom meeting listing exceeded ${MAX_FATHOM_MEETING_PAGES} pages`,+ );+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/map-fathom-meeting-to-call-summary.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/map-fathom-meeting-to-call-summary.util.tsnew file mode 100644index 00000000000..6e20fa45965--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/map-fathom-meeting-to-call-summary.util.ts@@ -0,0 +1,28 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type Meeting } from 'fathom-typescript/sdk/models/shared';++import { type FathomCallSummary } from 'src/logic-functions/types/fathom-call-summary.type';+import { getFathomMeetingTitle } from 'src/logic-functions/utils/get-fathom-meeting-title.util';++const MILLISECONDS_PER_MINUTE = 60_000;++export const mapFathomMeetingToCallSummary = (+ meeting: Meeting,+): FathomCallSummary => ({+ recordingId: meeting.recordingId,+ title: getFathomMeetingTitle(meeting),+ startedAt: meeting.recordingStartTime.toISOString(),+ durationMinutes: Math.round(+ (meeting.recordingEndTime.getTime() -+ meeting.recordingStartTime.getTime()) /+ MILLISECONDS_PER_MINUTE,+ ),+ participants: meeting.calendarInvitees+ .map((invitee) => invitee.email)+ .filter(isNonEmptyString),+ recordedBy: meeting.recordedBy.email,+ fathomUrl: meeting.url,+ ...(isNonEmptyString(meeting.meetingUrl)+ ? { meetingUrl: meeting.meetingUrl }+ : {}),+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/reserve-fathom-backfill-batch-slots.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/reserve-fathom-backfill-batch-slots.util.tsnew file mode 100644index 00000000000..fdb750e9801--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/reserve-fathom-backfill-batch-slots.util.ts@@ -0,0 +1,42 @@+import { kv } from 'twenty-sdk/logic-function';++import { FATHOM_BACKFILL_BATCH_STAGGER_MILLISECONDS } from 'src/constants/fathom.constant';+import { getFathomBackfillScheduleKey } from 'src/logic-functions/utils/get-fathom-backfill-schedule-key.util';++type FathomBackfillSchedule = {+ nextBatchAvailableAt: number;+};++// Every backfill of one connected account, initial or manual, appends its+// batches to the same per-account timeline so Fathom sees one paced stream+// per token instead of parallel bursts.+export const reserveFathomBackfillBatchSlots = async ({+ connectedAccountId,+ batchCount,+}: {+ connectedAccountId: string;+ batchCount: number;+}): Promise<{ batchDelays: number[]; continuationDelay: number }> => {+ const now = Date.now();+ const scheduleKey = getFathomBackfillScheduleKey(connectedAccountId);+ const existingSchedule = await kv.get<FathomBackfillSchedule>(scheduleKey);+ const scheduleStart = Math.max(+ now,+ existingSchedule?.nextBatchAvailableAt ?? now,+ );+ const batchDelays = Array.from(+ { length: batchCount },+ (_, batchIndex) =>+ scheduleStart -+ now ++ batchIndex * FATHOM_BACKFILL_BATCH_STAGGER_MILLISECONDS,+ );+ const nextBatchAvailableAt =+ scheduleStart + batchCount * FATHOM_BACKFILL_BATCH_STAGGER_MILLISECONDS;++ if (batchCount > 0) {+ await kv.set(scheduleKey, { nextBatchAvailableAt });+ }++ return { batchDelays, continuationDelay: nextBatchAvailableAt - now };+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/serialize-fathom-meeting.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/serialize-fathom-meeting.util.tsnew file mode 100644index 00000000000..b53055564a7--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/serialize-fathom-meeting.util.ts@@ -0,0 +1,16 @@+import { type Meeting } from 'fathom-typescript/sdk/models/shared';++import { type SerializedFathomMeeting } from 'src/logic-functions/types/serialized-fathom-meeting.type';++export const serializeFathomMeeting = ({+ transcript: _transcript,+ defaultSummary: _defaultSummary,+ ...meeting+}: Meeting): SerializedFathomMeeting => ({+ ...meeting,+ createdAt: meeting.createdAt.toISOString(),+ scheduledStartTime: meeting.scheduledStartTime.toISOString(),+ scheduledEndTime: meeting.scheduledEndTime.toISOString(),+ recordingStartTime: meeting.recordingStartTime.toISOString(),+ recordingEndTime: meeting.recordingEndTime.toISOString(),+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util.tsindex 9edc8df1e57..8b46e27963a 100644--- a/packages/twenty-apps/public/fathom/src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util.ts+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util.ts@@ -6,6 +6,7 @@ import { type CallRecordingSyncFields } from 'src/logic-functions/types/call-recimport { computeCallRecordingIdForFathomMeeting } from 'src/logic-functions/utils/compute-call-recording-id-for-fathom-meeting.util';import { findMatchingCalendarEvent } from 'src/logic-functions/utils/find-matching-calendar-event.util';import { formatFathomSummary } from 'src/logic-functions/utils/format-fathom-summary.util';+import { getFathomMeetingTitle } from 'src/logic-functions/utils/get-fathom-meeting-title.util';import { mapFathomTranscriptToEntries } from 'src/logic-functions/utils/map-fathom-transcript-to-entries.util';import { upsertCallRecording } from 'src/logic-functions/utils/upsert-call-recording.util';@@ -29,9 +30,10 @@ export const syncFathomMeetingToCallRecording = async ({coreApiClient,meeting,});- const title = meeting.meetingTitle?.trim() || meeting.title.trim();- const isComplete =- transcriptEntries.length > 0 && isNonEmptyString(summaryMarkdown);+ const title = getFathomMeetingTitle(meeting);+ // Fathom exposes no pending state, so a summary still missing when we sync is+ // one it never generated: waiting on it would strand the recording.+ const isComplete = transcriptEntries.length > 0;const fields: CallRecordingSyncFields = {...(isNonEmptyString(title) ? { title } : {}),status: isComplete ? 'COMPLETED' : 'PROCESSING',diff --git a/packages/twenty-apps/public/fathom/src/utils/chunk-into-batches.util.ts b/packages/twenty-apps/public/fathom/src/utils/chunk-into-batches.util.tsnew file mode 100644index 00000000000..8c9f5f87be1--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/utils/chunk-into-batches.util.ts@@ -0,0 +1,14 @@+export const chunkIntoBatches = <TItem>(+ items: TItem[],+ batchSize: number,+): TItem[][] => {+ if (!Number.isInteger(batchSize) || batchSize <= 0) {+ throw new Error('Batch size must be a positive integer');+ }++ return Array.from(+ { length: Math.ceil(items.length / batchSize) },+ (_, batchIndex) =>+ items.slice(batchIndex * batchSize, (batchIndex + 1) * batchSize),+ );+};