The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Sync Fathom recordings from webhooks (#25208)
nitin61da7479bf3c
diff --git a/packages/twenty-apps/public/fathom/CHANGELOG.md b/packages/twenty-apps/public/fathom/CHANGELOG.mdindex d88f1af1025..4dd1aa2fc8a 100644--- a/packages/twenty-apps/public/fathom/CHANGELOG.md+++ b/packages/twenty-apps/public/fathom/CHANGELOG.md@@ -4,4 +4,6 @@ All notable changes to this application are documented in this file.## 0.1.0-- Initial application scaffolded with [`create-twenty-app`](https://www.npmjs.com/package/create-twenty-app)+- 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.diff --git a/packages/twenty-apps/public/fathom/README.md b/packages/twenty-apps/public/fathom/README.mdindex 96eac85dd41..d5b66dfbaf4 100644--- a/packages/twenty-apps/public/fathom/README.md+++ b/packages/twenty-apps/public/fathom/README.md@@ -1,9 +1,25 @@# Fathom-Connect a Fathom account to Twenty through OAuth. Twenty stores and refreshes-the connection token for the person who connected it.+**Bring new Fathom meeting recordings, transcripts, and insights into Twenty.**++## What you get++- Fathom recordings saved as Call Recordings+- Transcripts, summaries, and action items+- Links to matching calendar events when the match is unambiguous+- Automatic sync for new recordings## Requirements-The centrally managed Twenty OAuth app needs a Fathom client ID and client-secret. Development setup lives in [SETUP.md](SETUP.md).+Each person connects their Fathom account to Twenty. The connected Fathom+account decides which recordings Twenty can import; the Fathom and Twenty login+emails do not need to match.++## Heads up++- Twenty only links a recording to a calendar event when its meeting URL and+ scheduled time identify one clear match.+- Disconnect and reconnect Fathom after changing the webhook URL or webhook+ scopes so Fathom receives the new registration.++Development setup lives in [SETUP.md](SETUP.md).diff --git a/packages/twenty-apps/public/fathom/SETUP.md b/packages/twenty-apps/public/fathom/SETUP.mdindex 677d6218200..3736ac55a76 100644--- a/packages/twenty-apps/public/fathom/SETUP.md+++ b/packages/twenty-apps/public/fathom/SETUP.md@@ -8,6 +8,23 @@ Follow these steps to get your app running locally.- Yarn 4- Docker (to run the local Twenty server)- A Fathom OAuth client+- A public HTTPS URL forwarding to the local Twenty server++Register this OAuth callback in Fathom:++```text+https://<development-host>/auth/apps/callback+```++Set Twenty's `SERVER_URL` to that same public host. The connection hook registers+this destination with Fathom automatically:++```text+https://<development-host>/webhooks/server/72b52885-e1ba-419f-8e2e-052700f2c9f2?connectionId=<connected-account-id>+```++The ID is the **Fathom webhook resolver** logic function. Deliveries are routed+to the workspace that made the connection, so no per-workspace domain is needed.## Steps@@ -34,7 +51,7 @@ Follow these steps to get your app running locally.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.+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.## Verifying your setupdiff --git a/packages/twenty-apps/public/fathom/package.json b/packages/twenty-apps/public/fathom/package.jsonindex 172454a7e0a..23d899a90b1 100644--- a/packages/twenty-apps/public/fathom/package.json+++ b/packages/twenty-apps/public/fathom/package.json@@ -18,6 +18,10 @@"test:watch": "vitest","test:unit": "vitest run --config vitest.unit.config.ts"},+ "dependencies": {+ "@sniptt/guards": "^0.2.0",+ "fathom-typescript": "0.0.43"+ },"devDependencies": {"@types/node": "^24.7.2","@typescript/native-preview": "^7.0.0-dev.20260116.1",diff --git a/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-not-found-error.util.ts b/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-not-found-error.util.tsnew file mode 100644index 00000000000..258bd41b6c3--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-not-found-error.util.ts@@ -0,0 +1,8 @@+import { FathomError } from 'fathom-typescript/sdk/models/errors';++export const buildFathomNotFoundError = (): FathomError =>+ new FathomError('Not found', {+ response: new Response(null, { status: 404 }),+ request: new Request('https://api.fathom.ai/external/v1/webhooks/1'),+ body: '',+ });diff --git a/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-server-error.util.ts b/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-server-error.util.tsnew file mode 100644index 00000000000..7eb98ebd13e--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/__tests__/utils/build-fathom-server-error.util.ts@@ -0,0 +1,8 @@+import { FathomError } from 'fathom-typescript/sdk/models/errors';++export const buildFathomServerError = (): FathomError =>+ new FathomError('Service unavailable', {+ response: new Response(null, { status: 503 }),+ request: new Request('https://api.fathom.ai/external/v1/webhooks'),+ body: '',+ });diff --git a/packages/twenty-apps/public/fathom/src/connection-providers/fathom-connection.ts b/packages/twenty-apps/public/fathom/src/connection-providers/fathom-connection.tsindex 90a37c47989..59cefd74d2c 100644--- a/packages/twenty-apps/public/fathom/src/connection-providers/fathom-connection.ts+++ b/packages/twenty-apps/public/fathom/src/connection-providers/fathom-connection.ts@@ -1,12 +1,23 @@import { defineConnectionProvider } from 'twenty-sdk/define';-import { FATHOM_CONNECTION_PROVIDER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { FATHOM_PROVIDER_NAME } from 'src/constants/fathom.constant';+import {+ FATHOM_CONNECTION_PROVIDER_UNIVERSAL_IDENTIFIER,+ FATHOM_DISCONNECT_UNIVERSAL_IDENTIFIER,+ FATHOM_REGISTER_CONNECTION_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';export default defineConnectionProvider({universalIdentifier: FATHOM_CONNECTION_PROVIDER_UNIVERSAL_IDENTIFIER,- name: 'fathom',+ name: FATHOM_PROVIDER_NAME,displayName: 'Fathom',type: 'oauth',+ onConnectLogicFunction: {+ universalIdentifier: FATHOM_REGISTER_CONNECTION_UNIVERSAL_IDENTIFIER,+ },+ onDisconnectLogicFunction: {+ universalIdentifier: FATHOM_DISCONNECT_UNIVERSAL_IDENTIFIER,+ },oauth: {authorizationEndpoint: 'https://fathom.video/external/v1/oauth2/authorize',tokenEndpoint: 'https://api.fathom.ai/external/v1/oauth2/token',diff --git a/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts b/packages/twenty-apps/public/fathom/src/constants/fathom.constant.tsnew file mode 100644index 00000000000..a870418a99a--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts@@ -0,0 +1,4 @@+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;diff --git a/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.tsindex 44c2e7a47e9..d908644cc12 100644--- a/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts+++ b/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts@@ -7,3 +7,13 @@ export const DEFAULT_ROLE_UNIVERSAL_IDENTIFIER ='66c9ec61-dd73-4b1c-b3c5-ee54dffd8f05';export const FATHOM_CONNECTION_PROVIDER_UNIVERSAL_IDENTIFIER ='eec1a27d-7678-43df-81e9-9f245ada8fe4';+export const FATHOM_REGISTER_CONNECTION_UNIVERSAL_IDENTIFIER =+ 'd6cb329f-8d0d-48f0-af30-e3ce2e11ddc6';+export const FATHOM_DISCONNECT_UNIVERSAL_IDENTIFIER =+ '51edabd6-6698-4317-b134-f1d41633d76b';+export const FATHOM_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER =+ '72b52885-e1ba-419f-8e2e-052700f2c9f2';+export const FATHOM_WEBHOOK_UNIVERSAL_IDENTIFIER =+ '4047fcd1-8581-4188-bf35-e3e49a6235ca';+export const FATHOM_UNINSTALL_UNIVERSAL_IDENTIFIER =+ '2f0b2b98-6ec1-4a3f-95bb-b2adf4bd4e33';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.tsnew file mode 100644index 00000000000..b9040af793f--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-register-connection.test.ts@@ -0,0 +1,177 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++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';++const sdkMocks = vi.hoisted(() => ({+ createWebhook: vi.fn(),+ deleteWebhook: vi.fn(),+ getConnection: vi.fn(),+ kvGet: vi.fn(),+ kvSet: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<typeof import('twenty-sdk/logic-function')>()),+ kv: { get: sdkMocks.kvGet, set: sdkMocks.kvSet },+ getConnection: sdkMocks.getConnection,+}));++vi.mock('fathom-typescript', () => ({+ Fathom: class Fathom {+ createWebhook = sdkMocks.createWebhook;+ deleteWebhook = sdkMocks.deleteWebhook;+ },+}));++const { fathomRegisterConnectionHandler } =+ await import('src/logic-functions/fathom-register-connection');++const HOOK_PAYLOAD = {+ connectionProviderId: 'provider-1',+ connectionProviderName: 'fathom',+ connectedAccountId: 'connection-1',+};++const failRegistrationWrite = (error: Error) => {+ sdkMocks.kvSet.mockImplementation((key: string) =>+ key.startsWith('fathom-webhook:')+ ? Promise.reject(error)+ : Promise.resolve(),+ );+};++const INACTIVE_REGISTRATION = {+ webhookId: 'stale-webhook',+ secret: 'secret',+ isActive: false,+};++describe('fathomRegisterConnectionHandler', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => undefined);+ process.env.TWENTY_API_URL = 'https://example.dev';+ sdkMocks.getConnection.mockResolvedValue({ accessToken: 'token' });+ sdkMocks.kvGet.mockResolvedValue(null);+ sdkMocks.createWebhook.mockResolvedValue({+ id: 'webhook-1',+ secret: 'secret-1',+ });+ });++ it('claims the connection and registers a webhook pointing at the server route', async () => {+ expect(await fathomRegisterConnectionHandler(HOOK_PAYLOAD)).toEqual({+ success: true,+ webhookId: 'webhook-1',+ });+ expect(sdkMocks.kvSet).toHaveBeenCalledWith(+ 'fathom-connection:connection-1',+ null,+ { scope: 'SERVER' },+ );+ expect(sdkMocks.createWebhook).toHaveBeenCalledWith(+ expect.objectContaining({+ destinationUrl:+ 'https://example.dev/webhooks/server/72b52885-e1ba-419f-8e2e-052700f2c9f2?connectionId=connection-1',+ }),+ );+ expect(sdkMocks.kvSet).toHaveBeenCalledWith('fathom-webhook:connection-1', {+ webhookId: 'webhook-1',+ secret: 'secret-1',+ isActive: true,+ });+ });++ it('asks the queue to retry when Fathom fails transiently', async () => {+ sdkMocks.createWebhook.mockRejectedValue(buildFathomServerError());++ await expect(+ fathomRegisterConnectionHandler(HOOK_PAYLOAD),+ ).rejects.toBeInstanceOf(RetryableLogicFunctionError);+ });++ it('surfaces a rejected webhook without retrying', async () => {+ sdkMocks.createWebhook.mockRejectedValue(buildFathomNotFoundError());++ await expect(+ fathomRegisterConnectionHandler(HOOK_PAYLOAD),+ ).rejects.not.toBeInstanceOf(RetryableLogicFunctionError);+ });++ it('deletes the webhook it just created when the registration cannot be stored', async () => {+ failRegistrationWrite(new Error('Key value store unavailable'));++ await expect(fathomRegisterConnectionHandler(HOOK_PAYLOAD)).rejects.toThrow(+ 'Key value store unavailable',+ );+ expect(sdkMocks.deleteWebhook).toHaveBeenCalledWith({ id: 'webhook-1' });+ });++ it('keeps the webhook when the failed write turns out to have committed', async () => {+ failRegistrationWrite(new Error('Response lost'));+ sdkMocks.kvGet.mockResolvedValueOnce(null).mockResolvedValueOnce({+ webhookId: 'webhook-1',+ secret: 'secret-1',+ isActive: true,+ });++ expect(await fathomRegisterConnectionHandler(HOOK_PAYLOAD)).toEqual({+ success: true,+ webhookId: 'webhook-1',+ });+ expect(sdkMocks.deleteWebhook).not.toHaveBeenCalled();+ });++ it('reports the storage failure even when the created webhook cannot be deleted', async () => {+ failRegistrationWrite(new Error('Key value store unavailable'));+ sdkMocks.deleteWebhook.mockRejectedValue(new Error('Fathom unavailable'));++ await expect(fathomRegisterConnectionHandler(HOOK_PAYLOAD)).rejects.toThrow(+ 'Key value store unavailable',+ );+ });++ it('reuses the webhook of an already active registration', async () => {+ sdkMocks.kvGet.mockResolvedValue({+ ...INACTIVE_REGISTRATION,+ webhookId: 'existing-webhook',+ isActive: true,+ });++ expect(await fathomRegisterConnectionHandler(HOOK_PAYLOAD)).toEqual({+ success: true,+ webhookId: 'existing-webhook',+ });+ expect(sdkMocks.createWebhook).not.toHaveBeenCalled();+ });++ it('replaces an inactive registration whose webhook Fathom already dropped', async () => {+ sdkMocks.kvGet.mockResolvedValue(INACTIVE_REGISTRATION);+ sdkMocks.deleteWebhook.mockRejectedValue(buildFathomNotFoundError());++ expect(await fathomRegisterConnectionHandler(HOOK_PAYLOAD)).toEqual({+ success: true,+ webhookId: 'webhook-1',+ });+ expect(sdkMocks.deleteWebhook).toHaveBeenCalledWith({+ id: 'stale-webhook',+ });+ });++ it('does not replace an inactive registration when its webhook cannot be deleted', async () => {+ sdkMocks.kvGet.mockResolvedValue(INACTIVE_REGISTRATION);+ sdkMocks.deleteWebhook.mockRejectedValue(new Error('Fathom unavailable'));++ await expect(fathomRegisterConnectionHandler(HOOK_PAYLOAD)).rejects.toThrow(+ 'Fathom unavailable',+ );+ expect(sdkMocks.createWebhook).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-uninstall.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-uninstall.test.tsnew file mode 100644index 00000000000..c854cf1a807--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/__tests__/fathom-uninstall.test.ts@@ -0,0 +1,105 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildFathomNotFoundError } from 'src/__tests__/utils/build-fathom-not-found-error.util';++const sdkMocks = vi.hoisted(() => ({+ deleteWebhook: vi.fn(),+ kvDelete: vi.fn(),+ kvGet: vi.fn(),+ listConnections: vi.fn(),+}));++vi.mock('twenty-sdk/define', () => ({+ defineUninstallLogicFunction: (config: unknown) => config,+}));++vi.mock('twenty-sdk/logic-function', () => ({+ kv: { get: sdkMocks.kvGet, delete: sdkMocks.kvDelete },+ listConnections: sdkMocks.listConnections,+}));++vi.mock('fathom-typescript', () => ({+ Fathom: class Fathom {+ deleteWebhook = sdkMocks.deleteWebhook;+ },+}));++const { fathomUninstallHandler } =+ await import('src/logic-functions/fathom-uninstall');++const buildConnection = (id: string) => ({ id, accessToken: `token-${id}` });++const buildRegistration = (registrationKey: string) => ({+ webhookId: `webhook-for-${registrationKey}`,+ secret: 'secret',+ isActive: true,+});++describe('fathomUninstallHandler', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ vi.spyOn(console, 'error').mockImplementation(() => undefined);+ sdkMocks.listConnections.mockResolvedValue([+ buildConnection('connection-1'),+ buildConnection('connection-2'),+ ]);+ sdkMocks.kvGet.mockImplementation((key: string) =>+ Promise.resolve(buildRegistration(key)),+ );+ });++ it('deletes the Fathom webhook of every connected account', async () => {+ expect(await fathomUninstallHandler()).toEqual({ deletedWebhookCount: 2 });+ expect(sdkMocks.deleteWebhook.mock.calls).toEqual([+ [{ id: 'webhook-for-fathom-webhook:connection-1' }],+ [{ id: 'webhook-for-fathom-webhook:connection-2' }],+ ]);+ expect(sdkMocks.kvDelete.mock.calls).toEqual([+ ['fathom-webhook:connection-1'],+ ['fathom-connection:connection-1', { scope: 'SERVER' }],+ ['fathom-webhook:connection-2'],+ ['fathom-connection:connection-2', { scope: 'SERVER' }],+ ]);+ });++ it('keeps deleting the remaining webhooks when Fathom rejects one', async () => {+ sdkMocks.deleteWebhook.mockRejectedValueOnce(+ new Error('Fathom unavailable'),+ );++ expect(await fathomUninstallHandler()).toEqual({ deletedWebhookCount: 1 });+ expect(sdkMocks.deleteWebhook).toHaveBeenNthCalledWith(2, {+ id: 'webhook-for-fathom-webhook:connection-2',+ });+ expect(sdkMocks.kvDelete).toHaveBeenCalledTimes(4);+ expect(console.error).toHaveBeenCalledWith(+ expect.stringContaining('webhook-for-fathom-webhook:connection-1'),+ );+ });++ it('counts a webhook Fathom already dropped as deleted', async () => {+ sdkMocks.deleteWebhook.mockRejectedValueOnce(buildFathomNotFoundError());++ expect(await fathomUninstallHandler()).toEqual({ deletedWebhookCount: 2 });+ expect(console.error).not.toHaveBeenCalled();+ });++ it('keeps cleaning the remaining connections when one KV read fails', async () => {+ sdkMocks.kvGet.mockRejectedValueOnce(+ new Error('Key value store unavailable'),+ );++ expect(await fathomUninstallHandler()).toEqual({ deletedWebhookCount: 1 });+ expect(sdkMocks.deleteWebhook).toHaveBeenCalledWith({+ id: 'webhook-for-fathom-webhook:connection-2',+ });+ });++ it('skips connections that never registered a webhook', async () => {+ sdkMocks.kvGet.mockResolvedValue(null);++ expect(await fathomUninstallHandler()).toEqual({ deletedWebhookCount: 0 });+ expect(sdkMocks.deleteWebhook).not.toHaveBeenCalled();+ expect(sdkMocks.kvDelete).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-disconnect.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-disconnect.tsnew file mode 100644index 00000000000..e844282f2f2--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-disconnect.ts@@ -0,0 +1,36 @@+import { defineLogicFunction } from 'twenty-sdk/define';+import { kv } from 'twenty-sdk/logic-function';+import { isDefined } from 'src/utils/is-defined';++import { FATHOM_DISCONNECT_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 { getFathomWebhookRegistrationKey } from 'src/logic-functions/utils/get-fathom-webhook-registration-key.util';++export const fathomDisconnectHandler = async (+ payload: FathomConnectionHookPayload,+): Promise<{ success: true }> => {+ const registrationKey = getFathomWebhookRegistrationKey(+ payload.connectedAccountId,+ );+ const registration = await kv.get<FathomWebhookRegistration>(registrationKey);++ if (isDefined(registration)) {+ // Twenty runs onDisconnect after deleting the token, so the secret is kept only+ // to acknowledge Fathom deliveries still in flight.+ // TODO: delete the webhook, this registration and the server-scoped connection+ // claim here, and drop isActive, once the engine carries #25215.+ await kv.set(registrationKey, { ...registration, isActive: false });+ }++ return { success: true };+};++export default defineLogicFunction({+ universalIdentifier: FATHOM_DISCONNECT_UNIVERSAL_IDENTIFIER,+ name: 'fathom-disconnect',+ description:+ 'Disables webhook ingestion after a user removes their Fathom connection.',+ timeoutSeconds: 10,+ handler: fathomDisconnectHandler,+});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.tsnew file mode 100644index 00000000000..92ed80b1d24--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-register-connection.ts@@ -0,0 +1,104 @@+import { isNonEmptyString } from '@sniptt/guards';+import { defineLogicFunction } from 'twenty-sdk/define';+import {+ getConnection,+ kv,+ RetryableLogicFunctionError,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'src/utils/is-defined';++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 { 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';+import { isTransientFathomError } from 'src/logic-functions/utils/is-transient-fathom-error.util';+import { storeFathomWebhookRegistration } from 'src/logic-functions/utils/store-fathom-webhook-registration.util';+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';++export const fathomRegisterConnectionHandler = async (+ payload: FathomConnectionHookPayload,+): Promise<{ success: true; webhookId: string }> => {+ if (!isNonEmptyString(payload.connectedAccountId)) {+ throw new Error(+ 'Fathom connection registration requires a connectedAccountId',+ );+ }++ const apiUrl = process.env.TWENTY_API_URL;++ if (!isNonEmptyString(apiUrl)) {+ throw new Error('TWENTY_API_URL is required to register a Fathom webhook');+ }++ const connection = await getConnection(payload.connectedAccountId);+ const fathomClient = createFathomClient(connection.accessToken);+ const registrationKey = getFathomWebhookRegistrationKey(+ payload.connectedAccountId,+ );+ const existingRegistration =+ await kv.get<FathomWebhookRegistration>(registrationKey);++ if (existingRegistration?.isActive) {+ return { success: true, webhookId: existingRegistration.webhookId };+ }++ if (isDefined(existingRegistration)) {+ await deleteStaleFathomWebhook({+ fathomClient,+ webhookId: existingRegistration.webhookId,+ });+ }++ await kv.set(getFathomConnectionClaimKey(payload.connectedAccountId), null, {+ scope: 'SERVER',+ });++ const webhook = await fathomClient+ .createWebhook({+ destinationUrl: getFathomWebhookDestinationUrl({+ apiUrl,+ connectedAccountId: payload.connectedAccountId,+ }),+ triggeredFor: [+ 'my_recordings',+ 'my_shared_with_team_recordings',+ 'shared_team_recordings',+ ],+ includeTranscript: true,+ includeSummary: true,+ includeActionItems: true,+ })+ .catch((error: unknown) => {+ if (isTransientFathomError(error)) {+ throw new RetryableLogicFunctionError(toErrorMessage(error));+ }++ throw error;+ });++ await storeFathomWebhookRegistration({+ fathomClient,+ connectedAccountId: payload.connectedAccountId,+ registrationKey,+ registration: {+ webhookId: webhook.id,+ secret: webhook.secret,+ isActive: true,+ },+ });++ return { success: true, webhookId: webhook.id };+};++export default defineLogicFunction({+ universalIdentifier: FATHOM_REGISTER_CONNECTION_UNIVERSAL_IDENTIFIER,+ name: 'fathom-register-connection',+ description:+ "Registers a Fathom webhook using the connected account's permissions.",+ timeoutSeconds: 30,+ handler: fathomRegisterConnectionHandler,+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-uninstall.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-uninstall.tsnew file mode 100644index 00000000000..acfec444c93--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-uninstall.ts@@ -0,0 +1,85 @@+import { defineUninstallLogicFunction } from 'twenty-sdk/define';+import {+ type AppConnection,+ kv,+ listConnections,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'src/utils/is-defined';++import { FATHOM_PROVIDER_NAME } from 'src/constants/fathom.constant';+import { FATHOM_UNINSTALL_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { type FathomWebhookRegistration } from 'src/logic-functions/types/fathom-webhook-registration.type';+import { getFathomConnectionClaimKey } from 'src/logic-functions/utils/get-fathom-connection-claim-key.util';+import { createFathomClient } from 'src/logic-functions/utils/create-fathom-client.util';+import { getFathomWebhookRegistrationKey } from 'src/logic-functions/utils/get-fathom-webhook-registration-key.util';+import { isFathomNotFoundError } from 'src/logic-functions/utils/is-fathom-not-found-error.util';+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';++const deleteWebhookForConnection = async (+ connection: AppConnection,+): Promise<boolean> => {+ const registrationKey = getFathomWebhookRegistrationKey(connection.id);+ const registration = await kv.get<FathomWebhookRegistration>(registrationKey);++ if (!isDefined(registration)) {+ return false;+ }++ let isWebhookGone = false;++ try {+ await createFathomClient(connection.accessToken).deleteWebhook({+ id: registration.webhookId,+ });+ isWebhookGone = true;+ } catch (error) {+ isWebhookGone = isFathomNotFoundError(error);++ if (!isWebhookGone) {+ // Uninstall runs once and takes the app's KV with it, so this log line is+ // the only record of the webhook left behind in Fathom.+ console.error(+ `[fathom] leaked webhook ${registration.webhookId} for connected account ${connection.id}: ${toErrorMessage(error)}`,+ );+ }+ }++ await kv.delete(registrationKey);+ await kv.delete(getFathomConnectionClaimKey(connection.id), {+ scope: 'SERVER',+ });++ return isWebhookGone;+};++export const fathomUninstallHandler = async (): Promise<{+ deletedWebhookCount: number;+}> => {+ const connections = await listConnections({+ providerName: FATHOM_PROVIDER_NAME,+ });+ let deletedWebhookCount = 0;++ for (const connection of connections) {+ try {+ if (await deleteWebhookForConnection(connection)) {+ deletedWebhookCount++;+ }+ } catch (error) {+ console.error(+ `[fathom] webhook cleanup failed for connected account ${connection.id}: ${toErrorMessage(error)}`,+ );+ }+ }++ return { deletedWebhookCount };+};++export default defineUninstallLogicFunction({+ universalIdentifier: FATHOM_UNINSTALL_UNIVERSAL_IDENTIFIER,+ name: 'fathom-uninstall',+ description:+ 'Deletes the Fathom webhooks registered for every connected account when the app is uninstalled.',+ timeoutSeconds: 30,+ handler: fathomUninstallHandler,+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-webhook-resolver.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-webhook-resolver.tsnew file mode 100644index 00000000000..74c2a25a774--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-webhook-resolver.ts@@ -0,0 +1,65 @@+import { isNonEmptyString } from '@sniptt/guards';+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import {+ kv,+ Response,+ type ServerRouteResolverResult,+} from 'twenty-sdk/logic-function';++import { FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/constants/fathom.constant';+import {+ FATHOM_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER,+ FATHOM_WEBHOOK_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';+import { getFathomConnectionClaimKey } from 'src/logic-functions/utils/get-fathom-connection-claim-key.util';++export const fathomWebhookResolverHandler = async (+ routePayload: RoutePayload<unknown>,+): Promise<ServerRouteResolverResult> => {+ const connectedAccountId =+ routePayload.queryStringParameters?.[+ FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER+ ];++ if (!isNonEmptyString(connectedAccountId)) {+ return new Response(+ { error: 'Missing Fathom connection identifier' },+ { status: 400 },+ );+ }++ const workspaceId = await kv.get<string>(+ getFathomConnectionClaimKey(connectedAccountId),+ { scope: 'SERVER' },+ );++ if (!isNonEmptyString(workspaceId)) {+ return new Response(+ { error: 'Unknown Fathom connection' },+ { status: 404 },+ );+ }++ return {+ workspaceId,+ targetLogicFunctionUniversalIdentifier: FATHOM_WEBHOOK_UNIVERSAL_IDENTIFIER,+ payload: routePayload,+ };+};++export default defineLogicFunction({+ universalIdentifier: FATHOM_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER,+ name: 'fathom-webhook-resolver',+ description:+ 'Routes a Fathom webhook delivery to the workspace that claimed the connection named in its query string.',+ timeoutSeconds: 15,+ handler: fathomWebhookResolverHandler,+ serverRouteTriggerSettings: {+ httpMethods: ['POST'],+ forwardedRequestHeaders: [+ 'webhook-id',+ 'webhook-timestamp',+ 'webhook-signature',+ ],+ },+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/fathom-webhook.ts b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-webhook.tsnew file mode 100644index 00000000000..c7428e5ff67--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/fathom-webhook.ts@@ -0,0 +1,104 @@+import { isNonEmptyString } from '@sniptt/guards';+import { Fathom } from 'fathom-typescript';+import { meetingFromJSON } from 'fathom-typescript/sdk/models/shared';+import { CoreApiClient } from 'twenty-client-sdk/core';+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { kv } from 'twenty-sdk/logic-function';+import { isDefined } from 'src/utils/is-defined';++import { FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/constants/fathom.constant';+import { FATHOM_WEBHOOK_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { type FathomWebhookRegistration } from 'src/logic-functions/types/fathom-webhook-registration.type';+import { getFathomWebhookRegistrationKey } from 'src/logic-functions/utils/get-fathom-webhook-registration-key.util';+import { syncFathomMeetingToCallRecording } from 'src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util';++type FathomWebhookResult =+ | {+ success: true;+ callRecordingId: string;+ calendarEventId?: string;+ created: boolean;+ }+ | { success: true; skipped: true; reason: string }+ | { success: false; error: string };++export const fathomWebhookHandler = async (+ routePayload: RoutePayload<unknown>,+): Promise<FathomWebhookResult> => {+ const connectedAccountId =+ routePayload.queryStringParameters?.[+ FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER+ ];++ if (!isNonEmptyString(connectedAccountId)) {+ return { success: false, error: 'Missing Fathom connection identifier' };+ }++ const registration = await kv.get<FathomWebhookRegistration>(+ getFathomWebhookRegistrationKey(connectedAccountId),+ );++ if (!isDefined(registration)) {+ return { success: false, error: 'Unknown Fathom webhook registration' };+ }++ if (!isNonEmptyString(routePayload.rawBody)) {+ return { success: false, error: 'Missing raw Fathom webhook body' };+ }++ const webhookId = routePayload.headers['webhook-id'];+ const webhookTimestamp = routePayload.headers['webhook-timestamp'];+ const webhookSignature = routePayload.headers['webhook-signature'];++ if (+ !isNonEmptyString(webhookId) ||+ !isNonEmptyString(webhookTimestamp) ||+ !isNonEmptyString(webhookSignature)+ ) {+ return { success: false, error: 'Missing Fathom webhook signature' };+ }++ try {+ Fathom.verifyWebhook(+ registration.secret,+ {+ 'webhook-id': webhookId,+ 'webhook-timestamp': webhookTimestamp,+ 'webhook-signature': webhookSignature,+ },+ routePayload.rawBody,+ );+ } catch {+ return { success: false, error: 'Invalid Fathom webhook signature' };+ }++ if (!registration.isActive) {+ return {+ success: true,+ skipped: true,+ reason: 'The Fathom connection has been removed',+ };+ }++ const meetingParseResult = meetingFromJSON(routePayload.rawBody);++ if (!meetingParseResult.ok) {+ return { success: false, error: 'Invalid Fathom meeting payload' };+ }++ const syncResult = await syncFathomMeetingToCallRecording({+ coreApiClient: new CoreApiClient({ runAs: 'application' }),+ meeting: meetingParseResult.value,+ });++ return { success: true, ...syncResult };+};++export default defineLogicFunction({+ universalIdentifier: FATHOM_WEBHOOK_UNIVERSAL_IDENTIFIER,+ name: 'fathom-webhook',+ description:+ 'Verifies Fathom meeting webhooks and upserts accessible recordings into CallRecording records.',+ timeoutSeconds: 60,+ handler: fathomWebhookHandler,+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/calendar-event-candidate.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/calendar-event-candidate.type.tsnew file mode 100644index 00000000000..521beafc8ee--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/calendar-event-candidate.type.ts@@ -0,0 +1,5 @@+export type CalendarEventCandidate = {+ id: string;+ startsAt: string;+ conferenceLink: { primaryLinkUrl?: string | null } | null;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/call-recording-sync-fields.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/call-recording-sync-fields.type.tsnew file mode 100644index 00000000000..1fa479646eb--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/call-recording-sync-fields.type.ts@@ -0,0 +1,13 @@+import { type TranscriptEntry } from 'src/logic-functions/types/transcript-entry.type';++export type CallRecordingSyncFields = {+ title?: string;+ status?: 'PROCESSING' | 'COMPLETED';+ recordingRequestStatus?: 'REQUESTED';+ externalRecordingId?: string;+ startedAt?: string;+ endedAt?: string;+ transcript?: TranscriptEntry[];+ summary?: { markdown: string; blocknote: null };+ calendarEventId?: string;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-connection-hook-payload.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-connection-hook-payload.type.tsnew file mode 100644index 00000000000..da57a0331dd--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-connection-hook-payload.type.ts@@ -0,0 +1,5 @@+export type FathomConnectionHookPayload = {+ connectionProviderId: string;+ connectionProviderName: string;+ connectedAccountId: string;+};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.tsnew file mode 100644index 00000000000..5bad12c8b13--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-webhook-registration.type.ts@@ -0,0 +1,5 @@+export type FathomWebhookRegistration = {+ webhookId: string;+ secret: string;+ isActive: boolean;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/transcript-entry.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/transcript-entry.type.tsnew file mode 100644index 00000000000..ff6b6770cd0--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/transcript-entry.type.ts@@ -0,0 +1,7 @@+export type TranscriptEntry = {+ participant: { name: string };+ words: Array<{+ text: string;+ start_timestamp?: { relative: number };+ }>;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/compute-call-recording-id-for-fathom-meeting.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/compute-call-recording-id-for-fathom-meeting.test.tsnew file mode 100644index 00000000000..7d741dcdb5b--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/compute-call-recording-id-for-fathom-meeting.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import { computeCallRecordingIdForFathomMeeting } from 'src/logic-functions/utils/compute-call-recording-id-for-fathom-meeting.util';++describe('computeCallRecordingIdForFathomMeeting', () => {+ it('returns one stable UUID for a Fathom recording', () => {+ const firstId = computeCallRecordingIdForFathomMeeting(123456789);+ const secondId = computeCallRecordingIdForFathomMeeting(123456789);++ expect(firstId).toBe(secondId);+ expect(firstId).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,+ );+ });++ it('uses a different UUID for a different recording', () => {+ expect(computeCallRecordingIdForFathomMeeting(1)).not.toBe(+ computeCallRecordingIdForFathomMeeting(2),+ );+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/find-matching-calendar-event.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/find-matching-calendar-event.test.tsnew file mode 100644index 00000000000..9d977519807--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/find-matching-calendar-event.test.ts@@ -0,0 +1,226 @@+import { type Meeting } from 'fathom-typescript/sdk/models/shared';+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { describe, expect, it, vi } from 'vitest';++import { MAX_CALENDAR_EVENT_PAGES } from 'src/constants/fathom.constant';+import { findMatchingCalendarEvent } from 'src/logic-functions/utils/find-matching-calendar-event.util';++const buildMeeting = (overrides: Partial<Meeting> = {}): Meeting => ({+ title: 'Customer call',+ meetingTitle: 'Customer call',+ meetingType: null,+ recordingId: 123,+ url: 'https://fathom.video/calls/123',+ meetingUrl: 'https://meet.google.com/abc-defg-hij',+ shareUrl: 'https://fathom.video/share/123',+ createdAt: new Date('2026-01-01T10:00:00.000Z'),+ scheduledStartTime: new Date('2026-01-01T10:00:00.000Z'),+ scheduledEndTime: new Date('2026-01-01T10:30:00.000Z'),+ recordingStartTime: new Date('2026-01-01T10:00:10.000Z'),+ recordingEndTime: new Date('2026-01-01T10:29:00.000Z'),+ calendarInviteesDomainsType: 'one_or_more_external',+ sharedWith: 'no_teams',+ transcriptLanguage: 'en',+ calendarInvitees: [],+ recordedBy: {+ name: 'Ada',+ email: '[email protected]',+ emailDomain: 'example.com',+ team: null,+ },+ ...overrides,+});++type CalendarEventCandidateFixture = {+ id: string;+ startsAt: string;+ conferenceLink: { primaryLinkUrl: string };+};++const buildPage = (+ candidates: CalendarEventCandidateFixture[],+ pageInfo: { hasNextPage: boolean; endCursor: string | null } = {+ hasNextPage: false,+ endCursor: null,+ },+) => ({+ calendarEvents: {+ edges: candidates.map((candidate) => ({ node: candidate })),+ pageInfo,+ },+});++const buildCoreApiClient = (+ candidates: CalendarEventCandidateFixture[],+): Pick<CoreApiClient, 'query'> => ({+ query: vi.fn().mockResolvedValue(buildPage(candidates)),+});++const EXACT_EVENT: CalendarEventCandidateFixture = {+ id: 'exact-event',+ startsAt: '2026-01-01T10:00:00.000Z',+ conferenceLink: { primaryLinkUrl: 'https://meet.google.com/abc-defg-hij' },+};++describe('findMatchingCalendarEvent', () => {+ it('queries live events in a five minute window around the scheduled start', async () => {+ const coreApiClient = buildCoreApiClient([]);++ await findMatchingCalendarEvent({ coreApiClient, meeting: buildMeeting() });++ expect(coreApiClient.query).toHaveBeenCalledWith(+ expect.objectContaining({+ calendarEvents: expect.objectContaining({+ __args: expect.objectContaining({+ filter: {+ and: [+ { startsAt: { gte: '2026-01-01T09:55:00.000Z' } },+ { startsAt: { lte: '2026-01-01T10:05:00.000Z' } },+ { isCanceled: { eq: false } },+ ],+ },+ }),+ }),+ }),+ );+ });++ it('matches an exact meeting URL to the nearest scheduled event', async () => {+ const calendarEventId = await findMatchingCalendarEvent({+ coreApiClient: buildCoreApiClient([+ {+ id: 'later-event',+ startsAt: '2026-01-01T10:03:00.000Z',+ conferenceLink: {+ primaryLinkUrl: 'https://meet.google.com/abc-defg-hij/',+ },+ },+ EXACT_EVENT,+ ]),+ meeting: buildMeeting(),+ });++ expect(calendarEventId).toBe('exact-event');+ });++ it('ignores www, case, query strings, fragments and trailing slashes when comparing URLs', async () => {+ const calendarEventId = await findMatchingCalendarEvent({+ coreApiClient: buildCoreApiClient([+ {+ ...EXACT_EVENT,+ conferenceLink: {+ primaryLinkUrl:+ 'https://WWW.meet.google.com/abc-defg-hij//?authuser=1#details',+ },+ },+ ]),+ meeting: buildMeeting({+ meetingUrl: 'https://meet.google.com/abc-defg-hij?hs=122',+ }),+ });++ expect(calendarEventId).toBe('exact-event');+ });++ it('does not guess when two reused-link events are equally close', async () => {+ const calendarEventId = await findMatchingCalendarEvent({+ coreApiClient: buildCoreApiClient([+ {+ ...EXACT_EVENT,+ id: 'before-event',+ startsAt: '2026-01-01T09:59:00.000Z',+ },+ {+ ...EXACT_EVENT,+ id: 'after-event',+ startsAt: '2026-01-01T10:01:00.000Z',+ },+ ]),+ meeting: buildMeeting(),+ });++ expect(calendarEventId).toBeUndefined();+ });++ it('matches an event that only appears on a later page', async () => {+ const query = vi+ .fn()+ .mockResolvedValueOnce(+ buildPage(+ [+ {+ id: 'unrelated-event',+ startsAt: '2026-01-01T10:00:00.000Z',+ conferenceLink: {+ primaryLinkUrl: 'https://meet.google.com/zzz-zzzz-zzz',+ },+ },+ ],+ { hasNextPage: true, endCursor: 'cursor-1' },+ ),+ )+ .mockResolvedValueOnce(+ buildPage([{ ...EXACT_EVENT, id: 'paged-event' }]),+ );++ expect(+ await findMatchingCalendarEvent({+ coreApiClient: { query },+ meeting: buildMeeting(),+ }),+ ).toBe('paged-event');+ expect(query).toHaveBeenCalledTimes(2);+ expect(query).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ calendarEvents: expect.objectContaining({+ __args: expect.objectContaining({ after: 'cursor-1' }),+ }),+ }),+ );+ });++ it('does not guess from a window it could not read to the end', async () => {+ const query = vi+ .fn()+ .mockResolvedValue(+ buildPage([EXACT_EVENT], { hasNextPage: true, endCursor: 'cursor-1' }),+ );++ expect(+ await findMatchingCalendarEvent({+ coreApiClient: { query },+ meeting: buildMeeting(),+ }),+ ).toBeUndefined();+ expect(query).toHaveBeenCalledTimes(MAX_CALENDAR_EVENT_PAGES);+ });++ it('does not guess when a page claims more results but carries no cursor', async () => {+ const query = vi+ .fn()+ .mockResolvedValue(+ buildPage([EXACT_EVENT], { hasNextPage: true, endCursor: null }),+ );++ expect(+ await findMatchingCalendarEvent({+ coreApiClient: { query },+ meeting: buildMeeting(),+ }),+ ).toBeUndefined();+ expect(query).toHaveBeenCalledTimes(1);+ });++ it('does not query CalendarEvents without Fathom meeting_url', async () => {+ const coreApiClient = buildCoreApiClient([]);++ expect(+ await findMatchingCalendarEvent({+ coreApiClient,+ meeting: buildMeeting({ meetingUrl: null }),+ }),+ ).toBeUndefined();+ expect(coreApiClient.query).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/format-fathom-summary.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/format-fathom-summary.test.tsnew file mode 100644index 00000000000..32f29fc35e3--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/format-fathom-summary.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import { formatFathomSummary } from 'src/logic-functions/utils/format-fathom-summary.util';++describe('formatFathomSummary', () => {+ it('combines the Fathom summary and action items', () => {+ expect(+ formatFathomSummary({+ summaryMarkdown: '## Summary\n\nPricing was discussed.',+ actionItems: [+ {+ description: 'Send the proposal',+ userGenerated: false,+ completed: false,+ recordingTimestamp: '00:10:45',+ recordingPlaybackUrl: 'https://fathom.video/calls/1?timestamp=645',+ assignee: { name: 'Ada', email: '[email protected]', team: null },+ },+ ],+ }),+ ).toBe(+ '## Summary\n\nPricing was discussed.\n\n## Action items\n\n- [ ] Send the proposal — Ada',+ );+ });++ it('returns action items when no summary is available', () => {+ expect(+ formatFathomSummary({+ summaryMarkdown: null,+ actionItems: [+ {+ description: 'Follow up',+ userGenerated: true,+ completed: true,+ recordingTimestamp: '00:01:00',+ recordingPlaybackUrl: 'https://fathom.video/calls/1?timestamp=60',+ assignee: { name: null, email: null, team: null },+ },+ ],+ }),+ ).toBe('## Action items\n\n- [x] Follow up');+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-webhook-destination-url.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-webhook-destination-url.test.tsnew file mode 100644index 00000000000..12bdd44f4b4--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-webhook-destination-url.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';++import { getFathomWebhookDestinationUrl } from 'src/logic-functions/utils/get-fathom-webhook-destination-url.util';++describe('getFathomWebhookDestinationUrl', () => {+ it('builds the server route with the connection identifier', () => {+ expect(+ getFathomWebhookDestinationUrl({+ apiUrl: 'https://twenty.example.com',+ connectedAccountId: 'connection-id',+ }),+ ).toBe(+ 'https://twenty.example.com/webhooks/server/72b52885-e1ba-419f-8e2e-052700f2c9f2?connectionId=connection-id',+ );+ });++ it('preserves a base path on the API URL', () => {+ expect(+ getFathomWebhookDestinationUrl({+ apiUrl: 'https://twenty.example.com/api/',+ connectedAccountId: 'connection-id',+ }),+ ).toBe(+ 'https://twenty.example.com/api/webhooks/server/72b52885-e1ba-419f-8e2e-052700f2c9f2?connectionId=connection-id',+ );+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/map-fathom-transcript-to-entries.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/map-fathom-transcript-to-entries.test.tsnew file mode 100644index 00000000000..e93d52d174c--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/map-fathom-transcript-to-entries.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';++import { mapFathomTranscriptToEntries } from 'src/logic-functions/utils/map-fathom-transcript-to-entries.util';++describe('mapFathomTranscriptToEntries', () => {+ it('maps Fathom utterances to CallRecording transcript entries', () => {+ expect(+ mapFathomTranscriptToEntries([+ {+ speaker: { displayName: 'Ada' },+ text: 'Ship the integration.',+ timestamp: '01:02:03',+ },+ ]),+ ).toEqual([+ {+ participant: { name: 'Ada' },+ words: [+ {+ text: 'Ship the integration.',+ start_timestamp: { relative: 3723 },+ },+ ],+ },+ ]);+ });++ it('drops empty utterances and tolerates an invalid timestamp', () => {+ expect(+ mapFathomTranscriptToEntries([+ {+ speaker: { displayName: '' },+ text: ' ',+ timestamp: '00:00:01',+ },+ {+ speaker: { displayName: '' },+ text: 'Hello',+ timestamp: 'invalid',+ },+ {+ speaker: { displayName: 'Ada' },+ text: 'Out of range',+ timestamp: '00:75:00',+ },+ ]),+ ).toEqual([+ {+ participant: { name: 'Speaker' },+ words: [{ text: 'Hello' }],+ },+ {+ participant: { name: 'Ada' },+ words: [{ text: 'Out of range' }],+ },+ ]);+ });+});diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/compute-call-recording-id-for-fathom-meeting.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/compute-call-recording-id-for-fathom-meeting.util.tsnew file mode 100644index 00000000000..6fb2c4a1228--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/compute-call-recording-id-for-fathom-meeting.util.ts@@ -0,0 +1,14 @@+import { createHash } from 'crypto';++export const computeCallRecordingIdForFathomMeeting = (+ recordingId: number,+): string => {+ const bytes = createHash('sha256').update(`fathom:${recordingId}`).digest();++ bytes[6] = (bytes[6] & 0x0f) | 0x40;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;++ const hexadecimalValue = bytes.subarray(0, 16).toString('hex');++ return `${hexadecimalValue.slice(0, 8)}-${hexadecimalValue.slice(8, 12)}-${hexadecimalValue.slice(12, 16)}-${hexadecimalValue.slice(16, 20)}-${hexadecimalValue.slice(20)}`;+};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.tsnew file mode 100644index 00000000000..59360af64b1--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/create-fathom-client.util.ts@@ -0,0 +1,4 @@+import { Fathom } from 'fathom-typescript';++export const createFathomClient = (accessToken: string): Fathom =>+ new Fathom({ security: { bearerAuth: accessToken } });diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/delete-stale-fathom-webhook.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/delete-stale-fathom-webhook.util.tsnew file mode 100644index 00000000000..af098be3fee--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/delete-stale-fathom-webhook.util.ts@@ -0,0 +1,21 @@+import { type Fathom } from 'fathom-typescript';++import { isFathomNotFoundError } from 'src/logic-functions/utils/is-fathom-not-found-error.util';++// A webhook Fathom already dropped is the only failure safe to move past:+// anything else would orphan the old webhook once it is replaced.+export const deleteStaleFathomWebhook = async ({+ fathomClient,+ webhookId,+}: {+ fathomClient: Fathom;+ webhookId: string;+}): Promise<void> => {+ try {+ await fathomClient.deleteWebhook({ id: webhookId });+ } catch (error) {+ if (!isFathomNotFoundError(error)) {+ throw error;+ }+ }+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/find-matching-calendar-event.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/find-matching-calendar-event.util.tsnew file mode 100644index 00000000000..2deb83c6fc1--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/find-matching-calendar-event.util.ts@@ -0,0 +1,67 @@+import { type Meeting } from 'fathom-typescript/sdk/models/shared';+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { isDefined } from 'src/utils/is-defined';++import { listCalendarEventsInWindow } from 'src/logic-functions/utils/list-calendar-events-in-window.util';+import { normalizeMeetingUrl } from 'src/logic-functions/utils/normalize-meeting-url.util';++const MATCHING_WINDOW_MILLISECONDS = 5 * 60 * 1000;++export const findMatchingCalendarEvent = async ({+ coreApiClient,+ meeting,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ meeting: Meeting;+}): Promise<string | undefined> => {+ const normalizedFathomMeetingUrl = normalizeMeetingUrl(meeting.meetingUrl);++ if (!isDefined(normalizedFathomMeetingUrl)) {+ return undefined;+ }++ const scheduledStartMilliseconds = meeting.scheduledStartTime.getTime();+ const calendarEvents = await listCalendarEventsInWindow({+ coreApiClient,+ earliestStart: new Date(+ scheduledStartMilliseconds - MATCHING_WINDOW_MILLISECONDS,+ ).toISOString(),+ latestStart: new Date(+ scheduledStartMilliseconds + MATCHING_WINDOW_MILLISECONDS,+ ).toISOString(),+ });++ if (!isDefined(calendarEvents)) {+ return undefined;+ }++ const candidates = calendarEvents+ .filter(+ (candidate) =>+ normalizeMeetingUrl(candidate.conferenceLink?.primaryLinkUrl) ===+ normalizedFathomMeetingUrl,+ )+ .map((candidate) => ({+ candidate,+ startDifference: Math.abs(+ new Date(candidate.startsAt).getTime() - scheduledStartMilliseconds,+ ),+ }))+ .sort(+ (firstCandidate, secondCandidate) =>+ firstCandidate.startDifference - secondCandidate.startDifference,+ );++ if (candidates.length === 0) {+ return undefined;+ }++ if (+ candidates.length > 1 &&+ candidates[0].startDifference === candidates[1].startDifference+ ) {+ return undefined;+ }++ return candidates[0].candidate.id;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/format-fathom-summary.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/format-fathom-summary.util.tsnew file mode 100644index 00000000000..7d72afd9da7--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/format-fathom-summary.util.ts@@ -0,0 +1,35 @@+import { type ActionItem } from 'fathom-typescript/sdk/models/shared';+import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';++const formatActionItem = (actionItem: ActionItem): string => {+ const completionMarker = actionItem.completed ? 'x' : ' ';+ const assigneeName = actionItem.assignee.name?.trim();+ const assigneeSuffix = isNonEmptyString(assigneeName)+ ? ` — ${assigneeName}`+ : '';++ return `- [${completionMarker}] ${actionItem.description}${assigneeSuffix}`;+};++export const formatFathomSummary = ({+ summaryMarkdown,+ actionItems,+}: {+ summaryMarkdown: string | null | undefined;+ actionItems: ActionItem[] | null | undefined;+}): string => {+ const sections: string[] = [];+ const trimmedSummary = summaryMarkdown?.trim();++ if (isNonEmptyString(trimmedSummary)) {+ sections.push(trimmedSummary);+ }++ if (isNonEmptyArray(actionItems)) {+ sections.push(+ `## Action items\n\n${actionItems.map(formatActionItem).join('\n')}`,+ );+ }++ return sections.join('\n\n');+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-connection-claim-key.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-connection-claim-key.util.tsnew file mode 100644index 00000000000..308e87978a4--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-connection-claim-key.util.ts@@ -0,0 +1,3 @@+export const getFathomConnectionClaimKey = (+ connectedAccountId: string,+): string => `fathom-connection:${connectedAccountId}`;diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-webhook-destination-url.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-webhook-destination-url.util.tsnew file mode 100644index 00000000000..30e5c8b211b--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-webhook-destination-url.util.ts@@ -0,0 +1,22 @@+import { FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/constants/fathom.constant';+import { FATHOM_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';++export const getFathomWebhookDestinationUrl = ({+ apiUrl,+ connectedAccountId,+}: {+ apiUrl: string;+ connectedAccountId: string;+}): string => {+ const destinationUrl = new URL(apiUrl);+ const apiBasePath = destinationUrl.pathname.replace(/\/+$/, '');++ destinationUrl.pathname = `${apiBasePath}/webhooks/server/${FATHOM_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER}`;++ destinationUrl.searchParams.set(+ FATHOM_WEBHOOK_CONNECTION_QUERY_PARAMETER,+ connectedAccountId,+ );++ return destinationUrl.toString();+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-webhook-registration-key.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-webhook-registration-key.util.tsnew file mode 100644index 00000000000..adc4e06b784--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-webhook-registration-key.util.ts@@ -0,0 +1,3 @@+export const getFathomWebhookRegistrationKey = (+ connectedAccountId: string,+): string => `fathom-webhook:${connectedAccountId}`;diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-fathom-not-found-error.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-fathom-not-found-error.util.tsnew file mode 100644index 00000000000..1c2431ea6d1--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-fathom-not-found-error.util.ts@@ -0,0 +1,6 @@+import { FathomError } from 'fathom-typescript/sdk/models/errors';++const NOT_FOUND_STATUS_CODE = 404;++export const isFathomNotFoundError = (error: unknown): boolean =>+ error instanceof FathomError && error.statusCode === NOT_FOUND_STATUS_CODE;diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-transient-fathom-error.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-transient-fathom-error.util.tsnew file mode 100644index 00000000000..bfff18ab8bf--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-transient-fathom-error.util.ts@@ -0,0 +1,13 @@+import {+ FathomError,+ HTTPClientError,+} from 'fathom-typescript/sdk/models/errors';++const TOO_MANY_REQUESTS_STATUS_CODE = 429;+const SERVER_ERROR_STATUS_CODE_LOWER_BOUND = 500;++export const isTransientFathomError = (error: unknown): boolean =>+ error instanceof HTTPClientError ||+ (error instanceof FathomError &&+ (error.statusCode === TOO_MANY_REQUESTS_STATUS_CODE ||+ error.statusCode >= SERVER_ERROR_STATUS_CODE_LOWER_BOUND));diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-calendar-events-in-window.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-calendar-events-in-window.util.tsnew file mode 100644index 00000000000..1ff95bc0e4c--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/list-calendar-events-in-window.util.ts@@ -0,0 +1,79 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type CoreApiClient } from 'twenty-client-sdk/core';++import {+ CALENDAR_EVENT_PAGE_SIZE,+ MAX_CALENDAR_EVENT_PAGES,+} from 'src/constants/fathom.constant';+import { type CalendarEventCandidate } from 'src/logic-functions/types/calendar-event-candidate.type';++type CalendarEventsPage = {+ calendarEvents?: {+ edges?: Array<{ node: CalendarEventCandidate }>;+ pageInfo?: { hasNextPage?: boolean; endCursor?: string | null };+ };+};++// Matching is only conservative when every event in the window was compared,+// so a window that cannot be read to the end yields undefined, not a partial list.+export const listCalendarEventsInWindow = async ({+ coreApiClient,+ earliestStart,+ latestStart,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ earliestStart: string;+ latestStart: string;+}): Promise<CalendarEventCandidate[] | undefined> => {+ const calendarEvents: CalendarEventCandidate[] = [];+ let cursor: string | undefined = undefined;++ for (let page = 0; page < MAX_CALENDAR_EVENT_PAGES; page++) {+ const queryResult: CalendarEventsPage = await coreApiClient.query({+ calendarEvents: {+ __args: {+ // The API applies one operator per field filter, so a range is two and-ed entries.+ filter: {+ and: [+ { startsAt: { gte: earliestStart } },+ { startsAt: { lte: latestStart } },+ { isCanceled: { eq: false } },+ ],+ },+ first: CALENDAR_EVENT_PAGE_SIZE,+ ...(cursor === undefined ? {} : { after: cursor }),+ },+ edges: {+ node: {+ id: true,+ startsAt: true,+ conferenceLink: {+ primaryLinkUrl: true,+ },+ },+ },+ pageInfo: {+ hasNextPage: true,+ endCursor: true,+ },+ },+ });+ const pageInfo = queryResult.calendarEvents?.pageInfo;++ calendarEvents.push(+ ...(queryResult.calendarEvents?.edges ?? []).map((edge) => edge.node),+ );++ if (pageInfo?.hasNextPage !== true) {+ return calendarEvents;+ }++ if (!isNonEmptyString(pageInfo.endCursor)) {+ return undefined;+ }++ cursor = pageInfo.endCursor;+ }++ return undefined;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/map-fathom-transcript-to-entries.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/map-fathom-transcript-to-entries.util.tsnew file mode 100644index 00000000000..463154842cf--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/map-fathom-transcript-to-entries.util.ts@@ -0,0 +1,44 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type TranscriptItem } from 'fathom-typescript/sdk/models/shared';++import { type TranscriptEntry } from 'src/logic-functions/types/transcript-entry.type';+import { parseFathomTimestamp } from 'src/logic-functions/utils/parse-fathom-timestamp.util';++const UNKNOWN_SPEAKER_LABEL = 'Speaker';++export const mapFathomTranscriptToEntries = (+ transcript: TranscriptItem[] | null | undefined,+): TranscriptEntry[] => {+ if (!Array.isArray(transcript)) {+ return [];+ }++ return transcript.flatMap((transcriptItem) => {+ const text = transcriptItem.text.trim();++ if (!isNonEmptyString(text)) {+ return [];+ }++ const speakerName = transcriptItem.speaker.displayName.trim();+ const startTimestamp = parseFathomTimestamp(transcriptItem.timestamp);++ return [+ {+ participant: {+ name: isNonEmptyString(speakerName)+ ? speakerName+ : UNKNOWN_SPEAKER_LABEL,+ },+ words: [+ {+ text,+ ...(startTimestamp === undefined+ ? {}+ : { start_timestamp: { relative: startTimestamp } }),+ },+ ],+ },+ ];+ });+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/normalize-meeting-url.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/normalize-meeting-url.util.tsnew file mode 100644index 00000000000..b51d930a216--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/normalize-meeting-url.util.ts@@ -0,0 +1,22 @@+import { isNonEmptyString } from '@sniptt/guards';++export const normalizeMeetingUrl = (+ meetingUrl: string | null | undefined,+): string | undefined => {+ if (!isNonEmptyString(meetingUrl)) {+ return undefined;+ }++ try {+ const parsedUrl = new URL(meetingUrl);++ parsedUrl.hash = '';+ parsedUrl.search = '';+ parsedUrl.hostname = parsedUrl.hostname.toLowerCase().replace(/^www\./, '');+ parsedUrl.pathname = parsedUrl.pathname.replace(/\/+$/, '');++ return parsedUrl.toString();+ } catch {+ return undefined;+ }+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/parse-fathom-timestamp.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/parse-fathom-timestamp.util.tsnew file mode 100644index 00000000000..183c65a56de--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/parse-fathom-timestamp.util.ts@@ -0,0 +1,13 @@+const FATHOM_TIMESTAMP_PATTERN = /^(\d+):([0-5]?\d):([0-5]?\d)$/;++export const parseFathomTimestamp = (timestamp: string): number | undefined => {+ const timestampMatch = FATHOM_TIMESTAMP_PATTERN.exec(timestamp);++ if (timestampMatch === null) {+ return undefined;+ }++ const [, hours, minutes, seconds] = timestampMatch.map(Number);++ return hours * 3600 + minutes * 60 + seconds;+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/store-fathom-webhook-registration.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/store-fathom-webhook-registration.util.tsnew file mode 100644index 00000000000..0e5d22e6417--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/store-fathom-webhook-registration.util.ts@@ -0,0 +1,47 @@+import { type Fathom } from 'fathom-typescript';+import { kv } from 'twenty-sdk/logic-function';++import { type FathomWebhookRegistration } from 'src/logic-functions/types/fathom-webhook-registration.type';+import { deleteStaleFathomWebhook } from 'src/logic-functions/utils/delete-stale-fathom-webhook.util';+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';++export const storeFathomWebhookRegistration = async ({+ fathomClient,+ connectedAccountId,+ registrationKey,+ registration,+}: {+ fathomClient: Fathom;+ connectedAccountId: string;+ registrationKey: string;+ registration: FathomWebhookRegistration;+}): Promise<void> => {+ try {+ await kv.set(registrationKey, registration);+ } catch (error) {+ // A write whose response was lost may still have committed.+ const storedRegistration = await kv+ .get<FathomWebhookRegistration>(registrationKey)+ .catch(() => null);++ if (storedRegistration?.webhookId === registration.webhookId) {+ return;+ }++ // Fathom has no webhook listing endpoint, so a webhook this app never+ // recorded can never be found again: undo it before the retry creates+ // a second one against the same destination.+ try {+ await deleteStaleFathomWebhook({+ fathomClient,+ webhookId: registration.webhookId,+ });+ } catch (deleteError) {+ console.error(+ `[fathom] leaked webhook ${registration.webhookId} for connected account ${connectedAccountId}: ${toErrorMessage(deleteError)}`,+ );+ }++ throw error;+ }+};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.tsnew file mode 100644index 00000000000..9edc8df1e57--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/sync-fathom-meeting-to-call-recording.util.ts@@ -0,0 +1,64 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type Meeting } from 'fathom-typescript/sdk/models/shared';+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { type CallRecordingSyncFields } from 'src/logic-functions/types/call-recording-sync-fields.type';+import { 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 { mapFathomTranscriptToEntries } from 'src/logic-functions/utils/map-fathom-transcript-to-entries.util';+import { upsertCallRecording } from 'src/logic-functions/utils/upsert-call-recording.util';++export const syncFathomMeetingToCallRecording = async ({+ coreApiClient,+ meeting,+}: {+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;+ meeting: Meeting;+}): Promise<{+ callRecordingId: string;+ calendarEventId?: string;+ created: boolean;+}> => {+ const transcriptEntries = mapFathomTranscriptToEntries(meeting.transcript);+ const summaryMarkdown = formatFathomSummary({+ summaryMarkdown: meeting.defaultSummary?.markdownFormatted,+ actionItems: meeting.actionItems,+ });+ const calendarEventId = await findMatchingCalendarEvent({+ coreApiClient,+ meeting,+ });+ const title = meeting.meetingTitle?.trim() || meeting.title.trim();+ const isComplete =+ transcriptEntries.length > 0 && isNonEmptyString(summaryMarkdown);+ const fields: CallRecordingSyncFields = {+ ...(isNonEmptyString(title) ? { title } : {}),+ status: isComplete ? 'COMPLETED' : 'PROCESSING',+ recordingRequestStatus: 'REQUESTED',+ externalRecordingId: String(meeting.recordingId),+ startedAt: meeting.recordingStartTime.toISOString(),+ endedAt: meeting.recordingEndTime.toISOString(),+ ...(transcriptEntries.length === 0+ ? {}+ : { transcript: transcriptEntries }),+ ...(isNonEmptyString(summaryMarkdown)+ ? { summary: { markdown: summaryMarkdown, blocknote: null } }+ : {}),+ ...(calendarEventId === undefined ? {} : { calendarEventId }),+ };+ const callRecordingId = computeCallRecordingIdForFathomMeeting(+ meeting.recordingId,+ );+ const upsertResult = await upsertCallRecording({+ coreApiClient,+ callRecordingId,+ fields,+ });++ return {+ callRecordingId,+ calendarEventId,+ created: upsertResult.created,+ };+};diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/to-error-message.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/to-error-message.util.tsnew file mode 100644index 00000000000..d9fa1691ab6--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/to-error-message.util.ts@@ -0,0 +1,2 @@+export const toErrorMessage = (error: unknown): string =>+ error instanceof Error ? error.message : String(error);diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/upsert-call-recording.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/upsert-call-recording.util.tsnew file mode 100644index 00000000000..c1181dd1d4c--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/upsert-call-recording.util.ts@@ -0,0 +1,81 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { isDefined } from 'src/utils/is-defined';++import { type CallRecordingSyncFields } from 'src/logic-functions/types/call-recording-sync-fields.type';++const doesCallRecordingExist = async ({+ coreApiClient,+ callRecordingId,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ callRecordingId: string;+}): Promise<boolean> => {+ const queryResult = await coreApiClient.query({+ callRecordings: {+ __args: {+ filter: { id: { eq: callRecordingId } },+ first: 1,+ },+ edges: { node: { id: true } },+ },+ });++ return isDefined(queryResult.callRecordings?.edges?.[0]?.node);+};++const updateCallRecording = async ({+ coreApiClient,+ callRecordingId,+ fields,+}: {+ coreApiClient: Pick<CoreApiClient, 'mutation'>;+ callRecordingId: string;+ fields: CallRecordingSyncFields;+}): Promise<void> => {+ await coreApiClient.mutation({+ updateCallRecording: {+ __args: {+ id: callRecordingId,+ data: fields,+ },+ id: true,+ },+ });+};++export const upsertCallRecording = async ({+ coreApiClient,+ callRecordingId,+ fields,+}: {+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;+ callRecordingId: string;+ fields: CallRecordingSyncFields;+}): Promise<{ callRecordingId: string; created: boolean }> => {+ if (await doesCallRecordingExist({ coreApiClient, callRecordingId })) {+ await updateCallRecording({ coreApiClient, callRecordingId, fields });++ return { callRecordingId, created: false };+ }++ try {+ await coreApiClient.mutation({+ createCallRecording: {+ __args: {+ data: { id: callRecordingId, ...fields },+ },+ id: true,+ },+ });++ return { callRecordingId, created: true };+ } catch (error) {+ if (!(await doesCallRecordingExist({ coreApiClient, callRecordingId }))) {+ throw error;+ }++ await updateCallRecording({ coreApiClient, callRecordingId, fields });++ return { callRecordingId, created: false };+ }+};diff --git a/packages/twenty-apps/public/fathom/src/utils/is-defined.ts b/packages/twenty-apps/public/fathom/src/utils/is-defined.tsnew file mode 100644index 00000000000..04683b8674e--- /dev/null+++ b/packages/twenty-apps/public/fathom/src/utils/is-defined.ts@@ -0,0 +1,3 @@+export const isDefined = <TValue>(+ value: TValue | null | undefined,+): value is NonNullable<TValue> => value !== null && value !== undefined;diff --git a/packages/twenty-apps/public/fathom/yarn.lock b/packages/twenty-apps/public/fathom/yarn.lockindex e5c715e9c63..dda011d9d20 100644--- a/packages/twenty-apps/public/fathom/yarn.lock+++ b/packages/twenty-apps/public/fathom/yarn.lock@@ -910,6 +910,13 @@ __metadata:languageName: nodelinkType: hard+"@stablelib/base64@npm:^1.0.0":+ version: 1.0.1+ resolution: "@stablelib/base64@npm:1.0.1"+ checksum: 10c0/6330720f021819d19cecfe274111b79a256caa81df478d6b0ae7effc8842b96915b6aeed85926ff05b4d48ec1fc78ad043d928b730ee4e6cc6e8cba6aa097bed+ languageName: node+ linkType: hard+"@standard-schema/spec@npm:^1.1.0":version: 1.1.0resolution: "@standard-schema/spec@npm:1.1.0"@@ -921,8 +928,10 @@ __metadata:version: 0.0.0-use.localresolution: "@twentyhq/fathom@workspace:."dependencies:+ "@sniptt/guards": "npm:^0.2.0""@types/node": "npm:^24.7.2""@typescript/native-preview": "npm:^7.0.0-dev.20260116.1"+ fathom-typescript: "npm:0.0.43"oxlint: "npm:^0.16.0"twenty-client-sdk: "npm:2.35.0"twenty-sdk: "npm:2.35.0"@@ -1612,6 +1621,13 @@ __metadata:languageName: nodelinkType: hard+"fast-sha256@npm:^1.3.0":+ version: 1.3.0+ resolution: "fast-sha256@npm:1.3.0"+ checksum: 10c0/87f9e4baa7639576cf60a2b6235c9f436e1a1c52323abbd8a705b5bea8355500acf176f2aed0c14f2ecd6d6007e26151461bab2f27b8953bcca8d9d6b76a86e4+ languageName: node+ linkType: hard+"fast-string-truncated-width@npm:^3.0.2":version: 3.0.3resolution: "fast-string-truncated-width@npm:3.0.3"@@ -1637,6 +1653,16 @@ __metadata:languageName: nodelinkType: hard+"fathom-typescript@npm:0.0.43":+ version: 0.0.43+ resolution: "fathom-typescript@npm:0.0.43"+ dependencies:+ svix: "npm:^1.65.0"+ zod: "npm:^3.25.0 || ^4.0.0"+ checksum: 10c0/ca7f1aad7a01090d0feafb8218510cf7799d53316a20f84b6e35553f65e24ea9be4c0ce3bed5c0be1be0a2acb578d2a410bcb97542298e74b87d3770afb81f10+ languageName: node+ linkType: hard+"fdir@npm:^6.5.0":version: 6.5.0resolution: "fdir@npm:6.5.0"@@ -2611,6 +2637,16 @@ __metadata:languageName: nodelinkType: hard+"standardwebhooks@npm:1.0.0":+ version: 1.0.0+ resolution: "standardwebhooks@npm:1.0.0"+ dependencies:+ "@stablelib/base64": "npm:^1.0.0"+ fast-sha256: "npm:^1.3.0"+ checksum: 10c0/aee097d0f3c05172c19b80df1ed9596a2ce92f8956957650d0bbe47c2ca6d36515796b51d523333cb4a48c889b2ab130d789e7879e14975c4381bc7a61274327+ languageName: node+ linkType: hard+"std-env@npm:^4.0.0-rc.1":version: 4.2.0resolution: "std-env@npm:4.2.0"@@ -2663,6 +2699,15 @@ __metadata:languageName: nodelinkType: hard+"svix@npm:^1.65.0":+ version: 1.99.1+ resolution: "svix@npm:1.99.1"+ dependencies:+ standardwebhooks: "npm:1.0.0"+ checksum: 10c0/5a630bda0f03318fcab9daa24a76d1f958aeeccad029b240d964a47f0e86274af68a543a3aa8842431380ca9be0e781956137218cdec48d8bb71fd37cda09f9b+ languageName: node+ linkType: hard+"symbol-observable@npm:^1.0.4":version: 1.2.0resolution: "symbol-observable@npm:1.2.0"@@ -3149,3 +3194,10 @@ __metadata:checksum: 10c0/71cc2f2bbb537300c3f569e25693d37b3bc91f225cefce251a71c30bc6bb3e7f8e9420ca0eb57f2ac9e492b085b8dfa075fd1e8195c40b83c951dd59c6e4fbf8languageName: nodelinkType: hard++"zod@npm:^3.25.0 || ^4.0.0":+ version: 4.4.3+ resolution: "zod@npm:4.4.3"+ checksum: 10c0/7ea31b558e88f9faf44f31dd185e2e1cbf51fed3081787fb96cc2534749b50c0acfc6da7f0922a7353ed092dd358c7d50c28ea96c94d04af64191bd33152eca3+ languageName: node+ linkType: hard