Creating .blend file preview when saving files

When I save a file a preview of the .blend file is automatically generated, but when I open Blender as a background process, create a file, and call the same operator bpy.ops.wm.save_as_mainfile(filepath=path) The preview is not generated. If I open the file then save it manually the preview is generated.

no preview with preview

Does anyone know if I am able to have Blender generate the file preview when running Blender as a background process?

It appears that thumbnail creation uses Workbench to render an image of the scene from the current viewport camera. Workbench doesn’t work in headless mode, however. Perhaps you can render the thumbnails with Cycles? This is what I think is the problem.

If I render the thumbnail with cycles how would I assign the image to be used as the thumbnail?

I tried adding a camera, rendering the scene, then setting the render result to use_fake_user = True. All of that works, but the render result still doesn’t save even though the use_fake_user is selected.

I don’t know for certain but maybe start with the bl_preview_renders.py script that comes with each build (e.g. [bin]\2.90\scripts\modules\bl_previews_utils\bl_previews_render.py) This is typically used through the File->Data Previews->Batch Generate Previews menu entry for context.

It seems to use the preview member on various data blocks (data blocks like scenes, objects, and collections) and attaches the rendered item there:
Poor docs: https://docs.blender.org/api/blender2.8/bpy.types.ID.html?highlight=preview#bpy.types.ID.preview
Example from script:

item = ... some datablock from bpy.data...
item.preview.image_size = (RENDER_PREVIEW_SIZE, RENDER_PREVIEW_SIZE)
item.preview.image_pixels_float[:] = image.pixels

I am not sure what datablock the file browser decides to use but the object and collection ones are probably used when going through the .blend during linking and appending. Perhaps just the scene is used for the main file browser?