2026-06-07 19:25:47 +08:00
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { s3Service } from '@shumai/core/src/s3/s3'
2026-06-01 23:08:58 +08:00
import { prisma } from '@shumai/db'
2026-06-02 18:48:54 +08:00
import { setupTestDbHooks } from '@shumai/db/test'
2026-06-07 19:25:47 +08:00
import { beforeEach , describe , expect , it , vi } from 'vitest'
2026-08-09 14:44:13 +08:00
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
2026-07-18 10:32:38 +08:00
import { transcodeService } from '@shumai/core/src/transcode/transcode'
2026-06-18 11:54:30 +08:00
import * as child_process from 'child_process'
2026-09-08 10:17:15 +08:00
import * as fs from 'fs'
2026-06-18 11:54:30 +08:00
vi . mock ( 'child_process' , () => ({
execFile : vi.fn (),
}))
2026-06-05 21:25:08 +08:00
import {
getMediaInfoActivity ,
2026-06-07 19:25:47 +08:00
overlayAnnotationsActivity ,
2026-07-19 09:45:14 +08:00
renderPdfPagesActivity ,
2026-06-07 19:25:47 +08:00
takeScreenshotsActivity ,
2026-06-05 21:25:08 +08:00
transcodeVideoActivity ,
2026-07-05 15:11:19 +08:00
transcodeAudioActivity ,
2026-06-05 21:25:08 +08:00
updateAssetMediaActivity ,
2026-06-14 09:54:29 +08:00
downloadMediaToTmpActivity ,
transcodeImageActivity ,
2026-09-08 10:17:15 +08:00
extractPosterActivity ,
2026-06-14 09:54:29 +08:00
generateSpriteActivity ,
2026-07-19 21:19:43 +08:00
generatePdfProxyActivity ,
2026-06-18 11:54:30 +08:00
transcodeVideoChunkActivity ,
deleteS3ObjectActivity ,
2026-07-28 20:19:10 +08:00
createAutofillTaskIfEnabledActivity ,
2026-10-13 00:03:21 +08:00
createEmbeddingTaskIfEnabledActivity ,
2026-06-05 21:25:08 +08:00
} from './transcode'
2026-05-19 16:05:09 +08:00
2026-06-01 23:16:22 +08:00
vi . mock ( '@shumai/core/src/s3/s3' , () => ({
2026-05-19 16:05:09 +08:00
s3Service : {
getObject : vi.fn (),
putObject : vi.fn (),
headObject : vi.fn (),
presign : vi.fn (),
2026-06-07 17:27:47 +08:00
downloadToFile : vi.fn (),
2026-06-18 11:54:30 +08:00
deleteObject : vi.fn (),
2026-09-08 10:17:15 +08:00
resolveInput : vi.fn (). mockImplementation ( async ( _bucket , key ) => `https://mock-url/ ${ key } ` ),
2026-05-19 16:05:09 +08:00
},
}))
2026-08-09 14:44:13 +08:00
vi . mock ( '@shumai/core/src/transcode/transcode' , async ( importOriginal ) => {
const actual = await importOriginal < typeof import ( '@shumai/core/src/transcode/transcode' ) >()
return {
... actual ,
transcodeService : {
getVideoInfo : vi.fn (),
getAudioInfo : vi.fn (),
getImageInfo : vi.fn (),
getPdfInfo : vi.fn (). mockResolvedValue ({
originalWidth : 800 ,
originalHeight : 1000 ,
duration : 0 ,
bitRate : 0 ,
frameRate : 0 ,
totalFrames : 10 ,
hasAudio : false ,
mimeType : 'application/pdf' ,
}),
transcodeVideo : vi.fn (),
transcodeAudio : vi.fn (),
transcodeImage : vi.fn (),
generateSprite : vi.fn (),
2026-09-25 16:37:16 +08:00
generatePoster : vi.fn (),
2026-08-09 14:44:13 +08:00
generatePdfSprite : vi.fn (). mockResolvedValue ({
pageCount : 10 ,
originalWidth : 800 ,
originalHeight : 1000 ,
}),
generatePdfFromText : vi.fn (),
generatePdfFromCsv : vi.fn (),
createTempDir : vi.fn (). mockReturnValue ( '/tmp' ),
removeDir : vi.fn (),
takeScreenshots : vi.fn (),
overlayAnnotations : vi.fn (),
renderPdfPages : vi.fn (),
2026-09-24 14:32:47 +08:00
getAvailableFilters : vi.fn (). mockResolvedValue ( new Set ([ 'zscale' , 'tonemap' ])),
2026-08-09 14:44:13 +08:00
},
}
})
2026-05-19 16:05:09 +08:00
2026-06-07 17:27:47 +08:00
vi . mock ( '@shumai/core/src/metadata/metadata' , () => ({
metadataService : {
updateAssetMetadata : vi.fn (),
},
}))
2026-05-19 16:05:09 +08:00
vi . mock ( 'fs' , async ( importOriginal ) => {
const actual = await importOriginal < typeof import ( 'fs' ) >()
return {
... actual ,
readFileSync : vi.fn (). mockReturnValue ( Buffer . from ( 'fake data' )),
2026-07-29 21:40:25 +08:00
statSync : vi.fn (). mockReturnValue ({ size : 9 }),
2026-06-07 17:27:47 +08:00
existsSync : vi.fn (). mockReturnValue ( true ),
mkdirSync : vi.fn (),
unlinkSync : vi.fn (),
2026-05-19 16:05:09 +08:00
}
})
describe ( 'Transcode Activities' , () => {
setupTestDbHooks ()
2026-08-09 14:44:13 +08:00
beforeEach ( async () => {
2026-05-19 16:05:09 +08:00
vi . clearAllMocks ()
2026-08-09 14:44:13 +08:00
const fs = await import ( 'fs' )
vi . mocked ( fs . readFileSync ). mockImplementation (() => Buffer . from ( 'fake data' ) as never )
})
it ( 'should convert CSV via Gotenberg in landscape mode when maxCols > 5' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'wide.csv' , type : 'file' , status : 'uploaded' },
})
const fs = await import ( 'fs' )
vi . mocked ( fs . readFileSync ). mockImplementation (( _path : unknown , options? : unknown ) => {
if ( options ) {
return 'c1,c2,c3,c4,c5,c6,c7\n1,2,3,4,5,6,7' as never
}
return Buffer . from ( 'fake data' ) as never
})
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( true )
const convertSpy = vi
. spyOn ( gotenbergService , 'convertDocumentToPdf' )
. mockResolvedValue ( Buffer . from ( 'fake pdf landscape csv' ))
const res = await generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/wide.csv' ,
filePath : '/tmp/wide.csv' ,
mediaType : 'text/csv' ,
filename : 'wide.csv' ,
})
2026-09-09 11:03:48 +08:00
expect ( res . pdfProxyKey ). toBe ( 'files/asset1/proxy.pdf' )
2026-08-09 14:44:13 +08:00
expect ( convertSpy ). toHaveBeenCalledWith ( '/tmp/wide.csv' , 'wide.csv' , { landscape : true })
vi . mocked ( fs . readFileSync ). mockImplementation (() => Buffer . from ( 'fake data' ) as never )
})
it ( 'should convert CSV via Gotenberg in portrait mode when maxCols <= 5' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'narrow.csv' , type : 'file' , status : 'uploaded' },
})
const fs = await import ( 'fs' )
vi . mocked ( fs . readFileSync ). mockImplementation (( _path : unknown , options? : unknown ) => {
if ( options ) {
return 'c1,c2,c3\n1,2,3' as never
}
return Buffer . from ( 'fake data' ) as never
})
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( true )
const convertSpy = vi
. spyOn ( gotenbergService , 'convertDocumentToPdf' )
. mockResolvedValue ( Buffer . from ( 'fake pdf portrait csv' ))
const res = await generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/narrow.csv' ,
filePath : '/tmp/narrow.csv' ,
mediaType : 'text/csv' ,
filename : 'narrow.csv' ,
})
2026-09-09 11:03:48 +08:00
expect ( res . pdfProxyKey ). toBe ( 'files/asset1/proxy.pdf' )
2026-08-09 14:44:13 +08:00
expect ( convertSpy ). toHaveBeenCalledWith ( '/tmp/narrow.csv' , 'narrow.csv' , { landscape : false })
vi . mocked ( fs . readFileSync ). mockImplementation (() => Buffer . from ( 'fake data' ) as never )
2026-05-19 16:05:09 +08:00
})
2026-06-07 17:27:47 +08:00
it ( 'should call getVideoInfo and set file_type to video' , async () => {
2026-05-19 16:05:09 +08:00
const asset = await prisma . asset . create ({
data : { name : 'v.mp4' , type : 'file' , status : 'uploaded' },
})
vi . mocked ( transcodeService . getVideoInfo ). mockResolvedValue ({
originalWidth : 1920 ,
originalHeight : 1080 ,
duration : 10 ,
bitRate : 1000 ,
2026-08-26 16:28:14 +08:00
videoBitRate : 850000 ,
2026-05-19 16:05:09 +08:00
frameRate : 30 ,
2026-06-28 15:11:32 +08:00
totalFrames : 300 ,
2026-05-19 16:05:09 +08:00
hasAudio : true ,
2026-05-26 15:41:12 +08:00
videoCodec : 'Advanced Video Coding' ,
audioCodec : 'MPEG-4 Audio' ,
2026-05-26 15:09:06 +08:00
audioChannels : 2 ,
audioSampleRate : 48000 ,
audioBitDepth : 16 ,
2026-09-24 14:32:47 +08:00
rotation : - 90 ,
2026-05-19 16:05:09 +08:00
mimeType : 'video/mp4' ,
})
const result = await getMediaInfoActivity ({
assetId : asset.id ,
filePath : '/tmp/v.mp4' ,
2026-07-20 10:22:36 +08:00
proxyType : 'video' ,
2026-05-19 16:05:09 +08:00
mediaType : 'video/mp4' ,
})
expect ( transcodeService . getVideoInfo ). toHaveBeenCalledWith ( '/tmp/v.mp4' )
expect ( result . duration ). toBe ( 10 )
2026-06-07 19:25:47 +08:00
expect ( result . metadata ? . originalWidth ). toBe ( 1920 )
2026-09-24 14:32:47 +08:00
expect ( result . metadata ? . rotation ). toBe ( - 90 )
2026-08-26 16:28:14 +08:00
expect ( result . metadata ? . videoBitRate ). toBe ( 850000 )
2026-06-07 19:25:47 +08:00
expect ( result . metadata ? . videoCodec ). toBe ( 'Advanced Video Coding' )
expect ( result . metadata ? . audioCodec ). toBe ( 'MPEG-4 Audio' )
expect ( result . metadata ? . audioChannels ). toBe ( 2 )
expect ( result . metadata ? . audioSampleRate ). toBe ( 48000 )
expect ( result . metadata ? . audioBitDepth ). toBe ( 16 )
2026-06-07 17:27:47 +08:00
expect ( metadataService . updateAssetMetadata ). toHaveBeenCalledWith (
asset . id ,
2026-09-24 14:32:47 +08:00
expect . arrayContaining ([
{ key : 'file_type' , value : 'video' },
{ key : 'rotation' , value : - 90 },
]),
2026-06-07 17:27:47 +08:00
true ,
)
2026-05-19 16:05:09 +08:00
})
2026-10-19 15:35:08 +08:00
it ( 'should resolve presigned URL when assetKey is provided without filePath for video' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'remote-video.mp4' , type : 'file' , status : 'uploaded' },
})
vi . spyOn ( s3Service , 'resolveInput' ). mockResolvedValueOnce (
'http://s3.local/shumai/remote-video.mp4?presigned=true' ,
)
vi . mocked ( transcodeService . getVideoInfo ). mockResolvedValueOnce ({
originalWidth : 1920 ,
originalHeight : 1080 ,
duration : 15 ,
bitRate : 1000000 ,
videoBitRate : 800000 ,
frameRate : 30 ,
totalFrames : 450 ,
hasAudio : false ,
mimeType : 'video/mp4' ,
})
const result = await getMediaInfoActivity ({
assetId : asset.id ,
assetKey : 'remote-video.mp4' ,
proxyType : 'video' ,
mediaType : 'video/mp4' ,
})
expect ( s3Service . resolveInput ). toHaveBeenCalledWith ( expect . any ( String ), 'remote-video.mp4' )
expect ( transcodeService . getVideoInfo ). toHaveBeenCalledWith (
'http://s3.local/shumai/remote-video.mp4?presigned=true' ,
)
expect ( result . duration ). toBe ( 15 )
})
2026-10-02 13:51:17 +08:00
it ( 'should downgrade proxyType to audio when getVideoInfo throws No video stream found but audio exists' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'audio-with-art.mp4' , type : 'file' , status : 'uploaded' },
})
vi . mocked ( transcodeService . getVideoInfo ). mockRejectedValueOnce (
new Error ( 'No video stream found' ),
)
vi . mocked ( transcodeService . getAudioInfo ). mockResolvedValueOnce ({
originalWidth : 0 ,
originalHeight : 0 ,
duration : 42 ,
bitRate : 192000 ,
frameRate : 0 ,
totalFrames : 0 ,
hasAudio : true ,
audioCodec : 'aac' ,
audioChannels : 2 ,
audioSampleRate : 44100 ,
audioBitDepth : 16 ,
audioStreamIndex : 0 ,
mimeType : 'audio/mp4' ,
})
const result = await getMediaInfoActivity ({
assetId : asset.id ,
filePath : '/tmp/audio-with-art.mp4' ,
proxyType : 'video' ,
mediaType : 'video/mp4' ,
})
expect ( transcodeService . getVideoInfo ). toHaveBeenCalledWith ( '/tmp/audio-with-art.mp4' )
expect ( transcodeService . getAudioInfo ). toHaveBeenCalledWith ( '/tmp/audio-with-art.mp4' )
expect ( result . proxyType ). toBe ( 'audio' )
expect ( result . duration ). toBe ( 42 )
expect ( result . metadata ? . hasAudio ). toBe ( true )
expect ( result . metadata ? . audioStreamIndex ). toBe ( 0 )
expect ( result . metadata ? . videoStreamIndex ). toBeUndefined ()
expect ( metadataService . updateAssetMetadata ). toHaveBeenCalledWith (
asset . id ,
expect . arrayContaining ([
{ key : 'file_type' , value : 'audio' },
{ key : 'proxy_type' , value : 'audio' },
{ key : 'duration' , value : 42 },
]),
true ,
)
})
it ( 'should populate videoStreamIndex and audioStreamIndex in mediaInfo.metadata' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'dual-stream.mp4' , type : 'file' , status : 'uploaded' },
})
vi . mocked ( transcodeService . getVideoInfo ). mockResolvedValueOnce ({
originalWidth : 1920 ,
originalHeight : 1080 ,
duration : 15 ,
bitRate : 2000000 ,
frameRate : 30 ,
totalFrames : 450 ,
hasAudio : true ,
videoCodec : 'h264' ,
audioCodec : 'aac' ,
videoStreamIndex : 1 ,
audioStreamIndex : 2 ,
mimeType : 'video/mp4' ,
})
const result = await getMediaInfoActivity ({
assetId : asset.id ,
filePath : '/tmp/dual-stream.mp4' ,
proxyType : 'video' ,
mediaType : 'video/mp4' ,
})
expect ( result . metadata ? . videoStreamIndex ). toBe ( 1 )
expect ( result . metadata ? . audioStreamIndex ). toBe ( 2 )
})
2026-06-07 17:27:47 +08:00
it ( 'should call getImageInfo and set file_type to image' , async () => {
2026-05-19 16:05:09 +08:00
const asset = await prisma . asset . create ({
data : { name : 'i.png' , type : 'file' , status : 'uploaded' },
})
vi . mocked ( transcodeService . getImageInfo ). mockResolvedValue ({
originalWidth : 800 ,
originalHeight : 600 ,
duration : 0 ,
bitRate : 0 ,
frameRate : 0 ,
2026-06-28 15:11:32 +08:00
totalFrames : 0 ,
2026-05-19 16:05:09 +08:00
hasAudio : false ,
mimeType : 'image/png' ,
})
2026-06-07 19:25:47 +08:00
const result = await getMediaInfoActivity ({
2026-05-19 16:05:09 +08:00
assetId : asset.id ,
filePath : '/tmp/i.png' ,
2026-07-20 10:22:36 +08:00
proxyType : 'image' ,
2026-05-19 16:05:09 +08:00
mediaType : 'image/png' ,
})
expect ( transcodeService . getImageInfo ). toHaveBeenCalledWith ( '/tmp/i.png' )
2026-06-07 19:25:47 +08:00
expect ( result . metadata ? . originalWidth ). toBe ( 800 )
expect ( result . metadata ? . duration ). toBe ( 0 )
2026-06-07 17:27:47 +08:00
expect ( metadataService . updateAssetMetadata ). toHaveBeenCalledWith (
asset . id ,
expect . arrayContaining ([{ key : 'file_type' , value : 'image' }]),
true ,
)
})
2026-07-05 15:11:19 +08:00
it ( 'should set file_type to audio for audio files and extract audio metadata' , async () => {
2026-06-07 17:27:47 +08:00
const asset = await prisma . asset . create ({
data : { name : 'a.mp3' , type : 'file' , status : 'uploaded' },
})
2026-07-05 15:11:19 +08:00
vi . mocked ( transcodeService . getAudioInfo ). mockResolvedValue ({
originalWidth : 0 ,
originalHeight : 0 ,
duration : 45.5 ,
bitRate : 128000 ,
frameRate : 0 ,
totalFrames : 0 ,
hasAudio : true ,
audioCodec : 'mp3' ,
audioChannels : 2 ,
audioSampleRate : 44100 ,
audioBitDepth : 16 ,
mimeType : 'audio/mpeg' ,
})
2026-06-07 17:27:47 +08:00
2026-07-05 15:11:19 +08:00
const result = await getMediaInfoActivity ({
2026-06-07 17:27:47 +08:00
assetId : asset.id ,
filePath : '/tmp/a.mp3' ,
2026-07-20 10:22:36 +08:00
proxyType : 'audio' ,
2026-06-07 17:27:47 +08:00
mediaType : 'audio/mpeg' ,
})
2026-07-05 15:11:19 +08:00
expect ( transcodeService . getAudioInfo ). toHaveBeenCalledWith ( '/tmp/a.mp3' )
expect ( result . duration ). toBe ( 45.5 )
expect ( result . metadata ? . duration ). toBe ( 45.5 )
expect ( result . metadata ? . audioCodec ). toBe ( 'mp3' )
expect ( result . metadata ? . audioChannels ). toBe ( 2 )
expect ( result . metadata ? . audioSampleRate ). toBe ( 44100 )
expect ( result . metadata ? . audioBitDepth ). toBe ( 16 )
2026-06-07 17:27:47 +08:00
expect ( metadataService . updateAssetMetadata ). toHaveBeenCalledWith (
asset . id ,
2026-07-05 15:11:19 +08:00
expect . arrayContaining ([
{ key : 'file_type' , value : 'audio' },
{ key : 'duration' , value : 45.5 },
{ key : 'audio_codec' , value : 'mp3' },
{ key : 'audio_channels' , value : 2 },
{ key : 'audio_sample_rate' , value : 44100 },
{ key : 'audio_bit_depth' , value : 16 },
]),
2026-06-07 17:27:47 +08:00
true ,
)
})
it ( 'should set file_type to document for pdf/text files' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'd.pdf' , type : 'file' , status : 'uploaded' },
})
await getMediaInfoActivity ({
assetId : asset.id ,
filePath : '/tmp/d.pdf' ,
2026-07-20 10:22:36 +08:00
proxyType : 'pdf' ,
2026-06-07 17:27:47 +08:00
mediaType : 'application/pdf' ,
})
expect ( metadataService . updateAssetMetadata ). toHaveBeenCalledWith (
asset . id ,
2026-07-19 21:19:43 +08:00
expect . arrayContaining ([
{ key : 'file_type' , value : 'document' },
{ key : 'proxy_type' , value : 'pdf' },
]),
2026-06-07 17:27:47 +08:00
true ,
)
})
2026-07-19 21:19:43 +08:00
it ( 'should generate PDF proxy for text/csv files in generatePdfProxyActivity' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'test.txt' , type : 'file' , status : 'uploaded' },
})
2026-08-09 14:44:13 +08:00
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( false )
2026-07-19 21:19:43 +08:00
const generatePdfFromTextSpy = vi
. spyOn ( transcodeService , 'generatePdfFromText' )
. mockImplementation ( async ( _inPath , outPath ) => {
const fs = await import ( 'fs' )
fs . writeFileSync ( outPath , 'fake pdf content' )
})
const res = await generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/test.txt' ,
filePath : '/tmp/test.txt' ,
mediaType : 'text/plain' ,
filename : 'test.txt' ,
})
2026-09-09 11:03:48 +08:00
expect ( res . pdfProxyKey ). toBe ( 'files/asset1/proxy.pdf' )
expect ( s3Service . putObject ). toHaveBeenCalledWith (
'shumai' ,
'files/asset1/proxy.pdf' ,
expect . anything (),
expect . any ( Number ),
'application/pdf' ,
)
2026-07-19 21:19:43 +08:00
expect ( generatePdfFromTextSpy ). toHaveBeenCalled ()
generatePdfFromTextSpy . mockRestore ()
})
2026-07-20 18:35:16 +08:00
it ( 'should generate PDF proxy for markdown files in generatePdfProxyActivity' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'README.md' , type : 'file' , status : 'uploaded' },
})
2026-08-09 14:44:13 +08:00
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( false )
2026-07-20 18:35:16 +08:00
const generatePdfFromTextSpy = vi
. spyOn ( transcodeService , 'generatePdfFromText' )
. mockImplementation ( async ( _inPath , outPath ) => {
const fs = await import ( 'fs' )
fs . writeFileSync ( outPath , 'fake pdf content from md' )
})
const res = await generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/README.md' ,
filePath : '/tmp/README.md' ,
mediaType : 'text/markdown' ,
filename : 'README.md' ,
})
2026-09-09 11:03:48 +08:00
expect ( res . pdfProxyKey ). toBe ( 'files/asset1/proxy.pdf' )
2026-07-20 18:35:16 +08:00
expect ( generatePdfFromTextSpy ). toHaveBeenCalledWith (
'/tmp/README.md' ,
expect . stringContaining ( 'proxy.pdf' ),
)
generatePdfFromTextSpy . mockRestore ()
})
2026-08-09 14:44:13 +08:00
it ( 'should convert markdown document via Gotenberg Chromium in generatePdfProxyActivity when available' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'README.md' , type : 'file' , status : 'uploaded' },
})
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( true )
const convertMdSpy = vi
. spyOn ( gotenbergService , 'convertMarkdownToPdf' )
. mockResolvedValue ( Buffer . from ( 'fake pdf from gotenberg markdown' ))
const res = await generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/README.md' ,
filePath : '/tmp/README.md' ,
mediaType : 'text/markdown' ,
filename : 'README.md' ,
})
2026-09-09 11:03:48 +08:00
expect ( res . pdfProxyKey ). toBe ( 'files/asset1/proxy.pdf' )
2026-08-09 14:44:13 +08:00
expect ( convertMdSpy ). toHaveBeenCalledWith ( '/tmp/README.md' , 'README.md' )
})
it ( 'should convert office document via Gotenberg in generatePdfProxyActivity when available' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'document.docx' , type : 'file' , status : 'uploaded' },
})
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( true )
const convertSpy = vi
. spyOn ( gotenbergService , 'convertDocumentToPdf' )
. mockResolvedValue ( Buffer . from ( 'fake pdf from gotenberg office' ))
const res = await generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/document.docx' ,
filePath : '/tmp/document.docx' ,
mediaType : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ,
filename : 'document.docx' ,
})
2026-09-09 11:03:48 +08:00
expect ( res . pdfProxyKey ). toBe ( 'files/asset1/proxy.pdf' )
2026-08-09 14:44:13 +08:00
expect ( convertSpy ). toHaveBeenCalledWith ( '/tmp/document.docx' , 'document.docx' )
})
it ( 'should convert html document via Gotenberg Chromium in generatePdfProxyActivity when available' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'index.html' , type : 'file' , status : 'uploaded' },
})
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( true )
const convertHtmlSpy = vi
. spyOn ( gotenbergService , 'convertHtmlToPdf' )
. mockResolvedValue ( Buffer . from ( 'fake pdf from gotenberg html' ))
const res = await generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/index.html' ,
filePath : '/tmp/index.html' ,
mediaType : 'text/html' ,
filename : 'index.html' ,
})
2026-09-09 11:03:48 +08:00
expect ( res . pdfProxyKey ). toBe ( 'files/asset1/proxy.pdf' )
2026-08-09 14:44:13 +08:00
expect ( convertHtmlSpy ). toHaveBeenCalledWith ( '/tmp/index.html' , 'index.html' )
})
it ( 'should throw ApplicationFailure when Office document conversion is attempted but Gotenberg is unavailable' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'sheet.xlsx' , type : 'file' , status : 'uploaded' },
})
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( false )
await expect (
generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/sheet.xlsx' ,
filePath : '/tmp/sheet.xlsx' ,
mediaType : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ,
filename : 'sheet.xlsx' ,
}),
). rejects . toThrow ( 'Gotenberg service is required for Office document conversion' )
})
it ( 'should throw ApplicationFailure when HTML document conversion is attempted but Gotenberg is unavailable' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'index.html' , type : 'file' , status : 'uploaded' },
})
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( false )
await expect (
generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/index.html' ,
filePath : '/tmp/index.html' ,
mediaType : 'text/html' ,
filename : 'index.html' ,
}),
). rejects . toThrow ( 'Gotenberg service is required for HTML document conversion' )
})
it ( 'should fallback to transcodeService.generatePdfFromCsv for CSV when Gotenberg is unavailable' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'data.csv' , type : 'file' , status : 'uploaded' },
})
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( false )
const generatePdfFromCsvSpy = vi
. spyOn ( transcodeService , 'generatePdfFromCsv' )
. mockImplementation ( async ( _inPath , outPath ) => {
const fs = await import ( 'fs' )
fs . writeFileSync ( outPath , 'fake pdf from csv fallback' )
})
const res = await generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/data.csv' ,
filePath : '/tmp/data.csv' ,
mediaType : 'text/csv' ,
filename : 'data.csv' ,
})
2026-09-09 11:03:48 +08:00
expect ( res . pdfProxyKey ). toBe ( 'files/asset1/proxy.pdf' )
2026-08-09 14:44:13 +08:00
expect ( generatePdfFromCsvSpy ). toHaveBeenCalledWith (
'/tmp/data.csv' ,
expect . stringContaining ( 'proxy.pdf' ),
)
generatePdfFromCsvSpy . mockRestore ()
})
it ( 'should convert TXT document via Gotenberg when available' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'notes.txt' , type : 'file' , status : 'uploaded' },
})
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( true )
const convertSpy = vi
. spyOn ( gotenbergService , 'convertDocumentToPdf' )
. mockResolvedValue ( Buffer . from ( 'fake pdf from txt gotenberg' ))
const res = await generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/notes.txt' ,
filePath : '/tmp/notes.txt' ,
mediaType : 'text/plain' ,
filename : 'notes.txt' ,
})
2026-09-09 11:03:48 +08:00
expect ( res . pdfProxyKey ). toBe ( 'files/asset1/proxy.pdf' )
2026-08-09 14:44:13 +08:00
expect ( convertSpy ). toHaveBeenCalledWith ( '/tmp/notes.txt' , 'notes.txt' )
})
it ( 'should fallback to transcodeService.generatePdfFromText for TXT when Gotenberg is unavailable' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'notes.txt' , type : 'file' , status : 'uploaded' },
})
vi . spyOn ( gotenbergService , 'isAvailable' ). mockResolvedValue ( false )
const generatePdfFromTextSpy = vi
. spyOn ( transcodeService , 'generatePdfFromText' )
. mockImplementation ( async ( _inPath , outPath ) => {
const fs = await import ( 'fs' )
fs . writeFileSync ( outPath , 'fake pdf from txt fallback' )
})
const res = await generatePdfProxyActivity ({
assetId : asset.id ,
assetKey : 'files/asset1/notes.txt' ,
filePath : '/tmp/notes.txt' ,
mediaType : 'text/plain' ,
filename : 'notes.txt' ,
})
2026-09-09 11:03:48 +08:00
expect ( res . pdfProxyKey ). toBe ( 'files/asset1/proxy.pdf' )
2026-08-09 14:44:13 +08:00
expect ( generatePdfFromTextSpy ). toHaveBeenCalledWith (
'/tmp/notes.txt' ,
expect . stringContaining ( 'proxy.pdf' ),
)
generatePdfFromTextSpy . mockRestore ()
})
2026-06-07 17:27:47 +08:00
it ( 'should set file_type to file for unknown types' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'u.xyz' , type : 'file' , status : 'uploaded' },
})
await getMediaInfoActivity ({
assetId : asset.id ,
filePath : '/tmp/u.xyz' ,
mediaType : 'application/octet-stream' ,
})
expect ( metadataService . updateAssetMetadata ). toHaveBeenCalledWith (
asset . id ,
expect . arrayContaining ([{ key : 'file_type' , value : 'file' }]),
true ,
)
2026-05-19 16:05:09 +08:00
})
it ( 'should update asset media field' , async () => {
const asset = await prisma . asset . create ({
data : {
name : 'v.mp4' ,
2026-05-25 00:52:45 +08:00
storageKey : { create : { key : 'v.mp4' } },
2026-05-19 16:05:09 +08:00
status : 'uploaded' ,
type : 'file' ,
2026-09-17 11:51:03 +08:00
hasJpegPreview : true ,
2026-05-19 16:05:09 +08:00
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mediaInfo : any = { duration : 123 }
await updateAssetMediaActivity ({ assetId : asset.id , mediaInfo })
const updated = await prisma . asset . findUnique ({ where : { id : asset.id } })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect (( updated ? . media as any ). duration ). toBe ( 123 )
2026-09-17 11:51:03 +08:00
expect ( updated ? . hasJpegPreview ). toBe ( false )
2026-05-19 16:05:09 +08:00
expect ( s3Service . putObject ). toHaveBeenCalled ()
})
2026-09-19 10:40:49 +08:00
it ( 'should throw non-retryable ApplicationFailure and not upload when asset is pending_purge in updateAssetMediaActivity' , async () => {
const asset = await prisma . asset . create ({
data : {
name : 'purging.mp4' ,
storageKey : { create : { key : 'purging.mp4' } },
status : 'pending_purge' ,
type : 'file' ,
},
})
const putObjectSpy = vi . mocked ( s3Service . putObject )
putObjectSpy . mockClear ()
await expect (
updateAssetMediaActivity ({
assetId : asset.id ,
mediaInfo : { duration : 100 } as unknown as PrismaJson . MediaInfo ,
}),
). rejects . toThrow ( 'Asset not found, has no key, or is being purged' )
expect ( putObjectSpy ). not . toHaveBeenCalled ()
})
it ( 'should tolerate missing or deleted asset without throwing P2025 in updateAssetMediaActivity' , async () => {
const asset = await prisma . asset . create ({
data : {
name : 'deleted-during-update.mp4' ,
storageKey : { create : { key : 'deleted-during-update.mp4' } },
status : 'uploaded' ,
type : 'file' ,
},
})
const putObjectSpy = vi . mocked ( s3Service . putObject )
putObjectSpy . mockClear ()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
putObjectSpy . mockImplementationOnce ( async () : Promise < any > => {
await prisma . asset . delete ({ where : { id : asset.id } })
return {}
})
await expect (
updateAssetMediaActivity ({
assetId : asset.id ,
mediaInfo : { duration : 100 } as unknown as PrismaJson . MediaInfo ,
}),
). resolves . toBeUndefined ()
})
it ( 'should throw non-retryable ApplicationFailure and not upload when asset is pending_purge in transcodeVideoActivity' , async () => {
await prisma . asset . create ({
data : {
name : 'purging-video.mp4' ,
storageKey : { create : { key : 'purging-video.mp4' } },
status : 'pending_purge' ,
type : 'file' ,
},
})
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
const putObjectSpy = vi . mocked ( s3Service . putObject )
putObjectSpy . mockClear ()
await expect (
transcodeVideoActivity ({
assetKey : 'purging-video.mp4' ,
filePath : '/tmp/purging-video.mp4' ,
videoSpec : { resolution : '720p' , width : 1280 , height : 720 },
duration : 10 ,
originalFps : 30 ,
}),
). rejects . toThrow ( 'Asset or storage key has been purged or is pending purge' )
expect ( putObjectSpy ). not . toHaveBeenCalled ()
})
2026-05-19 16:05:09 +08:00
it ( 'should call transcodeService.transcodeVideo' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
await transcodeVideoActivity ({
assetKey : 'v.mp4' ,
filePath : '/tmp/v.mp4' ,
videoSpec : { resolution : '720p' , width : 1280 , height : 720 },
duration : 10 ,
originalFps : 30 ,
2026-08-26 16:28:14 +08:00
hardwareAcceleration : 'auto' ,
sourceVideoBitrate : 600_000 ,
2026-09-18 13:30:33 +08:00
threads : 8 ,
2026-05-19 16:05:09 +08:00
})
2026-08-26 16:28:14 +08:00
expect ( transcodeService . transcodeVideo ). toHaveBeenCalledWith (
expect . objectContaining ({
inputFile : '/tmp/v.mp4' ,
hardwareAcceleration : 'auto' ,
sourceVideoBitrate : 600_000 ,
2026-09-18 13:30:33 +08:00
threads : 8 ,
2026-08-26 16:28:14 +08:00
}),
)
2026-05-19 16:05:09 +08:00
})
2026-06-05 21:25:08 +08:00
2026-10-02 13:51:17 +08:00
it ( 'transcodeVideoActivity forwards streamIndex and audioStreamIndex to transcodeService' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
await transcodeVideoActivity ({
assetKey : 'v.mp4' ,
filePath : '/tmp/v.mp4' ,
videoSpec : { resolution : '720p' , width : 1280 , height : 720 },
duration : 10 ,
originalFps : 30 ,
streamIndex : 2 ,
audioStreamIndex : 1 ,
})
expect ( transcodeService . transcodeVideo ). toHaveBeenCalledWith (
expect . objectContaining ({
inputFile : '/tmp/v.mp4' ,
streamIndex : 2 ,
audioStreamIndex : 1 ,
}),
)
})
2026-09-24 14:32:47 +08:00
it ( 'transcodeVideoActivity appends -hdr.mp4 suffix and forwards HDR metadata' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
const result = await transcodeVideoActivity ({
assetKey : 'files/asset-1/video.mp4' ,
filePath : '/tmp/video.mp4' ,
videoSpec : { resolution : '1080p' , width : 1920 , height : 1080 , hdr : true },
duration : 10 ,
originalFps : 30 ,
sourceIsHdr : true ,
sourceHdrType : 'pq' ,
sourceColorTransfer : 'smpte2084' ,
sourceColorPrimaries : 'bt2020' ,
sourceColorSpace : 'bt2020nc' ,
})
expect ( result . key ). toBe ( 'files/asset-1/video-1080p-hdr.mp4' )
expect ( result . hdr ). toBe ( true )
expect ( transcodeService . transcodeVideo ). toHaveBeenCalledWith (
expect . objectContaining ({
inputFile : '/tmp/video.mp4' ,
hdr : true ,
sourceIsHdr : true ,
sourceHdrType : 'pq' ,
sourceColorTransfer : 'smpte2084' ,
sourceColorPrimaries : 'bt2020' ,
sourceColorSpace : 'bt2020nc' ,
}),
)
})
2026-06-05 21:25:08 +08:00
it ( 'should call transcodeService.takeScreenshots' , async () => {
vi . mocked ( transcodeService . takeScreenshots ). mockResolvedValue ([
{ key : 'screenshots/shot1.webp' , timestamp : 1.0 },
])
const result = await takeScreenshotsActivity ({
assetKey : 'v.mp4' ,
assetId : 'asset-1' ,
start : 0 ,
end : 10 ,
count : 1 ,
commentTimestamp : 1.0 ,
annotations : [],
})
expect ( transcodeService . takeScreenshots ). toHaveBeenCalledWith ({
assetKey : 'v.mp4' ,
assetId : 'asset-1' ,
start : 0 ,
end : 10 ,
count : 1 ,
commentTimestamp : 1.0 ,
annotations : [],
})
expect ( result ). toEqual ([{ key : 'screenshots/shot1.webp' , timestamp : 1.0 }])
})
it ( 'should call transcodeService.overlayAnnotations' , async () => {
vi . mocked ( transcodeService . overlayAnnotations ). mockResolvedValue ( 'annotations/ann.webp' )
const result = await overlayAnnotationsActivity ({
assetKey : 'i.png' ,
assetId : 'asset-2' ,
annotations : [],
})
expect ( transcodeService . overlayAnnotations ). toHaveBeenCalledWith ({
assetKey : 'i.png' ,
assetId : 'asset-2' ,
annotations : [],
})
expect ( result ). toBe ( 'annotations/ann.webp' )
})
2026-06-14 09:54:29 +08:00
2026-07-19 09:45:14 +08:00
it ( 'should call transcodeService.renderPdfPages' , async () => {
vi . mocked ( transcodeService . renderPdfPages ). mockResolvedValue ([
{ key : 'pdf_pages/doc-page-1.webp' , page : 1 },
])
const result = await renderPdfPagesActivity ({
assetKey : 'doc.pdf' ,
assetId : 'asset-pdf' ,
start : 1 ,
end : 1 ,
commentTimestamp : 1 ,
annotations : [],
})
expect ( transcodeService . renderPdfPages ). toHaveBeenCalledWith ({
assetKey : 'doc.pdf' ,
assetId : 'asset-pdf' ,
start : 1 ,
end : 1 ,
commentTimestamp : 1 ,
annotations : [],
})
expect ( result ). toEqual ([{ key : 'pdf_pages/doc-page-1.webp' , page : 1 }])
})
2026-06-14 09:54:29 +08:00
describe ( 'Non-retryable Error Handling' , () => {
it ( 'should throw non-retryable ApplicationFailure when downloadMediaToTmpActivity fails with ENOENT' , async () => {
vi . mocked ( s3Service . downloadToFile ). mockRejectedValue ({
code : 'ENOENT' ,
message : 'ENOENT: no such file or directory' ,
})
await expect ( downloadMediaToTmpActivity ({ assetKey : 'missing.mp4' })). rejects . toThrowError (
/Failed to download media to tmp/ ,
)
})
it ( 'should throw non-retryable ApplicationFailure when getMediaInfoActivity fails with ENOENT' , async () => {
const asset = await prisma . asset . create ({
data : { name : 'missing.mp4' , type : 'file' , status : 'uploaded' },
})
vi . mocked ( transcodeService . getVideoInfo ). mockRejectedValue ({
code : 'ENOENT' ,
message : 'ENOENT: no such file or directory' ,
})
await expect (
getMediaInfoActivity ({
assetId : asset.id ,
filePath : '/tmp/missing.mp4' ,
mediaType : 'video/mp4' ,
}),
). rejects . toThrowError ( /Failed to get media info/ )
})
it ( 'should throw non-retryable ApplicationFailure when transcodeVideoActivity fails with ffmpeg error' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( transcodeService . transcodeVideo ). mockRejectedValue ( new Error ( 'FFmpeg failed' ))
await expect (
transcodeVideoActivity ({
assetKey : 'v.mp4' ,
filePath : '/tmp/v.mp4' ,
videoSpec : { resolution : '720p' , width : 1280 , height : 720 },
duration : 10 ,
originalFps : 30 ,
}),
). rejects . toThrowError ( /Video transcoding failed/ )
})
2026-09-19 10:40:49 +08:00
it ( 'should throw non-retryable ApplicationFailure when transcodeVideoActivity is cancelled' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
const abortError = new Error ( 'The operation was aborted' )
abortError . name = 'AbortError'
vi . mocked ( transcodeService . transcodeVideo ). mockRejectedValue ( abortError )
const promise = transcodeVideoActivity ({
assetKey : 'v.mp4' ,
filePath : '/tmp/v.mp4' ,
videoSpec : { resolution : '720p' , width : 1280 , height : 720 },
duration : 10 ,
originalFps : 30 ,
})
await expect ( promise ). rejects . toThrowError ( /Video transcoding cancelled/ )
await expect ( promise ). rejects . toMatchObject ({
nonRetryable : true ,
})
})
2026-06-14 09:54:29 +08:00
it ( 'should throw non-retryable ApplicationFailure when transcodeImageActivity fails with sharp error' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( transcodeService . transcodeImage ). mockRejectedValue ( new Error ( 'sharp failed' ))
await expect (
transcodeImageActivity ({
assetKey : 'i.png' ,
filePath : '/tmp/i.png' ,
imageSpec : { width : 800 , height : 600 , quality : 90 , format : 'webp' },
}),
). rejects . toThrowError ( /Image transcoding failed/ )
})
2026-07-23 16:19:25 +08:00
it ( 'should throw non-retryable ApplicationFailure when transcodeImageActivity fails with ImageMagick error' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( transcodeService . transcodeImage ). mockRejectedValue (
new Error ( 'imagemagick convert failed' ),
)
await expect (
transcodeImageActivity ({
assetKey : 'i.psd' ,
filePath : '/tmp/i.psd' ,
imageSpec : { width : 800 , height : 600 , quality : 90 , format : 'webp' },
}),
). rejects . toThrowError ( /Image transcoding failed/ )
})
2026-10-03 11:03:31 +08:00
it ( 'should throw non-retryable ApplicationFailure when transcodeImageActivity fails with dcraw error' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( transcodeService . transcodeImage ). mockRejectedValue (
new Error ( 'dcraw_emu failed to decode RAW file' ),
)
await expect (
transcodeImageActivity ({
assetKey : 'photo.cr2' ,
filePath : '/tmp/photo.cr2' ,
imageSpec : { width : 800 , height : 600 , quality : 90 , format : 'webp' },
}),
). rejects . toMatchObject ({
message : expect.stringContaining ( 'Image transcoding failed' ),
nonRetryable : true ,
})
})
2026-06-14 09:54:29 +08:00
it ( 'should throw non-retryable ApplicationFailure when generateSpriteActivity fails with error' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( transcodeService . generateSprite ). mockRejectedValue ( new Error ( 'FFmpeg failed' ))
await expect (
generateSpriteActivity ({
assetKey : 'v.mp4' ,
filePath : '/tmp/v.mp4' ,
mediaInfo : { duration : 10 } as unknown as PrismaJson . MediaInfo ,
spriteSpec : { key : 'sprite.webp' , frames : 100 , tileX : 10 , tileY : 10 },
posterSpec : { key : 'poster.webp' },
}),
). rejects . toThrowError ( /Sprite\/Poster generation failed/ )
})
2026-09-24 14:32:47 +08:00
it ( 'generateSpriteActivity forwards HDR options to transcodeService.generateSprite' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( transcodeService . generateSprite ). mockImplementation (
async ( _in , spriteOut , posterOut ) => {
fs . writeFileSync ( spriteOut , Buffer . from ( 'fake-sprite' ))
fs . writeFileSync ( posterOut , Buffer . from ( 'fake-poster' ))
},
)
await generateSpriteActivity ({
assetKey : 'files/asset-1/video.mp4' ,
filePath : '/tmp/video.mp4' ,
mediaInfo : {
duration : 10 ,
metadata : {
isHdr : true ,
hdrType : 'pq' ,
colorTransfer : 'smpte2084' ,
},
} as unknown as PrismaJson . MediaInfo ,
spriteSpec : { key : 'files/asset-1/sprite.webp' , frames : 100 , tileX : 10 , tileY : 10 },
posterSpec : { key : 'files/asset-1/poster.webp' },
})
expect ( transcodeService . generateSprite ). toHaveBeenCalledWith (
'/tmp/video.mp4' ,
expect . any ( String ),
expect . any ( String ),
10 ,
undefined ,
{
isHdr : true ,
hdrType : 'pq' ,
colorTransfer : 'smpte2084' ,
},
2026-10-02 13:51:17 +08:00
undefined ,
)
})
it ( 'generateSpriteActivity forwards videoStreamIndex to transcodeService.generateSprite' , async () => {
vi . mocked ( transcodeService . generateSprite ). mockImplementation (
async ( _in , spriteOut , posterOut ) => {
const fs = await import ( 'fs' )
fs . writeFileSync ( spriteOut , 'fake-sprite' )
fs . writeFileSync ( posterOut , 'fake-poster' )
},
)
await generateSpriteActivity ({
assetKey : 'files/asset-1/video.mp4' ,
filePath : '/tmp/video.mp4' ,
mediaInfo : {
duration : 10 ,
metadata : {
videoStreamIndex : 1 ,
},
} as unknown as PrismaJson . MediaInfo ,
spriteSpec : { key : 'files/asset-1/sprite.webp' , frames : 100 , tileX : 10 , tileY : 10 },
posterSpec : { key : 'files/asset-1/poster.webp' },
})
expect ( transcodeService . generateSprite ). toHaveBeenCalledWith (
'/tmp/video.mp4' ,
expect . any ( String ),
expect . any ( String ),
10 ,
undefined ,
{
isHdr : undefined ,
hdrType : undefined ,
colorTransfer : undefined ,
},
1 ,
2026-09-24 14:32:47 +08:00
)
})
2026-06-14 09:54:29 +08:00
it ( 'should throw non-retryable ApplicationFailure when takeScreenshotsActivity fails with error' , async () => {
vi . mocked ( transcodeService . takeScreenshots ). mockRejectedValue ( new Error ( 'FFmpeg failed' ))
await expect (
takeScreenshotsActivity ({
assetKey : 'v.mp4' ,
assetId : 'asset-1' ,
start : 0 ,
end : 10 ,
count : 1 ,
commentTimestamp : 1.0 ,
annotations : [],
}),
). rejects . toThrowError ( /Screenshot extraction failed/ )
})
it ( 'should throw non-retryable ApplicationFailure when overlayAnnotationsActivity fails with error' , async () => {
vi . mocked ( transcodeService . overlayAnnotations ). mockRejectedValue ( new Error ( 'sharp failed' ))
await expect (
overlayAnnotationsActivity ({
assetKey : 'i.png' ,
assetId : 'asset-2' ,
annotations : [],
}),
). rejects . toThrowError ( /Overlay annotations failed/ )
})
})
2026-06-18 11:54:30 +08:00
describe ( 'Video Chunk Activities' , () => {
it ( 'should transcode video chunk using ffmpeg and upload to S3' , async () => {
// Mock child_process.execFile to simulate ffmpeg succeeding
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;( child_process . execFile as any ). mockImplementation (
2026-06-18 11:57:38 +08:00
(
file : string ,
args : string [],
cb : ( err : Error | null , result : { stdout : string ; stderr : string }) => void ,
) => {
2026-06-18 11:54:30 +08:00
cb ( null , { stdout : '' , stderr : '' })
},
)
const res = await transcodeVideoChunkActivity ({
assetId : 'asset-abc' ,
filePath : '/tmp/full-video.mp4' ,
startTime : 10 ,
endTime : 25 ,
})
// Verify ffmpeg command args
expect ( child_process . execFile ). toHaveBeenCalledWith (
'ffmpeg' ,
expect . arrayContaining ([
'-y' ,
'-i' ,
'/tmp/full-video.mp4' ,
'-ss' ,
'10' ,
'-t' ,
'15' ,
2026-06-18 19:53:19 +08:00
'-vf' ,
'fps=1' ,
'-c:v' ,
'libx264' ,
'-preset' ,
'ultrafast' ,
'-crf' ,
'28' ,
'-an' ,
2026-06-18 11:54:30 +08:00
]),
expect . any ( Function ),
)
// Verify S3 upload
expect ( s3Service . putObject ). toHaveBeenCalledWith (
'shumai' ,
expect . stringMatching ( /^files\/asset-abc\/tmp-embedding-chunks\/chunk-10-25-.*\.mp4$/ ),
expect . any ( Buffer ),
expect . any ( Number ),
'video/mp4' ,
)
expect ( res . chunkKey ). toMatch ( /^files\/asset-abc\/tmp-embedding-chunks\/chunk-10-25-.*\.mp4$/ )
})
2026-09-08 10:17:15 +08:00
it ( 'should transcode video chunk using assetKey directly via resolveInput' , async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;( child_process . execFile as any ). mockImplementation (
(
file : string ,
args : string [],
cb : ( err : Error | null , result : { stdout : string ; stderr : string }) => void ,
) => {
cb ( null , { stdout : '' , stderr : '' })
},
)
vi . mocked ( s3Service . resolveInput ). mockResolvedValue ( 'https://mock-r2.com/video.mp4' )
const res = await transcodeVideoChunkActivity ({
assetId : 'asset-abc' ,
assetKey : 'video.mp4' ,
startTime : 10 ,
endTime : 25 ,
})
expect ( s3Service . resolveInput ). toHaveBeenCalledWith ( 'shumai' , 'video.mp4' )
expect ( child_process . execFile ). toHaveBeenCalledWith (
'ffmpeg' ,
expect . arrayContaining ([
'-ss' ,
'10' ,
'-i' ,
'https://mock-r2.com/video.mp4' ,
'-reconnect' ,
'1' ,
]),
expect . any ( Function ),
)
expect ( res . chunkKey ). toMatch ( /^files\/asset-abc\/tmp-embedding-chunks\/chunk-10-25-.*\.mp4$/ )
})
2026-10-15 15:49:24 +08:00
it ( 'should extract frames archive when format is frames' , async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;( child_process . execFile as any ). mockImplementation (
(
_file : string ,
args : string [],
cb : ( err : Error | null , result : { stdout : string ; stderr : string }) => void ,
) => {
if ( _file === 'ffmpeg' && args ) {
const outPattern = args [ args . length - 1 ]
if ( outPattern && outPattern . includes ( 'frame_%04d.jpg' )) {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fsActual = require ( 'fs' )
// eslint-disable-next-line @typescript-eslint/no-require-imports
const pathActual = require ( 'path' )
const dir = pathActual . dirname ( outPattern )
fsActual . writeFileSync (
pathActual . join ( dir , 'frame_0001.jpg' ),
Buffer . from ( 'mock-frame' ),
)
}
}
cb ( null , { stdout : '' , stderr : '' })
},
)
const res = await transcodeVideoChunkActivity ({
assetId : 'asset-abc' ,
filePath : '/tmp/full-video.mp4' ,
startTime : 10 ,
endTime : 25 ,
format : 'frames' ,
})
expect ( child_process . execFile ). toHaveBeenCalledWith (
'ffmpeg' ,
expect . arrayContaining ([ '-vf' , 'fps=1' , '-q:v' , '2' ]),
expect . any ( Function ),
)
expect ( child_process . execFile ). not . toHaveBeenCalledWith (
'tar' ,
expect . anything (),
expect . anything (),
)
expect ( s3Service . putObject ). toHaveBeenCalledWith (
'shumai' ,
expect . stringMatching ( /^files\/asset-abc\/tmp-embedding-chunks\/frames-10-25-.*\.tar$/ ),
expect . any ( Buffer ),
expect . any ( Number ),
'application/x-tar' ,
)
expect ( res . chunkKey ). toMatch ( /^files\/asset-abc\/tmp-embedding-chunks\/frames-10-25-.*\.tar$/ )
const putCall = vi . mocked ( s3Service . putObject ). mock . calls [ 0 ]
const uploadedBuffer = putCall [ 2 ] as Buffer
const uploadedArchive = new Bun . Archive ( uploadedBuffer )
const archiveFiles = await uploadedArchive . files ()
expect ( archiveFiles . has ( 'frame_0001.jpg' )). toBe ( true )
const uploadedFile = archiveFiles . get ( 'frame_0001.jpg' ) !
expect ( uploadedFile . size ). toBeGreaterThan ( 0 )
const uploadedFileBytes = await uploadedFile . bytes ()
expect ( uploadedFileBytes . byteLength ). toBeGreaterThan ( 0 )
})
it ( 'should sample uniform 16 frames when chunk duration > 16s' , async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- child_process.execFile mockImplementation returns void rather than ChildProcess in unit tests
;( child_process . execFile as any ). mockImplementation (
(
_cmd : unknown ,
_args : unknown ,
cb : ( err : null , res : { stdout : string ; stderr : string }) => void ,
) => {
cb ( null , {
stdout : '' ,
stderr : '' ,
})
},
)
await transcodeVideoChunkActivity ({
assetId : 'asset-abc' ,
filePath : '/tmp/full-video.mp4' ,
startTime : 0 ,
endTime : 60 ,
format : 'frames' ,
})
expect ( child_process . execFile ). toHaveBeenCalledWith (
'ffmpeg' ,
expect . arrayContaining ([ '-vf' , `fps= ${ 16 / 60 } ` , '-vframes' , '16' , '-q:v' , '2' ]),
expect . any ( Function ),
)
})
2026-09-08 10:17:15 +08:00
it ( 'should throw non-retryable ApplicationFailure when neither filePath nor assetKey is provided' , async () => {
expect . assertions ( 2 )
try {
await transcodeVideoChunkActivity ({
assetId : 'asset-abc' ,
startTime : 0 ,
endTime : 10 ,
})
} catch ( err : unknown ) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect (( err as any ). nonRetryable ). toBe ( true )
expect (( err as Error ). message ). toContain (
'Neither filePath nor assetKey was provided for video chunk transcoding' ,
)
}
})
it ( 'should throw retryable ApplicationFailure when ffmpeg fails' , async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;( child_process . execFile as any ). mockImplementation (
(
_file : string ,
_args : string [],
cb : ( err : Error | null , result : { stdout : string ; stderr : string }) => void ,
) => {
cb ( new Error ( 'ffmpeg segmentation fault' ), { stdout : '' , stderr : '' })
},
)
expect . assertions ( 2 )
try {
await transcodeVideoChunkActivity ({
assetId : 'asset-abc' ,
filePath : '/tmp/test.mp4' ,
startTime : 0 ,
endTime : 10 ,
})
} catch ( err : unknown ) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect (( err as any ). nonRetryable ). toBe ( false )
expect (( err as Error ). message ). toContain ( 'Failed to transcode video chunk' )
}
})
it ( 'should return existing poster if already present in S3' , async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi . mocked ( s3Service . headObject ). mockResolvedValue ({} as any )
const res = await extractPosterActivity ({
assetKey : 'video.mp4' ,
posterSpec : { key : 'poster.webp' },
})
expect ( res . poster . key ). toBe ( 'poster.webp' )
expect ( child_process . execFile ). not . toHaveBeenCalled ()
})
2026-09-25 16:37:16 +08:00
it ( 'should extract poster upfront and upload to S3' , async () => {
2026-09-08 10:17:15 +08:00
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( s3Service . resolveInput ). mockResolvedValue ( 'https://mock-r2.com/video.mp4' )
2026-09-25 16:37:16 +08:00
vi . mocked ( transcodeService . generatePoster ). mockImplementation ( async ( _in , posterOut ) => {
fs . writeFileSync ( posterOut , Buffer . from ( 'fake-poster-bytes' ))
})
2026-09-08 10:17:15 +08:00
const res = await extractPosterActivity ({
assetKey : 'video.mp4' ,
posterSpec : { key : 'files/asset-1/poster.webp' },
})
expect ( res . poster . key ). toBe ( 'files/asset-1/poster.webp' )
expect ( s3Service . resolveInput ). toHaveBeenCalledWith ( 'shumai' , 'video.mp4' )
2026-09-25 16:37:16 +08:00
expect ( transcodeService . generatePoster ). toHaveBeenCalledWith (
'https://mock-r2.com/video.mp4' ,
expect . stringContaining ( 'poster.webp' ),
{
isHdr : undefined ,
hdrType : undefined ,
colorTransfer : undefined ,
signal : undefined ,
},
2026-09-08 10:17:15 +08:00
)
expect ( s3Service . putObject ). toHaveBeenCalledWith (
'shumai' ,
'files/asset-1/poster.webp' ,
expect . any ( Buffer ),
expect . any ( Number ),
'image/webp' ,
)
})
2026-09-24 14:32:47 +08:00
it ( 'extractPosterActivity applies tone mapping filter when isHdr is true' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( s3Service . resolveInput ). mockResolvedValue ( 'https://mock-r2.com/video.mp4' )
2026-09-25 16:37:16 +08:00
vi . mocked ( transcodeService . generatePoster ). mockImplementation ( async ( _in , posterOut ) => {
fs . writeFileSync ( posterOut , Buffer . from ( 'fake-poster-bytes' ))
})
2026-09-24 14:32:47 +08:00
await extractPosterActivity ({
assetKey : 'video.mp4' ,
posterSpec : { key : 'files/asset-1/poster.webp' },
isHdr : true ,
hdrType : 'pq' ,
colorTransfer : 'smpte2084' ,
})
2026-09-25 16:37:16 +08:00
expect ( transcodeService . generatePoster ). toHaveBeenCalledWith (
'https://mock-r2.com/video.mp4' ,
expect . stringContaining ( 'poster.webp' ),
{
isHdr : true ,
hdrType : 'pq' ,
colorTransfer : 'smpte2084' ,
signal : undefined ,
},
)
2026-09-24 14:32:47 +08:00
})
2026-09-19 10:40:49 +08:00
it ( 'should throw non-retryable ApplicationFailure when poster extraction is cancelled with aborted signal' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
const controller = new AbortController ()
controller . abort ()
await expect (
extractPosterActivity ({
assetKey : 'video.mp4' ,
posterSpec : { key : 'files/asset-1/poster.webp' },
signal : controller.signal ,
}),
). rejects . toMatchObject ({
message : 'Poster extraction cancelled' ,
nonRetryable : true ,
})
})
it ( 'should throw non-retryable ApplicationFailure when poster extraction ffmpeg execution is aborted' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( s3Service . resolveInput ). mockResolvedValue ( 'https://mock-r2.com/video.mp4' )
const controller = new AbortController ()
2026-09-25 16:37:16 +08:00
const abortErr = new Error ( 'The operation was aborted' )
2026-09-19 10:40:49 +08:00
// eslint-disable-next-line @typescript-eslint/no-explicit-any
2026-09-25 16:37:16 +08:00
;( abortErr as any ). code = 'ABORT_ERR'
vi . mocked ( transcodeService . generatePoster ). mockRejectedValue ( abortErr )
2026-09-19 10:40:49 +08:00
await expect (
extractPosterActivity ({
assetKey : 'video.mp4' ,
posterSpec : { key : 'files/asset-1/poster.webp' },
signal : controller.signal ,
}),
). rejects . toMatchObject ({
message : 'Poster extraction cancelled' ,
nonRetryable : true ,
})
})
it ( 'should throw non-retryable ApplicationFailure and not upload when asset is pending_purge before poster upload' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( s3Service . resolveInput ). mockResolvedValue ( 'https://mock-r2.com/video.mp4' )
const putObjectSpy = vi . mocked ( s3Service . putObject )
putObjectSpy . mockClear ()
await prisma . asset . create ({
data : {
name : 'purging-poster.mp4' ,
storageKey : { create : { key : 'purging-poster.mp4' } },
status : 'pending_purge' ,
type : 'file' ,
},
})
2026-09-25 16:37:16 +08:00
vi . mocked ( transcodeService . generatePoster ). mockImplementation ( async ( _in , posterOut ) => {
fs . writeFileSync ( posterOut , Buffer . from ( 'fake-poster-bytes' ))
})
2026-09-19 10:40:49 +08:00
await expect (
extractPosterActivity ({
assetKey : 'purging-poster.mp4' ,
posterSpec : { key : 'files/asset-1/poster.webp' },
}),
). rejects . toMatchObject ({
message : 'Asset or storage key has been purged or is pending purge' ,
nonRetryable : true ,
})
expect ( putObjectSpy ). not . toHaveBeenCalled ()
})
2026-06-18 11:54:30 +08:00
it ( 'should delete S3 object successfully' , async () => {
await deleteS3ObjectActivity ({ key : 'files/test-key.mp4' })
expect ( s3Service . deleteObject ). toHaveBeenCalledWith ( 'shumai' , 'files/test-key.mp4' )
})
2026-07-05 15:11:19 +08:00
it ( 'should transcode audio file and upload proxy to S3' , async () => {
vi . mocked ( s3Service . headObject ). mockRejectedValue ( new Error ( 'Not found' ))
vi . mocked ( transcodeService . transcodeAudio ). mockResolvedValue ()
const res = await transcodeAudioActivity ({
assetKey : 'files/proj-123/a.wav' ,
filePath : '/tmp/a.wav' ,
2026-09-18 13:30:33 +08:00
threads : 4 ,
2026-07-05 15:11:19 +08:00
})
expect ( transcodeService . transcodeAudio ). toHaveBeenCalledWith ({
inputFile : '/tmp/a.wav' ,
outputFile : expect.stringContaining ( 'a-audio-proxy.mp4' ),
bitrate : '128k' ,
2026-09-18 13:30:33 +08:00
threads : 4 ,
2026-07-05 15:11:19 +08:00
})
expect ( s3Service . putObject ). toHaveBeenCalledWith (
'shumai' ,
'files/proj-123/a-audio-proxy.mp4' ,
2026-07-29 21:42:54 +08:00
expect . any ( ReadableStream ),
2026-07-05 15:11:19 +08:00
expect . any ( Number ),
'video/mp4' ,
)
expect ( res ). toEqual ({
width : 0 ,
height : 0 ,
key : 'files/proj-123/a-audio-proxy.mp4' ,
})
})
it ( 'should return existing audio transcode if already exists in S3' , async () => {
vi . mocked ( s3Service . headObject ). mockResolvedValue (
{} as Awaited < ReturnType < typeof s3Service.headObject >>,
)
const res = await transcodeAudioActivity ({
assetKey : 'files/proj-123/a.wav' ,
filePath : '/tmp/a.wav' ,
})
expect ( transcodeService . transcodeAudio ). not . toHaveBeenCalled ()
expect ( res ). toEqual ({
width : 0 ,
height : 0 ,
key : 'files/proj-123/a-audio-proxy.mp4' ,
})
})
2026-07-28 20:19:10 +08:00
it ( 'should create ai_metadata_autofill task when autofill agent exists and asset is image' , async () => {
const user = await prisma . user . create ({
data : { name : 'Test User Autofill' , email : 'test-autofill-agent@test.com' },
})
const team = await prisma . team . create ({
data : { name : 'Test Team Autofill' },
})
await prisma . teamMember . create ({
data : { teamId : team.id , userId : user.id , role : 'owner' },
})
const project = await prisma . project . create ({
data : { name : 'Test Project Autofill' , teamId : team.id },
})
const autofillAgent = await prisma . agent . create ({
data : {
id : user.id ,
type : 'autofill' ,
enabled : true ,
teamId : team.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config : { provider : 'test' , model : 'test' } as any ,
},
})
const asset = await prisma . asset . create ({
data : {
name : 'photo.png' ,
mediaType : 'image/png' ,
type : 'file' ,
status : 'processed' ,
projectId : project.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
media : { proxyType : 'image' } as any ,
},
})
await createAutofillTaskIfEnabledActivity ({
assetId : asset.id ,
teamId : team.id ,
projectId : project.id ,
})
const task = await prisma . workflowTask . findFirst ({
where : { assetId : asset.id , type : 'ai_metadata_autofill' },
})
expect ( task ). toBeDefined ()
expect ( task ? . status ). toBe ( 'pending' )
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect (( task ? . payload as any ) ? . agent ? . agentId ). toBe ( autofillAgent . id )
})
2026-09-08 14:19:03 +08:00
it ( 'should create ai_metadata_autofill task when autofill agent exists and asset is pdf' , async () => {
const user = await prisma . user . create ({
data : { name : 'Test User Autofill PDF' , email : 'test-autofill-agent-pdf@test.com' },
})
const team = await prisma . team . create ({
data : { name : 'Test Team Autofill PDF' },
})
await prisma . teamMember . create ({
data : { teamId : team.id , userId : user.id , role : 'owner' },
})
const project = await prisma . project . create ({
data : { name : 'Test Project Autofill PDF' , teamId : team.id },
})
const autofillAgent = await prisma . agent . create ({
data : {
id : user.id ,
type : 'autofill' ,
enabled : true ,
teamId : team.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config : { provider : 'test' , model : 'test' } as any ,
},
})
const asset = await prisma . asset . create ({
data : {
name : 'document.pdf' ,
mediaType : 'application/pdf' ,
type : 'file' ,
status : 'processed' ,
projectId : project.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
media : { proxyType : 'pdf' } as any ,
},
})
await createAutofillTaskIfEnabledActivity ({
assetId : asset.id ,
teamId : team.id ,
projectId : project.id ,
})
const task = await prisma . workflowTask . findFirst ({
where : { assetId : asset.id , type : 'ai_metadata_autofill' },
})
expect ( task ). toBeDefined ()
expect ( task ? . status ). toBe ( 'pending' )
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect (( task ? . payload as any ) ? . agent ? . agentId ). toBe ( autofillAgent . id )
})
it ( 'should create ai_metadata_autofill task when autofill agent exists and asset is audio' , async () => {
const user = await prisma . user . create ({
data : { name : 'Test User Autofill Audio' , email : 'test-autofill-agent-audio@test.com' },
})
const team = await prisma . team . create ({
data : { name : 'Test Team Autofill Audio' },
})
await prisma . teamMember . create ({
data : { teamId : team.id , userId : user.id , role : 'owner' },
})
const project = await prisma . project . create ({
data : { name : 'Test Project Autofill Audio' , teamId : team.id },
})
const autofillAgent = await prisma . agent . create ({
data : {
id : user.id ,
type : 'autofill' ,
enabled : true ,
teamId : team.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config : { provider : 'test' , model : 'test' } as any ,
},
})
const asset = await prisma . asset . create ({
data : {
name : 'audio.mp3' ,
mediaType : 'audio/mpeg' ,
type : 'file' ,
status : 'processed' ,
projectId : project.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
media : { proxyType : 'audio' } as any ,
},
})
await createAutofillTaskIfEnabledActivity ({
assetId : asset.id ,
teamId : team.id ,
projectId : project.id ,
})
const task = await prisma . workflowTask . findFirst ({
where : { assetId : asset.id , type : 'ai_metadata_autofill' },
})
expect ( task ). toBeDefined ()
expect ( task ? . status ). toBe ( 'pending' )
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect (( task ? . payload as any ) ? . agent ? . agentId ). toBe ( autofillAgent . id )
})
it ( 'should not create ai_metadata_autofill task if asset is a folder' , async () => {
const user = await prisma . user . create ({
data : { name : 'Test User Autofill Folder' , email : 'test-autofill-agent-folder@test.com' },
})
const team = await prisma . team . create ({
data : { name : 'Test Team Autofill Folder' },
})
await prisma . teamMember . create ({
data : { teamId : team.id , userId : user.id , role : 'owner' },
})
const project = await prisma . project . create ({
data : { name : 'Test Project Autofill Folder' , teamId : team.id },
})
await prisma . agent . create ({
data : {
id : user.id ,
type : 'autofill' ,
enabled : true ,
teamId : team.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config : { provider : 'test' , model : 'test' } as any ,
},
})
const folderAsset = await prisma . asset . create ({
data : {
name : 'Folder' ,
type : 'folder' ,
status : 'processed' ,
projectId : project.id ,
},
})
await createAutofillTaskIfEnabledActivity ({
assetId : folderAsset.id ,
teamId : team.id ,
projectId : project.id ,
})
const task = await prisma . workflowTask . findFirst ({
where : { assetId : folderAsset.id , type : 'ai_metadata_autofill' },
})
expect ( task ). toBeNull ()
})
2026-09-19 10:40:49 +08:00
it ( 'should create ai_metadata_autofill task when asset is in trash (isDeleted: true)' , async () => {
const user = await prisma . user . create ({
data : { name : 'Test User Trashed Autofill' , email : 'test-trashed-autofill@test.com' },
})
const team = await prisma . team . create ({
data : { name : 'Test Team Trashed Autofill' },
})
await prisma . teamMember . create ({
data : { teamId : team.id , userId : user.id , role : 'owner' },
})
const project = await prisma . project . create ({
data : { name : 'Test Project Trashed Autofill' , teamId : team.id },
})
const autofillAgent = await prisma . agent . create ({
data : {
id : user.id ,
type : 'autofill' ,
enabled : true ,
teamId : team.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config : { provider : 'test' , model : 'test' } as any ,
},
})
const asset = await prisma . asset . create ({
data : {
name : 'trashed-video.mp4' ,
mediaType : 'video/mp4' ,
type : 'file' ,
status : 'trashed' ,
isDeleted : true ,
projectId : project.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
media : { proxyType : 'video' } as any ,
},
})
await createAutofillTaskIfEnabledActivity ({
assetId : asset.id ,
teamId : team.id ,
projectId : project.id ,
})
const task = await prisma . workflowTask . findFirst ({
where : { assetId : asset.id , type : 'ai_metadata_autofill' },
})
expect ( task ). toBeDefined ()
expect ( task ? . status ). toBe ( 'pending' )
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect (( task ? . payload as any ) ? . agent ? . agentId ). toBe ( autofillAgent . id )
})
2026-06-18 11:54:30 +08:00
})
2026-10-13 00:03:21 +08:00
describe ( 'createEmbeddingTaskIfEnabledActivity' , () => {
it ( 'should create ai_embedding task for 3D asset with imageTranscodes' , async () => {
const user = await prisma . user . create ({
data : { name : 'Test User Embedding' , email : 'test-embedding-agent@test.com' },
})
const team = await prisma . team . create ({
data : { name : 'Test Team Embedding' },
})
await prisma . teamMember . create ({
data : { teamId : team.id , userId : user.id , role : 'owner' },
})
const project = await prisma . project . create ({
data : { name : 'Test Project Embedding' , teamId : team.id },
})
const embeddingAgent = await prisma . agent . create ({
data : {
id : user.id ,
type : 'embedding' ,
enabled : true ,
teamId : team.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config : { provider : 'test' , model : 'test' } as any ,
},
})
const asset = await prisma . asset . create ({
data : {
name : 'robot.glb' ,
mediaType : 'model/gltf-binary' ,
type : 'file' ,
status : 'processed' ,
projectId : project.id ,
media : {
proxyType : '3d' ,
imageTranscodes : [
{
key : 'files/asset-1/views.webp' ,
width : 2880 ,
height : 2880 ,
quality : 85 ,
format : 'webp' ,
},
],
} as unknown as PrismaJson . MediaInfo ,
},
})
await createEmbeddingTaskIfEnabledActivity ({
assetId : asset.id ,
teamId : team.id ,
projectId : project.id ,
})
const task = await prisma . workflowTask . findFirst ({
where : { assetId : asset.id , type : 'ai_embedding' },
})
expect ( task ). toBeDefined ()
expect ( task ? . status ). toBe ( 'pending' )
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect (( task ? . payload as any ) ? . agent ? . agentId ). toBe ( embeddingAgent . id )
})
it ( 'should NOT create ai_embedding task for 3D asset without imageTranscodes' , async () => {
const user = await prisma . user . create ({
data : { name : 'Test User Embedding 2' , email : 'test-embedding-agent-2@test.com' },
})
const team = await prisma . team . create ({
data : { name : 'Test Team Embedding 2' },
})
await prisma . teamMember . create ({
data : { teamId : team.id , userId : user.id , role : 'owner' },
})
const project = await prisma . project . create ({
data : { name : 'Test Project Embedding 2' , teamId : team.id },
})
await prisma . agent . create ({
data : {
id : user.id ,
type : 'embedding' ,
enabled : true ,
teamId : team.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config : { provider : 'test' , model : 'test' } as any ,
},
})
const asset = await prisma . asset . create ({
data : {
name : 'robot.glb' ,
mediaType : 'model/gltf-binary' ,
type : 'file' ,
status : 'processed' ,
projectId : project.id ,
media : {
proxyType : '3d' ,
imageTranscodes : [],
} as unknown as PrismaJson . MediaInfo ,
},
})
await createEmbeddingTaskIfEnabledActivity ({
assetId : asset.id ,
teamId : team.id ,
projectId : project.id ,
})
const task = await prisma . workflowTask . findFirst ({
where : { assetId : asset.id , type : 'ai_embedding' },
})
expect ( task ). toBeNull ()
})
2026-10-16 21:20:25 +08:00
it ( 'should NOT create ai_embedding task when ENABLE_EMBEDDING_AGENT is false' , async () => {
const user = await prisma . user . create ({
data : { name : 'Test User Embedding 3' , email : 'test-embedding-agent-3@test.com' },
})
const team = await prisma . team . create ({
data : { name : 'Test Team Embedding 3' },
})
await prisma . teamMember . create ({
data : { teamId : team.id , userId : user.id , role : 'owner' },
})
const project = await prisma . project . create ({
data : { name : 'Test Project Embedding 3' , teamId : team.id },
})
await prisma . agent . create ({
data : {
id : user.id ,
type : 'embedding' ,
enabled : true ,
teamId : team.id ,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config : { provider : 'test' , model : 'test' } as any ,
},
})
const asset = await prisma . asset . create ({
data : {
name : 'robot.glb' ,
mediaType : 'model/gltf-binary' ,
type : 'file' ,
status : 'processed' ,
projectId : project.id ,
media : {
proxyType : '3d' ,
imageTranscodes : [
{
key : 'files/asset-1/views.webp' ,
width : 2880 ,
height : 2880 ,
quality : 85 ,
format : 'webp' ,
},
],
} as unknown as PrismaJson . MediaInfo ,
},
})
process . env . ENABLE_EMBEDDING_AGENT = 'false'
try {
await createEmbeddingTaskIfEnabledActivity ({
assetId : asset.id ,
teamId : team.id ,
projectId : project.id ,
})
const task = await prisma . workflowTask . findFirst ({
where : { assetId : asset.id , type : 'ai_embedding' },
})
expect ( task ). toBeNull ()
} finally {
delete process . env . ENABLE_EMBEDDING_AGENT
}
})
2026-10-13 00:03:21 +08:00
})
2026-05-19 16:05:09 +08:00
})