Skip to content

The open alternative to Salesforce, designed for AI.

Add Fathom media storage foundation (#25432)

nitin9bcee7abf27e
diff --git a/packages/twenty-apps/public/fathom/package.json b/packages/twenty-apps/public/fathom/package.json
index 23d899a90b1..508ae397e72 100644
--- a/packages/twenty-apps/public/fathom/package.json
+++ b/packages/twenty-apps/public/fathom/package.json
@@ -20,7 +20,8 @@
},
"dependencies": {
"@sniptt/guards": "^0.2.0",
- "fathom-typescript": "0.0.43"
+ "fathom-typescript": "0.0.43",
+ "zod": "^4.1.11"
},
"devDependencies": {
"@types/node": "^24.7.2",
diff --git a/packages/twenty-apps/public/fathom/src/constants/fathom-media-failure-reason.constant.ts b/packages/twenty-apps/public/fathom/src/constants/fathom-media-failure-reason.constant.ts
new file mode 100644
index 00000000000..5df3d8f1678
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/constants/fathom-media-failure-reason.constant.ts
@@ -0,0 +1,9 @@
+export const FATHOM_MEDIA_FAILURE_REASON = {
+ FILE_TOO_LARGE: 'media_file_too_large',
+ NO_DOWNLOADABLE_MEDIA: 'no_downloadable_media',
+ DOWNLOAD_FORBIDDEN: 'download_forbidden',
+ DOWNLOAD_EXPIRED: 'download_expired',
+ DOWNLOAD_TIMED_OUT: 'download_timed_out',
+ CONNECTED_ACCOUNT_UNAVAILABLE: 'connected_account_unavailable',
+ COMPLETED_WITHOUT_FILE: 'completed_without_file',
+};
diff --git a/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts b/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts
index 339e70ba8d1..08468ab88da 100644
--- a/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts
+++ b/packages/twenty-apps/public/fathom/src/constants/fathom.constant.ts
@@ -13,3 +13,8 @@ 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;
+export const FATHOM_MEDIA_MAX_FILE_SIZE_BYTES = 500 * 1024 * 1024;
+export const FATHOM_MEDIA_DOWNLOAD_TIMEOUT_MILLISECONDS = 120_000;
+export const FATHOM_MEDIA_UPLOAD_TIMEOUT_MILLISECONDS = 12 * 60 * 1_000;
+export const FATHOM_MEDIA_IMPORT_CLAIM_DURATION_MILLISECONDS = 20 * 60 * 1_000;
+export const FATHOM_MEDIA_FILE_FOLDER = 'FilesField';
diff --git a/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts
index e8ac678c4f5..c58a385b321 100644
--- a/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts
+++ b/packages/twenty-apps/public/fathom/src/constants/universal-identifiers.ts
@@ -49,3 +49,7 @@ export const FATHOM_RECORDING_IMPORT_CALL_RECORDING_INDEX_UNIVERSAL_IDENTIFIER =
'f0c4e74a-a426-46f8-a76d-a78e00202f8a';
export const FATHOM_RECORDING_IMPORT_CALL_RECORDING_INDEX_FIELD_UNIVERSAL_IDENTIFIER =
'130da502-a1ff-4add-818f-8b272978d01c';
+export const CALL_RECORDING_VIDEO_FIELD_UNIVERSAL_IDENTIFIER =
+ 'bb9523d3-457e-4f4b-8c79-27a77afb87da';
+export const CALL_RECORDING_AUDIO_FIELD_UNIVERSAL_IDENTIFIER =
+ '2eafc2d0-8fec-430c-a939-65ca5fbc0f08';
diff --git a/packages/twenty-apps/public/fathom/src/default-role.ts b/packages/twenty-apps/public/fathom/src/default-role.ts
index 351396688af..12d84a94bfc 100644
--- a/packages/twenty-apps/public/fathom/src/default-role.ts
+++ b/packages/twenty-apps/public/fathom/src/default-role.ts
@@ -1,5 +1,6 @@
import {
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
+ SystemPermissionFlag,
defineApplicationRole,
} from 'twenty-sdk/define';
@@ -13,7 +14,7 @@ export default defineApplicationRole({
universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,
label: `${APP_DISPLAY_NAME} default role`,
description:
- 'Reads calendar events, manages Fathom recording imports, and writes canonical recording data to CallRecording records.',
+ 'Reads calendar events, manages Fathom recording imports, and writes canonical recording data and media to CallRecording records.',
canReadAllObjectRecords: false,
canUpdateAllObjectRecords: false,
canSoftDeleteAllObjectRecords: false,
@@ -58,5 +59,5 @@ export default defineApplicationRole({
},
],
fieldPermissions: [],
- permissionFlagUniversalIdentifiers: [],
+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.UPLOAD_FILE],
});
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/schemas/call-recording-media-state-query-result.schema.ts b/packages/twenty-apps/public/fathom/src/logic-functions/schemas/call-recording-media-state-query-result.schema.ts
new file mode 100644
index 00000000000..4328da171f5
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/schemas/call-recording-media-state-query-result.schema.ts
@@ -0,0 +1,68 @@
+import { z } from 'zod';
+
+import { fathomMediaKindSchema } from 'src/logic-functions/schemas/fathom-media-kind.schema';
+
+const fileSchema = z.object({
+ fileId: z.string().nullable().optional(),
+});
+
+export const fathomMediaUploadCheckpointSchema = z.object({
+ downloadId: z.string().trim().min(1),
+ fileId: z.string().trim().min(1),
+ kind: fathomMediaKindSchema,
+});
+
+const fathomRecordingImportSchema = z.object({
+ id: z.string(),
+ updatedAt: z.string(),
+ recordingId: z.string().nullable().optional(),
+ connectedAccountId: z.string().nullable().optional(),
+ mediaDownloadId: z.string().nullable().optional(),
+ mediaFailureReason: z.string().nullable().optional(),
+ mediaImportClaimedAt: z.string().nullable().optional(),
+ mediaUploadCheckpoint: z.unknown().nullable().optional(),
+});
+
+const fathomRecordingImportsConnectionSchema = z
+ .object({
+ edges: z.array(
+ z
+ .object({
+ node: fathomRecordingImportSchema.nullable().optional(),
+ })
+ .nullable(),
+ ),
+ })
+ .nullable()
+ .optional();
+
+export const callRecordingMediaStateNodeSchema = z.object({
+ id: z.string(),
+ updatedAt: z.string(),
+ video: z.array(fileSchema).nullable().optional(),
+ audio: z.array(fileSchema).nullable().optional(),
+ fathomRecordingImports: fathomRecordingImportsConnectionSchema,
+ transcript: z.unknown().nullable().optional(),
+ summary: z
+ .object({
+ markdown: z.string().nullable().optional(),
+ blocknote: z.unknown().nullable().optional(),
+ })
+ .nullable()
+ .optional(),
+});
+
+export const callRecordingMediaStateQueryResultSchema = z.object({
+ callRecordings: z
+ .object({
+ edges: z.array(
+ z
+ .object({
+ node: callRecordingMediaStateNodeSchema.nullable().optional(),
+ })
+ .nullable(),
+ ),
+ })
+ .nullable()
+ .optional(),
+});
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/schemas/fathom-media-kind.schema.ts b/packages/twenty-apps/public/fathom/src/logic-functions/schemas/fathom-media-kind.schema.ts
new file mode 100644
index 00000000000..d101369b1ec
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/schemas/fathom-media-kind.schema.ts
@@ -0,0 +1,5 @@
+import { z } from 'zod';
+
+export const fathomMediaKindSchema = z.enum(['video', 'audio']);
+
+export type FathomMediaKind = z.infer<typeof fathomMediaKindSchema>;
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/call-recording-media-file.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/call-recording-media-file.type.ts
new file mode 100644
index 00000000000..56de4133ed6
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/call-recording-media-file.type.ts
@@ -0,0 +1 @@
+export type CallRecordingMediaFile = { fileId: string; label: string };
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/call-recording-media-state.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/call-recording-media-state.type.ts
new file mode 100644
index 00000000000..9167a3861a9
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/call-recording-media-state.type.ts
@@ -0,0 +1,17 @@
+import { type FathomMediaUploadCheckpoint } from 'src/logic-functions/types/fathom-media-upload-checkpoint.type';
+
+export type CallRecordingMediaState = {
+ id: string;
+ updatedAt: string;
+ fathomRecordingImportId: string | undefined;
+ fathomRecordingImportUpdatedAt: string | undefined;
+ recordingId: string | undefined;
+ hasVideo: boolean;
+ hasAudio: boolean;
+ hasTranscript: boolean;
+ hasSummary: boolean;
+ failureReason: string | undefined;
+ connectedAccountId: string | undefined;
+ downloadId: string | undefined;
+ uploadCheckpoint: FathomMediaUploadCheckpoint | undefined;
+};
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.ts
index 1fa479646eb..b8554edd3e8 100644
--- 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.ts
@@ -1,3 +1,4 @@
+import { type CallRecordingMediaFile } from 'src/logic-functions/types/call-recording-media-file.type';
import { type TranscriptEntry } from 'src/logic-functions/types/transcript-entry.type';
export type CallRecordingSyncFields = {
@@ -8,6 +9,8 @@ export type CallRecordingSyncFields = {
startedAt?: string;
endedAt?: string;
transcript?: TranscriptEntry[];
+ video?: CallRecordingMediaFile[];
+ audio?: CallRecordingMediaFile[];
summary?: { markdown: string; blocknote: null };
calendarEventId?: string;
};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-media-upload-checkpoint.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-media-upload-checkpoint.type.ts
new file mode 100644
index 00000000000..daf261b9877
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-media-upload-checkpoint.type.ts
@@ -0,0 +1,7 @@
+import { type FathomMediaKind } from 'src/logic-functions/schemas/fathom-media-kind.schema';
+
+export type FathomMediaUploadCheckpoint = {
+ downloadId: string;
+ fileId: string;
+ kind: FathomMediaKind;
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-media-write-context.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-media-write-context.type.ts
new file mode 100644
index 00000000000..0afd1114043
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-media-write-context.type.ts
@@ -0,0 +1,6 @@
+export type FathomMediaWriteContext = {
+ fathomRecordingImportId: string;
+ connectedAccountId: string;
+ claimedAt: string;
+ downloadId: string | null;
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-recording-import-fields.type.ts b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-recording-import-fields.type.ts
index f49a82ac9f9..660d644f6cb 100644
--- a/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-recording-import-fields.type.ts
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/types/fathom-recording-import-fields.type.ts
@@ -1,3 +1,5 @@
+import { type FathomMediaUploadCheckpoint } from 'src/logic-functions/types/fathom-media-upload-checkpoint.type';
+
export type FathomRecordingImportFields = {
callRecordingId?: string;
recordingId?: string;
@@ -5,5 +7,5 @@ export type FathomRecordingImportFields = {
mediaDownloadId?: string | null;
mediaFailureReason?: string | null;
mediaImportClaimedAt?: string | null;
- mediaUploadCheckpoint?: unknown | null;
+ mediaUploadCheckpoint?: FathomMediaUploadCheckpoint | null;
};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-media-download-failure-reason.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-media-download-failure-reason.test.ts
new file mode 100644
index 00000000000..c478599f6a0
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/get-fathom-media-download-failure-reason.test.ts
@@ -0,0 +1,60 @@
+import { type RecordingDownload } from 'fathom-typescript/sdk/models/shared';
+import { describe, expect, it } from 'vitest';
+
+import { getFathomMediaDownloadFailureReason } from 'src/logic-functions/utils/get-fathom-media-download-failure-reason.util';
+
+const DOWNLOAD_FILE = {
+ url: 'https://example.com/recording',
+ contentType: 'video/mp4',
+ fileSizeBytes: 1_024,
+ expiresAt: new Date('2026-09-06T12:00:00.000Z'),
+};
+
+describe('getFathomMediaDownloadFailureReason', () => {
+ it.each<{
+ description: string;
+ download: Pick<
+ RecordingDownload,
+ 'status' | 'failureReason' | 'video' | 'audio'
+ >;
+ expectedReason: string | undefined;
+ }>([
+ {
+ description: 'processing without files remains pending',
+ download: { status: 'processing' },
+ expectedReason: undefined,
+ },
+ {
+ description: 'completed video is importable',
+ download: { status: 'completed', video: DOWNLOAD_FILE },
+ expectedReason: undefined,
+ },
+ {
+ description: 'completed audio is importable',
+ download: { status: 'completed', audio: DOWNLOAD_FILE },
+ expectedReason: undefined,
+ },
+ {
+ description: 'expired downloads cannot reuse an expired file',
+ download: { status: 'expired', video: DOWNLOAD_FILE },
+ expectedReason: 'download_expired',
+ },
+ {
+ description: 'failed downloads retain the provider reason',
+ download: { status: 'failed', failureReason: 'generation_timeout' },
+ expectedReason: 'generation_timeout',
+ },
+ {
+ description: 'failed downloads without a reason use the fallback',
+ download: { status: 'failed' },
+ expectedReason: 'generation_failed',
+ },
+ {
+ description: 'completed downloads without media are unavailable',
+ download: { status: 'completed' },
+ expectedReason: 'completed_without_file',
+ },
+ ])('$description', ({ download, expectedReason }) => {
+ expect(getFathomMediaDownloadFailureReason(download)).toBe(expectedReason);
+ });
+});
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/is-fathom-call-recording-import-complete.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/is-fathom-call-recording-import-complete.test.ts
new file mode 100644
index 00000000000..24b18f6eaaf
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/is-fathom-call-recording-import-complete.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+
+import { isFathomCallRecordingImportComplete } from 'src/logic-functions/utils/is-fathom-call-recording-import-complete.util';
+
+describe('isFathomCallRecordingImportComplete', () => {
+ it.each([
+ { hasVideo: true, hasAudio: false, failureReason: undefined },
+ { hasVideo: false, hasAudio: true, failureReason: undefined },
+ {
+ hasVideo: false,
+ hasAudio: false,
+ failureReason: 'no_downloadable_media',
+ },
+ ])('completes when transcript and media are terminal', (mediaState) => {
+ expect(
+ isFathomCallRecordingImportComplete({
+ hasTranscript: true,
+ ...mediaState,
+ }),
+ ).toBe(true);
+ });
+
+ it('waits for media after the transcript arrives', () => {
+ expect(
+ isFathomCallRecordingImportComplete({
+ hasTranscript: true,
+ hasVideo: false,
+ hasAudio: false,
+ failureReason: undefined,
+ }),
+ ).toBe(false);
+ });
+
+ it('waits for the transcript after media arrives', () => {
+ expect(
+ isFathomCallRecordingImportComplete({
+ hasTranscript: false,
+ hasVideo: true,
+ hasAudio: false,
+ failureReason: undefined,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/map-call-recording-media-state.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/map-call-recording-media-state.test.ts
new file mode 100644
index 00000000000..cb1d37ddcfe
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/map-call-recording-media-state.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from 'vitest';
+
+import { mapCallRecordingMediaState } from 'src/logic-functions/utils/map-call-recording-media-state.util';
+
+describe('mapCallRecordingMediaState', () => {
+ it('maps persisted media state and a valid upload checkpoint', () => {
+ expect(
+ mapCallRecordingMediaState({
+ id: 'call-recording-id',
+ updatedAt: '2026-09-05T00:00:00.000Z',
+ video: [{ fileId: 'video-file-id' }],
+ audio: [{ fileId: null }],
+ fathomRecordingImports: {
+ edges: [
+ {
+ node: {
+ id: 'fathom-recording-import-id',
+ updatedAt: '2026-09-05T00:01:00.000Z',
+ recordingId: 'recording-id',
+ mediaFailureReason: 'failure-reason',
+ connectedAccountId: 'connected-account-id',
+ mediaDownloadId: 'download-id',
+ mediaImportClaimedAt: '2026-09-05T00:00:30.000Z',
+ mediaUploadCheckpoint: {
+ downloadId: 'download-id',
+ fileId: 'video-file-id',
+ kind: 'video',
+ },
+ },
+ },
+ ],
+ },
+ transcript: [{}],
+ summary: { markdown: 'Summary', blocknote: null },
+ }),
+ ).toEqual({
+ id: 'call-recording-id',
+ updatedAt: '2026-09-05T00:00:00.000Z',
+ fathomRecordingImportId: 'fathom-recording-import-id',
+ fathomRecordingImportUpdatedAt: '2026-09-05T00:01:00.000Z',
+ recordingId: 'recording-id',
+ hasVideo: true,
+ hasAudio: false,
+ hasTranscript: true,
+ hasSummary: true,
+ failureReason: 'failure-reason',
+ connectedAccountId: 'connected-account-id',
+ downloadId: 'download-id',
+ uploadCheckpoint: {
+ downloadId: 'download-id',
+ fileId: 'video-file-id',
+ kind: 'video',
+ },
+ });
+ });
+
+ it('normalizes empty media fields and rejects a malformed checkpoint', () => {
+ expect(
+ mapCallRecordingMediaState({
+ id: 'call-recording-id',
+ updatedAt: '2026-09-05T00:00:00.000Z',
+ video: [{ fileId: '' }, {}, { fileId: null }],
+ audio: null,
+ fathomRecordingImports: {
+ edges: [
+ {
+ node: {
+ id: '',
+ updatedAt: '',
+ recordingId: '',
+ mediaFailureReason: '',
+ connectedAccountId: null,
+ mediaDownloadId: null,
+ mediaUploadCheckpoint: {
+ downloadId: 'download-id',
+ fileId: '',
+ kind: 'video',
+ },
+ },
+ },
+ ],
+ },
+ transcript: {},
+ summary: { markdown: '', blocknote: null },
+ }),
+ ).toEqual({
+ id: 'call-recording-id',
+ updatedAt: '2026-09-05T00:00:00.000Z',
+ fathomRecordingImportId: undefined,
+ fathomRecordingImportUpdatedAt: undefined,
+ recordingId: undefined,
+ hasVideo: false,
+ hasAudio: false,
+ hasTranscript: false,
+ hasSummary: false,
+ failureReason: undefined,
+ connectedAccountId: undefined,
+ downloadId: undefined,
+ uploadCheckpoint: undefined,
+ });
+ });
+
+ it('detects summary content stored as blocknote', () => {
+ const mediaState = mapCallRecordingMediaState({
+ id: 'call-recording-id',
+ updatedAt: '2026-09-05T00:00:00.000Z',
+ fathomRecordingImports: null,
+ summary: { markdown: null, blocknote: {} },
+ });
+
+ expect(mediaState.hasSummary).toBe(true);
+ });
+});
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/open-fathom-media-download.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/open-fathom-media-download.test.ts
new file mode 100644
index 00000000000..d2ec513e419
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/open-fathom-media-download.test.ts
@@ -0,0 +1,54 @@
+import { createServer, type Server } from 'node:http';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { openFathomMediaDownload } from 'src/logic-functions/utils/open-fathom-media-download.util';
+
+const openServers: Server[] = [];
+
+const startEmptyDownloadServer = async (): Promise<string> => {
+ const server = createServer((_request, response) => {
+ response.writeHead(200, { 'content-length': '0' });
+ response.end();
+ });
+
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ openServers.push(server);
+
+ const address = server.address();
+
+ if (address === null || typeof address === 'string') {
+ throw new Error('Download test server did not bind a TCP port');
+ }
+
+ return `http://127.0.0.1:${address.port}/download`;
+};
+
+afterEach(async () => {
+ await Promise.all(
+ openServers
+ .splice(0)
+ .map(
+ async (server) =>
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) =>
+ error === undefined ? resolve() : reject(error),
+ ),
+ ),
+ ),
+ );
+});
+
+describe('openFathomMediaDownload', () => {
+ it('reports an empty provider download without opening an upload', async () => {
+ const downloadUrl = await startEmptyDownloadServer();
+
+ await expect(
+ openFathomMediaDownload({
+ callRecordingId: 'call-recording-id',
+ fileName: 'video.mp4',
+ downloadFile: { url: downloadUrl },
+ }),
+ ).resolves.toEqual({ outcome: 'empty' });
+ });
+});
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/put-fathom-media-body-to-upload-target.test.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/put-fathom-media-body-to-upload-target.test.ts
new file mode 100644
index 00000000000..2a1f1d859b9
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/__tests__/put-fathom-media-body-to-upload-target.test.ts
@@ -0,0 +1,125 @@
+import { createServer, type Server } from 'node:http';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { putFathomMediaBodyToUploadTarget } from 'src/logic-functions/utils/put-fathom-media-body-to-upload-target.util';
+
+const openServers: Server[] = [];
+
+const startUploadServer = async ({
+ statusCode,
+ uploadedChunks,
+ receivedHeaders,
+}: {
+ statusCode: number;
+ uploadedChunks?: Buffer[];
+ receivedHeaders?: Record<string, string | string[] | undefined>;
+}): Promise<string> => {
+ const server = createServer((request, response) => {
+ if (receivedHeaders !== undefined) {
+ Object.assign(receivedHeaders, request.headers);
+ }
+
+ request.on('data', (chunk: Buffer) => uploadedChunks?.push(chunk));
+ request.on('end', () => {
+ response.writeHead(statusCode);
+ response.end();
+ });
+ });
+
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ openServers.push(server);
+
+ const address = server.address();
+
+ if (address === null || typeof address === 'string') {
+ throw new Error('Upload test server did not bind a TCP port');
+ }
+
+ return `http://127.0.0.1:${address.port}/upload`;
+};
+
+const buildMediaBody = (bytes: number[]): ReadableStream<Uint8Array> =>
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(Uint8Array.from(bytes));
+ controller.close();
+ },
+ });
+
+afterEach(async () => {
+ await Promise.all(
+ openServers
+ .splice(0)
+ .map(
+ async (server) =>
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) =>
+ error === undefined ? resolve() : reject(error),
+ ),
+ ),
+ ),
+ );
+});
+
+describe('putFathomMediaBodyToUploadTarget', () => {
+ it('streams the media body to an upload target with its declared headers', async () => {
+ const uploadedChunks: Buffer[] = [];
+ const receivedHeaders: Record<string, string | string[] | undefined> = {};
+ const uploadUrl = await startUploadServer({
+ statusCode: 200,
+ uploadedChunks,
+ receivedHeaders,
+ });
+
+ await putFathomMediaBodyToUploadTarget({
+ callRecordingId: 'call-recording-id',
+ fileName: 'video.mp4',
+ mediaDownloadBody: buildMediaBody([1, 2, 3, 4]),
+ sizeBytes: 4,
+ uploadTarget: { uploadUrl, contentType: 'video/mp4' },
+ });
+
+ expect(receivedHeaders['content-type']).toBe('video/mp4');
+ expect(receivedHeaders['content-length']).toBe('4');
+ expect(Buffer.concat(uploadedChunks)).toEqual(Buffer.from([1, 2, 3, 4]));
+ });
+
+ it('rejects a failed storage response', async () => {
+ const uploadUrl = await startUploadServer({ statusCode: 500 });
+
+ await expect(
+ putFathomMediaBodyToUploadTarget({
+ callRecordingId: 'call-recording-id',
+ fileName: 'video.mp4',
+ mediaDownloadBody: buildMediaBody([1, 2, 3, 4]),
+ sizeBytes: 4,
+ uploadTarget: { uploadUrl, contentType: 'video/mp4' },
+ }),
+ ).rejects.toThrow('upload of video.mp4 failed with status 500');
+ });
+
+ it('cancels the media body when the upload request cannot be created', async () => {
+ let isCancelled = false;
+ const mediaDownloadBody = new ReadableStream<Uint8Array>({
+ cancel() {
+ isCancelled = true;
+ },
+ });
+
+ await expect(
+ putFathomMediaBodyToUploadTarget({
+ callRecordingId: 'call-recording-id',
+ fileName: 'video.mp4',
+ mediaDownloadBody,
+ sizeBytes: 4,
+ uploadTarget: {
+ uploadUrl: 'not-a-valid-upload-url',
+ contentType: 'video/mp4',
+ },
+ }),
+ ).rejects.toThrow();
+
+ expect(isCancelled).toBe(true);
+ });
+});
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/build-fathom-media-write-fence.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/build-fathom-media-write-fence.util.ts
new file mode 100644
index 00000000000..ea281ee8e00
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/build-fathom-media-write-fence.util.ts
@@ -0,0 +1,13 @@
+import { type FathomMediaWriteContext } from 'src/logic-functions/types/fathom-media-write-context.type';
+import { isDefined } from 'src/utils/is-defined';
+
+export const buildFathomMediaWriteFence = (
+ writeContext: FathomMediaWriteContext,
+) => ({
+ id: { eq: writeContext.fathomRecordingImportId },
+ connectedAccountId: { eq: writeContext.connectedAccountId },
+ mediaImportClaimedAt: { eq: writeContext.claimedAt },
+ mediaDownloadId: isDefined(writeContext.downloadId)
+ ? { eq: writeContext.downloadId }
+ : { is: 'NULL' as const },
+});
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/cancel-fathom-media-download-body.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/cancel-fathom-media-download-body.util.ts
new file mode 100644
index 00000000000..6a1812bdead
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/cancel-fathom-media-download-body.util.ts
@@ -0,0 +1,23 @@
+import { isNull } from '@sniptt/guards';
+
+import { toErrorMessage } from 'src/logic-functions/utils/to-error-message.util';
+
+export const cancelFathomMediaDownloadBody = async ({
+ body,
+ callRecordingId,
+ fileName,
+}: {
+ body: ReadableStream<Uint8Array> | null;
+ callRecordingId: string;
+ fileName: string;
+}): Promise<void> => {
+ if (isNull(body)) {
+ return;
+ }
+
+ await body.cancel().catch((error: unknown) => {
+ console.warn(
+ `[fathom] media download body cancellation failed callRecordingId=${callRecordingId} fileName=${fileName}: ${toErrorMessage(error)}`,
+ );
+ });
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/claim-fathom-media-import.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/claim-fathom-media-import.util.ts
new file mode 100644
index 00000000000..be84e8da4a9
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/claim-fathom-media-import.util.ts
@@ -0,0 +1,41 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { FATHOM_MEDIA_IMPORT_CLAIM_DURATION_MILLISECONDS } from 'src/constants/fathom.constant';
+
+export type FathomMediaImportClaim = {
+ claimedAt: string;
+};
+
+export const claimFathomMediaImport = async ({
+ coreApiClient,
+ fathomRecordingImportId,
+ now,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'mutation'>;
+ fathomRecordingImportId: string;
+ now: Date;
+}): Promise<FathomMediaImportClaim | undefined> => {
+ const claimedAt = now.toISOString();
+ const staleBefore = new Date(
+ now.getTime() - FATHOM_MEDIA_IMPORT_CLAIM_DURATION_MILLISECONDS,
+ ).toISOString();
+ const mutationResult = await coreApiClient.mutation({
+ updateFathomRecordingImports: {
+ __args: {
+ filter: {
+ id: { eq: fathomRecordingImportId },
+ or: [
+ { mediaImportClaimedAt: { is: 'NULL' } },
+ { mediaImportClaimedAt: { lte: staleBefore } },
+ ],
+ },
+ data: { mediaImportClaimedAt: claimedAt },
+ },
+ id: true,
+ },
+ });
+
+ return (mutationResult.updateFathomRecordingImports ?? []).length === 0
+ ? undefined
+ : { claimedAt };
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/complete-fathom-call-recording-import.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/complete-fathom-call-recording-import.util.ts
new file mode 100644
index 00000000000..c21ae613bc6
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/complete-fathom-call-recording-import.util.ts
@@ -0,0 +1,50 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { isDefined } from 'src/utils/is-defined';
+
+import { findCallRecordingMediaState } from 'src/logic-functions/utils/find-call-recording-media-state.util';
+import { isFathomCallRecordingImportComplete } from 'src/logic-functions/utils/is-fathom-call-recording-import-complete.util';
+
+export const completeFathomCallRecordingImport = async ({
+ coreApiClient,
+ callRecordingId,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;
+ callRecordingId: string;
+}): Promise<boolean> => {
+ const callRecording = await findCallRecordingMediaState({
+ coreApiClient,
+ callRecordingId,
+ });
+
+ if (
+ !isDefined(callRecording) ||
+ !isNonEmptyString(callRecording.fathomRecordingImportId) ||
+ !isNonEmptyString(callRecording.fathomRecordingImportUpdatedAt) ||
+ !isFathomCallRecordingImportComplete(callRecording)
+ ) {
+ return false;
+ }
+
+ const mutationResult = await coreApiClient.mutation({
+ updateCallRecordings: {
+ __args: {
+ filter: {
+ id: { eq: callRecordingId },
+ updatedAt: { eq: callRecording.updatedAt },
+ status: { eq: 'PROCESSING' },
+ fathomRecordingImports: {
+ id: { eq: callRecording.fathomRecordingImportId },
+ updatedAt: {
+ eq: callRecording.fathomRecordingImportUpdatedAt,
+ },
+ },
+ },
+ data: { status: 'COMPLETED' },
+ },
+ id: true,
+ },
+ });
+
+ return (mutationResult.updateCallRecordings ?? []).length > 0;
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/complete-fathom-media-file-upload.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/complete-fathom-media-file-upload.util.ts
new file mode 100644
index 00000000000..1ab6baab52e
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/complete-fathom-media-file-upload.util.ts
@@ -0,0 +1,23 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+
+export const completeFathomMediaFileUpload = async ({
+ fileId,
+}: {
+ fileId: string;
+}): Promise<string> => {
+ const metadataClient = new MetadataApiClient();
+ const mutationResult = await metadataClient.mutation({
+ completeFileUpload: {
+ __args: { fileId },
+ id: true,
+ },
+ });
+ const uploadedFileId = mutationResult.completeFileUpload?.id;
+
+ if (!isNonEmptyString(uploadedFileId)) {
+ throw new Error('completeFileUpload mutation did not return a file id');
+ }
+
+ return uploadedFileId;
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/find-call-recording-media-state.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/find-call-recording-media-state.util.ts
new file mode 100644
index 00000000000..aaa4ccf5fc3
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/find-call-recording-media-state.util.ts
@@ -0,0 +1,57 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { isDefined } from 'src/utils/is-defined';
+
+import { callRecordingMediaStateQueryResultSchema } from 'src/logic-functions/schemas/call-recording-media-state-query-result.schema';
+import { type CallRecordingMediaState } from 'src/logic-functions/types/call-recording-media-state.type';
+import { mapCallRecordingMediaState } from 'src/logic-functions/utils/map-call-recording-media-state.util';
+
+export const findCallRecordingMediaState = async ({
+ coreApiClient,
+ callRecordingId,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query'>;
+ callRecordingId: string;
+}): Promise<CallRecordingMediaState | undefined> => {
+ const queryResult = await coreApiClient.query({
+ callRecordings: {
+ __args: {
+ filter: { id: { eq: callRecordingId } },
+ first: 1,
+ },
+ edges: {
+ node: {
+ id: true,
+ updatedAt: true,
+ summary: { markdown: true, blocknote: true },
+ video: { fileId: true },
+ audio: { fileId: true },
+ fathomRecordingImports: {
+ __args: { first: 1 },
+ edges: {
+ node: {
+ id: true,
+ updatedAt: true,
+ recordingId: true,
+ connectedAccountId: true,
+ mediaDownloadId: true,
+ mediaFailureReason: true,
+ mediaImportClaimedAt: true,
+ mediaUploadCheckpoint: true,
+ },
+ },
+ },
+ transcript: true,
+ },
+ },
+ },
+ });
+ const parsedQueryResult =
+ callRecordingMediaStateQueryResultSchema.parse(queryResult);
+ const node = parsedQueryResult.callRecordings?.edges[0]?.node;
+
+ if (!isDefined(node)) {
+ return undefined;
+ }
+
+ return mapCallRecordingMediaState(node);
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-media-download-failure-reason.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-media-download-failure-reason.util.ts
new file mode 100644
index 00000000000..205b24d0b10
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/get-fathom-media-download-failure-reason.util.ts
@@ -0,0 +1,29 @@
+import { type RecordingDownload } from 'fathom-typescript/sdk/models/shared';
+
+import { FATHOM_MEDIA_FAILURE_REASON } from 'src/constants/fathom-media-failure-reason.constant';
+import { isDefined } from 'src/utils/is-defined';
+
+export const getFathomMediaDownloadFailureReason = (
+ download: Pick<
+ RecordingDownload,
+ 'status' | 'failureReason' | 'video' | 'audio'
+ >,
+): string | undefined => {
+ if (download.status === 'processing') {
+ return undefined;
+ }
+
+ if (download.status === 'expired') {
+ return FATHOM_MEDIA_FAILURE_REASON.DOWNLOAD_EXPIRED;
+ }
+
+ if (download.status === 'failed') {
+ return download.failureReason ?? 'generation_failed';
+ }
+
+ if (!isDefined(download.video) && !isDefined(download.audio)) {
+ return FATHOM_MEDIA_FAILURE_REASON.COMPLETED_WITHOUT_FILE;
+ }
+
+ return undefined;
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/import-fathom-media-file.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/import-fathom-media-file.util.ts
new file mode 100644
index 00000000000..8beb0c929cc
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/import-fathom-media-file.util.ts
@@ -0,0 +1,101 @@
+import { type RecordingDownloadFile } from 'fathom-typescript/sdk/models/shared';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { FATHOM_MEDIA_MAX_FILE_SIZE_BYTES } from 'src/constants/fathom.constant';
+import {
+ CALL_RECORDING_AUDIO_FIELD_UNIVERSAL_IDENTIFIER,
+ CALL_RECORDING_VIDEO_FIELD_UNIVERSAL_IDENTIFIER,
+} from 'src/constants/universal-identifiers';
+import { type FathomMediaKind } from 'src/logic-functions/schemas/fathom-media-kind.schema';
+import { type CallRecordingMediaFile } from 'src/logic-functions/types/call-recording-media-file.type';
+import { type FathomMediaWriteContext } from 'src/logic-functions/types/fathom-media-write-context.type';
+import { completeFathomMediaFileUpload } from 'src/logic-functions/utils/complete-fathom-media-file-upload.util';
+import { openFathomMediaDownload } from 'src/logic-functions/utils/open-fathom-media-download.util';
+import { uploadFathomMediaStream } from 'src/logic-functions/utils/upload-fathom-media-stream.util';
+import { updateFathomMediaUploadCheckpoint } from 'src/logic-functions/utils/update-fathom-media-upload-checkpoint.util';
+
+export type { FathomMediaKind } from 'src/logic-functions/schemas/fathom-media-kind.schema';
+
+export type ImportFathomMediaFileResult =
+ | { outcome: 'imported'; files: CallRecordingMediaFile[] }
+ | { outcome: 'empty' }
+ | { outcome: 'stale' }
+ | { outcome: 'too-large'; sizeBytes: number };
+
+const MEDIA_DESCRIPTOR_BY_KIND = {
+ video: {
+ fileName: 'video.mp4',
+ fieldMetadataUniversalIdentifier:
+ CALL_RECORDING_VIDEO_FIELD_UNIVERSAL_IDENTIFIER,
+ },
+ audio: {
+ fileName: 'audio.mp3',
+ fieldMetadataUniversalIdentifier:
+ CALL_RECORDING_AUDIO_FIELD_UNIVERSAL_IDENTIFIER,
+ },
+} satisfies Record<
+ FathomMediaKind,
+ { fileName: string; fieldMetadataUniversalIdentifier: string }
+>;
+
+export const importFathomMediaFile = async ({
+ callRecordingId,
+ coreApiClient,
+ downloadId,
+ writeContext,
+ kind,
+ downloadFile,
+}: {
+ callRecordingId: string;
+ coreApiClient: Pick<CoreApiClient, 'mutation'>;
+ downloadId: string;
+ writeContext: FathomMediaWriteContext;
+ kind: FathomMediaKind;
+ downloadFile: Pick<RecordingDownloadFile, 'fileSizeBytes' | 'url'>;
+}): Promise<ImportFathomMediaFileResult> => {
+ const { fileName, fieldMetadataUniversalIdentifier } =
+ MEDIA_DESCRIPTOR_BY_KIND[kind];
+
+ if (
+ !Number.isSafeInteger(downloadFile.fileSizeBytes) ||
+ downloadFile.fileSizeBytes <= 0
+ ) {
+ return { outcome: 'empty' };
+ }
+
+ if (downloadFile.fileSizeBytes > FATHOM_MEDIA_MAX_FILE_SIZE_BYTES) {
+ return { outcome: 'too-large', sizeBytes: downloadFile.fileSizeBytes };
+ }
+
+ const download = await openFathomMediaDownload({
+ callRecordingId,
+ fileName,
+ downloadFile,
+ });
+
+ if (download.outcome !== 'opened') {
+ return download;
+ }
+
+ const fileId = await uploadFathomMediaStream({
+ callRecordingId,
+ fileName,
+ fieldMetadataUniversalIdentifier,
+ body: download.body,
+ sizeBytes: download.sizeBytes,
+ });
+
+ const wasCheckpointSaved = await updateFathomMediaUploadCheckpoint({
+ coreApiClient,
+ writeContext,
+ uploadCheckpoint: { downloadId, fileId, kind },
+ });
+
+ if (!wasCheckpointSaved) {
+ return { outcome: 'stale' };
+ }
+
+ await completeFathomMediaFileUpload({ fileId });
+
+ return { outcome: 'imported', files: [{ fileId, label: fileName }] };
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-fathom-call-recording-import-complete.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-fathom-call-recording-import-complete.util.ts
new file mode 100644
index 00000000000..0f6be47bd82
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-fathom-call-recording-import-complete.util.ts
@@ -0,0 +1,10 @@
+import { type CallRecordingMediaState } from 'src/logic-functions/types/call-recording-media-state.type';
+import { isFathomMediaSettled } from 'src/logic-functions/utils/is-fathom-media-settled.util';
+
+export const isFathomCallRecordingImportComplete = (
+ callRecording: Pick<
+ CallRecordingMediaState,
+ 'hasTranscript' | 'hasVideo' | 'hasAudio' | 'failureReason'
+ >,
+): boolean =>
+ callRecording.hasTranscript && isFathomMediaSettled(callRecording);
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-fathom-media-settled.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-fathom-media-settled.util.ts
new file mode 100644
index 00000000000..4c6eeeb1869
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/is-fathom-media-settled.util.ts
@@ -0,0 +1,13 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type CallRecordingMediaState } from 'src/logic-functions/types/call-recording-media-state.type';
+
+export const isFathomMediaSettled = (
+ callRecording: Pick<
+ CallRecordingMediaState,
+ 'hasVideo' | 'hasAudio' | 'failureReason'
+ >,
+): boolean =>
+ callRecording.hasVideo ||
+ callRecording.hasAudio ||
+ isNonEmptyString(callRecording.failureReason);
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/map-call-recording-media-state.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/map-call-recording-media-state.util.ts
new file mode 100644
index 00000000000..ef776427387
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/map-call-recording-media-state.util.ts
@@ -0,0 +1,54 @@
+import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
+import { type z } from 'zod';
+
+import {
+ type callRecordingMediaStateNodeSchema,
+ fathomMediaUploadCheckpointSchema,
+} from 'src/logic-functions/schemas/call-recording-media-state-query-result.schema';
+import { type CallRecordingMediaState } from 'src/logic-functions/types/call-recording-media-state.type';
+import { isDefined } from 'src/utils/is-defined';
+
+export const mapCallRecordingMediaState = (
+ node: z.infer<typeof callRecordingMediaStateNodeSchema>,
+): CallRecordingMediaState => {
+ const recordingImport = node.fathomRecordingImports?.edges[0]?.node;
+ const uploadCheckpointResult = fathomMediaUploadCheckpointSchema.safeParse(
+ recordingImport?.mediaUploadCheckpoint,
+ );
+
+ return {
+ id: node.id,
+ updatedAt: node.updatedAt,
+ fathomRecordingImportId: isNonEmptyString(recordingImport?.id)
+ ? recordingImport.id
+ : undefined,
+ fathomRecordingImportUpdatedAt: isNonEmptyString(
+ recordingImport?.updatedAt,
+ )
+ ? recordingImport.updatedAt
+ : undefined,
+ recordingId: isNonEmptyString(recordingImport?.recordingId)
+ ? recordingImport.recordingId
+ : undefined,
+ hasVideo:
+ node.video?.some((file) => isNonEmptyString(file.fileId)) ?? false,
+ hasAudio:
+ node.audio?.some((file) => isNonEmptyString(file.fileId)) ?? false,
+ hasTranscript: isNonEmptyArray(node.transcript),
+ hasSummary:
+ isNonEmptyString(node.summary?.markdown) ||
+ isDefined(node.summary?.blocknote),
+ failureReason: isNonEmptyString(recordingImport?.mediaFailureReason)
+ ? recordingImport.mediaFailureReason
+ : undefined,
+ connectedAccountId: isNonEmptyString(recordingImport?.connectedAccountId)
+ ? recordingImport.connectedAccountId
+ : undefined,
+ downloadId: isNonEmptyString(recordingImport?.mediaDownloadId)
+ ? recordingImport.mediaDownloadId
+ : undefined,
+ uploadCheckpoint: uploadCheckpointResult.success
+ ? uploadCheckpointResult.data
+ : undefined,
+ };
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/open-fathom-media-download.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/open-fathom-media-download.util.ts
new file mode 100644
index 00000000000..38512ce71ce
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/open-fathom-media-download.util.ts
@@ -0,0 +1,81 @@
+import { isNonEmptyString, isNull, isUndefined } from '@sniptt/guards';
+import { type RecordingDownloadFile } from 'fathom-typescript/sdk/models/shared';
+
+import {
+ FATHOM_MEDIA_DOWNLOAD_TIMEOUT_MILLISECONDS,
+ FATHOM_MEDIA_MAX_FILE_SIZE_BYTES,
+} from 'src/constants/fathom.constant';
+import { cancelFathomMediaDownloadBody } from 'src/logic-functions/utils/cancel-fathom-media-download-body.util';
+
+export type OpenFathomMediaDownloadResult =
+ | { outcome: 'opened'; body: ReadableStream<Uint8Array>; sizeBytes: number }
+ | { outcome: 'empty' }
+ | { outcome: 'too-large'; sizeBytes: number };
+
+export const openFathomMediaDownload = async ({
+ callRecordingId,
+ fileName,
+ downloadFile,
+}: {
+ callRecordingId: string;
+ fileName: string;
+ downloadFile: Pick<RecordingDownloadFile, 'url'>;
+}): Promise<OpenFathomMediaDownloadResult> => {
+ const response = await fetch(downloadFile.url, {
+ signal: AbortSignal.timeout(FATHOM_MEDIA_DOWNLOAD_TIMEOUT_MILLISECONDS),
+ });
+ const contentLengthBytes = parseContentLengthBytes(
+ response.headers.get('content-length'),
+ );
+
+ if (
+ !response.ok ||
+ isUndefined(contentLengthBytes) ||
+ contentLengthBytes > FATHOM_MEDIA_MAX_FILE_SIZE_BYTES ||
+ contentLengthBytes === 0
+ ) {
+ await cancelFathomMediaDownloadBody({
+ callRecordingId,
+ fileName,
+ body: response.body,
+ });
+
+ if (!response.ok) {
+ throw new Error(`download failed with status ${response.status}`);
+ }
+
+ if (isUndefined(contentLengthBytes)) {
+ throw new Error('download response is missing content-length');
+ }
+
+ if (contentLengthBytes > FATHOM_MEDIA_MAX_FILE_SIZE_BYTES) {
+ return { outcome: 'too-large', sizeBytes: contentLengthBytes };
+ }
+
+ return { outcome: 'empty' };
+ }
+
+ if (isNull(response.body)) {
+ throw new Error('download returned no body');
+ }
+
+ return {
+ outcome: 'opened',
+ body: response.body,
+ sizeBytes: contentLengthBytes,
+ };
+};
+
+const parseContentLengthBytes = (
+ headerValue: string | null,
+): number | undefined => {
+ if (!isNonEmptyString(headerValue)) {
+ return undefined;
+ }
+
+ const parsedBytes = Number(headerValue.trim());
+
+ return Number.isSafeInteger(parsedBytes) && parsedBytes >= 0
+ ? parsedBytes
+ : undefined;
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/put-fathom-media-body-to-upload-target.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/put-fathom-media-body-to-upload-target.util.ts
new file mode 100644
index 00000000000..783a3b5087d
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/put-fathom-media-body-to-upload-target.util.ts
@@ -0,0 +1,145 @@
+import { request as requestOverHttp, type IncomingMessage } from 'node:http';
+import { request as requestOverHttps } from 'node:https';
+import { Readable } from 'node:stream';
+import { finished, pipeline } from 'node:stream/promises';
+
+import { FATHOM_MEDIA_UPLOAD_TIMEOUT_MILLISECONDS } from 'src/constants/fathom.constant';
+import { cancelFathomMediaDownloadBody } from 'src/logic-functions/utils/cancel-fathom-media-download-body.util';
+
+type MediaUploadTarget = {
+ uploadUrl: string;
+ contentType: string;
+};
+
+const HTTP_STATUS_OK_LOWER_BOUND = 200;
+const HTTP_STATUS_OK_UPPER_BOUND = 300;
+
+export const putFathomMediaBodyToUploadTarget = async ({
+ callRecordingId,
+ mediaDownloadBody,
+ fileName,
+ sizeBytes,
+ uploadTarget,
+}: {
+ callRecordingId: string;
+ mediaDownloadBody: ReadableStream<Uint8Array>;
+ fileName: string;
+ sizeBytes: number;
+ uploadTarget: MediaUploadTarget;
+}): Promise<void> => {
+ const mediaDownloadReadable = Readable.from(
+ readMediaDownloadBody({ mediaDownloadBody }),
+ );
+
+ await streamMediaDownloadReadableToUploadTarget({
+ fileName,
+ mediaDownloadReadable,
+ sizeBytes,
+ uploadTarget,
+ }).catch(async (error: unknown) => {
+ await cancelFathomMediaDownloadBody({
+ body: mediaDownloadBody,
+ callRecordingId,
+ fileName,
+ });
+
+ throw error;
+ });
+};
+
+const readMediaDownloadBody = async function* ({
+ mediaDownloadBody,
+}: {
+ mediaDownloadBody: ReadableStream<Uint8Array>;
+}) {
+ const reader = mediaDownloadBody.getReader();
+ let isComplete = false;
+
+ try {
+ while (true) {
+ const chunk = await reader.read();
+
+ if (chunk.done) {
+ isComplete = true;
+ return;
+ }
+
+ yield chunk.value;
+ }
+ } finally {
+ if (!isComplete) {
+ await reader.cancel().catch(() => undefined);
+ }
+
+ reader.releaseLock();
+ }
+};
+
+const streamMediaDownloadReadableToUploadTarget = async ({
+ fileName,
+ mediaDownloadReadable,
+ sizeBytes,
+ uploadTarget,
+}: {
+ fileName: string;
+ mediaDownloadReadable: Readable;
+ sizeBytes: number;
+ uploadTarget: MediaUploadTarget;
+}): Promise<void> => {
+ const uploadUrl = new URL(uploadTarget.uploadUrl);
+ const requestUpload =
+ uploadUrl.protocol === 'http:' ? requestOverHttp : requestOverHttps;
+ const uploadRequest = requestUpload(uploadUrl, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': uploadTarget.contentType,
+ 'Content-Length': sizeBytes,
+ },
+ signal: AbortSignal.timeout(FATHOM_MEDIA_UPLOAD_TIMEOUT_MILLISECONDS),
+ });
+
+ const uploadResponsePromise = new Promise<IncomingMessage>(
+ (resolve, reject) => {
+ uploadRequest.once('response', resolve);
+ uploadRequest.once('error', reject);
+ },
+ );
+ const uploadPipelinePromise = pipeline(mediaDownloadReadable, uploadRequest);
+
+ const uploadResponse = await Promise.race([
+ uploadResponsePromise,
+ uploadPipelinePromise.then(async () => await uploadResponsePromise),
+ ]).catch(async (error: unknown) => {
+ mediaDownloadReadable.destroy();
+ uploadRequest.destroy();
+ await uploadPipelinePromise.catch(() => undefined);
+
+ throw error;
+ });
+
+ uploadResponse.resume();
+
+ const uploadResponseBodyDrainPromise = finished(uploadResponse);
+ const uploadStatusCode = uploadResponse.statusCode ?? 0;
+
+ if (
+ uploadStatusCode < HTTP_STATUS_OK_LOWER_BOUND ||
+ uploadStatusCode >= HTTP_STATUS_OK_UPPER_BOUND
+ ) {
+ const uploadError = new Error(
+ `upload of ${fileName} failed with status ${uploadStatusCode}`,
+ );
+
+ mediaDownloadReadable.destroy(uploadError);
+ uploadRequest.destroy(uploadError);
+
+ await Promise.allSettled([
+ uploadPipelinePromise,
+ uploadResponseBodyDrainPromise,
+ ]);
+
+ throw uploadError;
+ }
+
+ await Promise.all([uploadPipelinePromise, uploadResponseBodyDrainPromise]);
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/record-fathom-media-failure.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/record-fathom-media-failure.util.ts
new file mode 100644
index 00000000000..07637963b5e
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/record-fathom-media-failure.util.ts
@@ -0,0 +1,23 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { settleCallRecordingMedia } from 'src/logic-functions/utils/settle-call-recording-media.util';
+import { type FathomMediaWriteContext } from 'src/logic-functions/types/fathom-media-write-context.type';
+
+export const recordFathomMediaFailure = async ({
+ coreApiClient,
+ callRecordingId,
+ reason,
+ writeContext,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;
+ callRecordingId: string;
+ reason: string;
+ writeContext: FathomMediaWriteContext;
+}): Promise<boolean> => {
+ return settleCallRecordingMedia({
+ coreApiClient,
+ callRecordingId,
+ writeContext,
+ fields: { mediaFailureReason: reason },
+ });
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/settle-call-recording-media.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/settle-call-recording-media.util.ts
new file mode 100644
index 00000000000..550f3e50ba2
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/settle-call-recording-media.util.ts
@@ -0,0 +1,61 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { type CallRecordingSyncFields } from 'src/logic-functions/types/call-recording-sync-fields.type';
+import { type FathomRecordingImportFields } from 'src/logic-functions/types/fathom-recording-import-fields.type';
+import { type FathomMediaWriteContext } from 'src/logic-functions/types/fathom-media-write-context.type';
+import { completeFathomCallRecordingImport } from 'src/logic-functions/utils/complete-fathom-call-recording-import.util';
+import { updateCallRecordingMedia } from 'src/logic-functions/utils/update-call-recording-media.util';
+import { updateFathomRecordingImport } from 'src/logic-functions/utils/update-fathom-recording-import.util';
+import { isDefined } from 'src/utils/is-defined';
+
+export const settleCallRecordingMedia = async ({
+ coreApiClient,
+ callRecordingId,
+ fields,
+ writeContext,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;
+ callRecordingId: string;
+ writeContext: FathomMediaWriteContext;
+ fields: Pick<CallRecordingSyncFields, 'video' | 'audio'> &
+ Pick<FathomRecordingImportFields, 'mediaFailureReason'>;
+}): Promise<boolean> => {
+ if (isDefined(fields.video) || isDefined(fields.audio)) {
+ const isMediaApplied = await updateCallRecordingMedia({
+ coreApiClient,
+ callRecordingId,
+ writeContext,
+ fields: {
+ ...(isDefined(fields.video) ? { video: fields.video } : {}),
+ ...(isDefined(fields.audio) ? { audio: fields.audio } : {}),
+ },
+ });
+
+ if (!isMediaApplied) {
+ return false;
+ }
+ }
+
+ const isImportApplied = await updateFathomRecordingImport({
+ coreApiClient,
+ writeContext,
+ fields: {
+ ...(isDefined(fields.mediaFailureReason)
+ ? { mediaFailureReason: fields.mediaFailureReason }
+ : {}),
+ mediaDownloadId: null,
+ mediaUploadCheckpoint: null,
+ },
+ });
+
+ if (!isImportApplied) {
+ return false;
+ }
+
+ await completeFathomCallRecordingImport({
+ coreApiClient,
+ callRecordingId,
+ });
+
+ return true;
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/update-call-recording-media.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/update-call-recording-media.util.ts
new file mode 100644
index 00000000000..c000146084c
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/update-call-recording-media.util.ts
@@ -0,0 +1,32 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { type CallRecordingSyncFields } from 'src/logic-functions/types/call-recording-sync-fields.type';
+import { type FathomMediaWriteContext } from 'src/logic-functions/types/fathom-media-write-context.type';
+import { buildFathomMediaWriteFence } from 'src/logic-functions/utils/build-fathom-media-write-fence.util';
+
+export const updateCallRecordingMedia = async ({
+ coreApiClient,
+ callRecordingId,
+ fields,
+ writeContext,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'mutation'>;
+ callRecordingId: string;
+ writeContext: FathomMediaWriteContext;
+ fields: Pick<CallRecordingSyncFields, 'video' | 'audio'>;
+}): Promise<boolean> => {
+ const result = await coreApiClient.mutation({
+ updateCallRecordings: {
+ __args: {
+ filter: {
+ id: { eq: callRecordingId },
+ fathomRecordingImports: buildFathomMediaWriteFence(writeContext),
+ },
+ data: fields,
+ },
+ id: true,
+ },
+ });
+
+ return (result.updateCallRecordings ?? []).length > 0;
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/update-fathom-media-upload-checkpoint.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/update-fathom-media-upload-checkpoint.util.ts
new file mode 100644
index 00000000000..e3a78bc7c1c
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/update-fathom-media-upload-checkpoint.util.ts
@@ -0,0 +1,20 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { type FathomMediaUploadCheckpoint } from 'src/logic-functions/types/fathom-media-upload-checkpoint.type';
+import { type FathomMediaWriteContext } from 'src/logic-functions/types/fathom-media-write-context.type';
+import { updateFathomRecordingImport } from 'src/logic-functions/utils/update-fathom-recording-import.util';
+
+export const updateFathomMediaUploadCheckpoint = async ({
+ coreApiClient,
+ uploadCheckpoint,
+ writeContext,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'mutation'>;
+ uploadCheckpoint: FathomMediaUploadCheckpoint | null;
+ writeContext: FathomMediaWriteContext;
+}): Promise<boolean> =>
+ updateFathomRecordingImport({
+ coreApiClient,
+ writeContext,
+ fields: { mediaUploadCheckpoint: uploadCheckpoint },
+ });
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/update-fathom-recording-import.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/update-fathom-recording-import.util.ts
new file mode 100644
index 00000000000..43149e39c4d
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/update-fathom-recording-import.util.ts
@@ -0,0 +1,30 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { type FathomRecordingImportFields } from 'src/logic-functions/types/fathom-recording-import-fields.type';
+import { type FathomMediaWriteContext } from 'src/logic-functions/types/fathom-media-write-context.type';
+import { buildFathomMediaWriteFence } from 'src/logic-functions/utils/build-fathom-media-write-fence.util';
+
+export const updateFathomRecordingImport = async ({
+ coreApiClient,
+ fields,
+ writeContext,
+}: {
+ coreApiClient: Pick<CoreApiClient, 'mutation'>;
+ writeContext: FathomMediaWriteContext;
+ fields: Pick<
+ FathomRecordingImportFields,
+ 'mediaFailureReason' | 'mediaDownloadId' | 'mediaUploadCheckpoint'
+ >;
+}): Promise<boolean> => {
+ const result = await coreApiClient.mutation({
+ updateFathomRecordingImports: {
+ __args: {
+ filter: buildFathomMediaWriteFence(writeContext),
+ data: fields,
+ },
+ id: true,
+ },
+ });
+
+ return (result.updateFathomRecordingImports ?? []).length > 0;
+};
diff --git a/packages/twenty-apps/public/fathom/src/logic-functions/utils/upload-fathom-media-stream.util.ts b/packages/twenty-apps/public/fathom/src/logic-functions/utils/upload-fathom-media-stream.util.ts
new file mode 100644
index 00000000000..04fad7a5ceb
--- /dev/null
+++ b/packages/twenty-apps/public/fathom/src/logic-functions/utils/upload-fathom-media-stream.util.ts
@@ -0,0 +1,69 @@
+import { isNonEmptyString, isUndefined } from '@sniptt/guards';
+import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+
+import { FATHOM_MEDIA_FILE_FOLDER } from 'src/constants/fathom.constant';
+import { cancelFathomMediaDownloadBody } from 'src/logic-functions/utils/cancel-fathom-media-download-body.util';
+import { putFathomMediaBodyToUploadTarget } from 'src/logic-functions/utils/put-fathom-media-body-to-upload-target.util';
+
+export const uploadFathomMediaStream = async ({
+ callRecordingId,
+ fileName,
+ fieldMetadataUniversalIdentifier,
+ body,
+ sizeBytes,
+}: {
+ callRecordingId: string;
+ fileName: string;
+ fieldMetadataUniversalIdentifier: string;
+ body: ReadableStream<Uint8Array>;
+ sizeBytes: number;
+}): Promise<string> => {
+ const metadataClient = new MetadataApiClient();
+ const uploadTarget = await metadataClient
+ .mutation({
+ createFileUpload: {
+ __args: {
+ filename: fileName,
+ size: sizeBytes,
+ fileFolder: FATHOM_MEDIA_FILE_FOLDER,
+ fieldMetadataUniversalIdentifier,
+ },
+ fileId: true,
+ uploadUrl: true,
+ contentType: true,
+ },
+ })
+ .then((mutationResult) => {
+ const uploadTarget = mutationResult.createFileUpload;
+
+ if (
+ isUndefined(uploadTarget) ||
+ !isNonEmptyString(uploadTarget.fileId) ||
+ !isNonEmptyString(uploadTarget.uploadUrl) ||
+ !isNonEmptyString(uploadTarget.contentType)
+ ) {
+ throw new Error('createFileUpload mutation returned an invalid target');
+ }
+
+ return uploadTarget;
+ })
+ .catch(async (error: unknown) => {
+ await cancelFathomMediaDownloadBody({
+ callRecordingId,
+ fileName,
+ body,
+ });
+
+ throw error;
+ });
+
+ await putFathomMediaBodyToUploadTarget({
+ callRecordingId,
+ fileName,
+ mediaDownloadBody: body,
+ sizeBytes,
+ uploadTarget,
+ });
+
+ return uploadTarget.fileId;
+};
diff --git a/packages/twenty-apps/public/fathom/yarn.lock b/packages/twenty-apps/public/fathom/yarn.lock
index dda011d9d20..dfa64f1a66f 100644
--- a/packages/twenty-apps/public/fathom/yarn.lock
+++ b/packages/twenty-apps/public/fathom/yarn.lock
@@ -938,6 +938,7 @@ __metadata:
typescript: "npm:^5.9.3"
vite-tsconfig-paths: "npm:^4.2.1"
vitest: "npm:^4.0.0"
+ zod: "npm:^4.1.11"
languageName: unknown
linkType: soft
@@ -3201,3 +3202,10 @@ __metadata:
checksum: 10c0/7ea31b558e88f9faf44f31dd185e2e1cbf51fed3081787fb96cc2534749b50c0acfc6da7f0922a7353ed092dd358c7d50c28ea96c94d04af64191bd33152eca3
languageName: node
linkType: hard
+
+"zod@npm:^4.1.11":
+ version: 4.5.4
+ resolution: "zod@npm:4.5.4"
+ checksum: 10c0/511a2a4d1a6f875dfdd70a1586989a8b14ef126776cd6218a2c760b9f65f14ef389ec20d92ee1aa4fcb4566d4ff3fa012956044f9dc503510d82e4c756a8ba92
+ languageName: node
+ linkType: hard