2026-11-11 16:05:18 +08:00
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
2026-10-27 08:09:11 +08:00
import { authzService } from '@shumai/core/src/authz/authz'
import { getOperation } from '@shumai/core/src/operations'
2026-11-18 15:58:57 +08:00
import { runnerService } from '@shumai/core/src/runner'
2026-11-11 16:05:18 +08:00
import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma , type Asset , type StorageKey } from '@shumai/db'
import * as path from 'path'
2026-11-18 15:58:57 +08:00
import { beforeEach , describe , expect , it , vi } from 'vitest'
2026-10-27 08:09:11 +08:00
import { toAgentTool } from '../operation-tools'
import './download-asset'
vi . mock ( '@shumai/db' , async ( importOriginal ) => {
const actual = await importOriginal < typeof import ( '@shumai/db' ) >()
return {
... actual ,
prisma : {
asset : { findUnique : vi.fn (), findFirst : vi.fn () },
storageKey : { findFirst : vi.fn (), findUnique : vi.fn () },
},
}
})
vi . mock ( '@shumai/core/src/s3/s3' , async ( importOriginal ) => {
const actual = await importOriginal < typeof import ( '@shumai/core/src/s3/s3' ) >()
return {
... actual ,
s3Service : {
headObject : vi.fn (),
downloadToFile : vi.fn (),
presign : vi.fn (). mockResolvedValue ( 'https://signed.example/file' ),
},
}
})
2026-11-18 15:58:57 +08:00
vi . mock ( '@shumai/core/src/runner' , () => ({
runnerService : {
requireOnlineRunner : vi.fn (),
isRunnerConnected : vi.fn (),
downloadToRunner : vi.fn (),
},
}))
2026-10-27 08:09:11 +08:00
vi . mock ( '@shumai/core/src/authz/authz' , async ( importOriginal ) => {
const actual = await importOriginal < typeof import ( '@shumai/core/src/authz/authz' ) >()
return { ... actual , authzService : { hasPermission : vi.fn () } }
})
type Head = Awaited < ReturnType < typeof s3Service.headObject >>
2026-11-18 15:58:57 +08:00
type Saved = { filePath : string ; contentType : string ; size : number }
2026-10-27 08:09:11 +08:00
function downloadTool ( userId = 'user-1' ) {
2026-11-18 15:58:57 +08:00
return toAgentTool ( getOperation ( 'download_asset' ) ! , {
userId ,
teamId : 'team-1' ,
runnerId : null ,
})
2026-10-27 08:09:11 +08:00
}
function textOf ( result : { content : unknown [] }) : string {
return ( result . content [ 0 ] as { text : string }). text
}
function mockAssets (... assets : Array < Record < string , unknown >>) {
vi . mocked ( prisma . asset . findUnique ). mockImplementation (
( async ( args : { where : { id : string } }) =>
assets . find (( a ) => a . id === args . where . id ) ?? null ) as never ,
)
}
2026-11-18 15:58:57 +08:00
function mockStorage ( contentType : string , size = 11 ) {
vi . mocked ( s3Service . headObject ). mockResolvedValue ({ size , contentType } as Head )
vi . mocked ( runnerService . downloadToRunner ). mockResolvedValue ({
type : 'file.download.result' ,
executionId : 'exec-dl-1' ,
ok : true ,
size ,
mimeType : contentType ,
2026-10-27 08:09:11 +08:00
})
}
const photo = {
id : 'img-1' ,
name : 'sample_photo.jpg' ,
type : 'file' ,
isDeleted : false ,
storageKey : { key : 'files/up-1/sample_photo.jpg' },
media : { proxyType : 'image' , imageTranscodes : [{ key : 'files/img-1/proxy.webp' }] },
}
describe ( 'download_asset agent tool' , () => {
beforeEach (() => {
vi . clearAllMocks ()
vi . mocked ( authzService . hasPermission ). mockResolvedValue ()
2026-11-18 15:58:57 +08:00
vi . mocked ( runnerService . requireOnlineRunner ). mockResolvedValue ({
id : 'runner-1' ,
teamId : 'team-1' ,
name : 'Local Mac Mini' ,
keyPrefix : 'shm_rn_12345678' ,
isDefault : true ,
status : 'connected' ,
createdAt : '2026-11-14T00:00:00.000Z' ,
updatedAt : '2026-11-14T00:00:00.000Z' ,
})
2026-10-27 08:09:11 +08:00
})
it ( 'offers assetIds, proxy, and the agent-only key parameter' , () => {
const tool = downloadTool ()
const schema = tool . parameters as { properties : Record < string , unknown >; required? : string [] }
expect ( Object . keys ( schema . properties )). toEqual ([ 'assetIds' , 'proxy' , 'key' ])
expect ( schema . required ?? []). not . toContain ( 'assetIds' )
expect ( tool . description ). toContain ( '.pi directory' )
})
2026-11-18 15:58:57 +08:00
it ( 'saves the web preview into .pi on the runner by default, named after the asset' , async () => {
2026-10-27 08:09:11 +08:00
mockAssets ( photo )
2026-11-18 15:58:57 +08:00
mockStorage ( 'image/webp' , 11 )
2026-10-27 08:09:11 +08:00
2026-11-11 16:05:18 +08:00
const result = await invokeTool ( downloadTool (), 'call-1' , { assetIds : [ 'img-1' ] })
2026-10-27 08:09:11 +08:00
expect ( authzService . hasPermission ). toHaveBeenCalledWith ({
user : { id : 'user-1' },
permission : 'Read' ,
type : 'asset' ,
id : 'img-1' ,
})
2026-11-18 15:58:57 +08:00
expect ( runnerService . requireOnlineRunner ). toHaveBeenCalledWith ( 'team-1' , null )
expect ( runnerService . downloadToRunner ). toHaveBeenCalledWith ( 'runner-1' , {
url : 'https://signed.example/file' ,
destPath : path.posix.join ( '.pi' , 'img-1_sample_photo.webp' ),
})
2026-10-27 08:09:11 +08:00
expect ( textOf ( result )). toBe (
[
2026-11-18 15:58:57 +08:00
`Downloaded "sample_photo.webp" (ID: img-1, proxy, image/webp, 11 B) to " ${ path . posix . join ( '.pi' , 'img-1_sample_photo.webp' ) } ".` ,
2026-10-27 08:09:11 +08:00
'Remember to delete these temporary files when finished.' ,
]. join ( '\n' ),
)
const details = result . details as { files : Saved [] }
expect ( details . files [ 0 ]). toMatchObject ({
2026-11-18 15:58:57 +08:00
filePath : path.posix.join ( '.pi' , 'img-1_sample_photo.webp' ),
2026-10-27 08:09:11 +08:00
contentType : 'image/webp' ,
size : 11 ,
})
})
it ( 'saves the original with proxy false' , async () => {
mockAssets ( photo )
2026-11-18 15:58:57 +08:00
mockStorage ( 'image/jpeg' , 1234 )
2026-10-27 08:09:11 +08:00
2026-11-11 16:05:18 +08:00
await invokeTool ( downloadTool (), 'call-1' , { assetIds : [ 'img-1' ], proxy : false })
2026-10-27 08:09:11 +08:00
2026-11-18 15:58:57 +08:00
expect ( s3Service . presign ). toHaveBeenCalledWith (
2026-10-27 08:09:11 +08:00
'shumai' ,
'files/up-1/sample_photo.jpg' ,
2026-11-18 15:58:57 +08:00
'GET' ,
false ,
undefined ,
false ,
600 ,
2026-10-27 08:09:11 +08:00
)
2026-11-18 15:58:57 +08:00
expect ( runnerService . downloadToRunner ). toHaveBeenCalledWith ( 'runner-1' , {
url : 'https://signed.example/file' ,
destPath : path.posix.join ( '.pi' , 'img-1_sample_photo.jpg' ),
})
2026-10-27 08:09:11 +08:00
})
it ( 'downloads several files and the latest version of a version stack' , async () => {
mockAssets ( photo , { id : 'stack-1' , name : 'banana' , type : 'version_stack' , isDeleted : false })
vi . mocked ( prisma . asset . findFirst ). mockResolvedValue ({
id : 'file-v2' ,
name : 'banana_pig.png' ,
type : 'file' ,
isDeleted : false ,
storageKey : { key : 'files/up-2/banana_pig.png' },
media : { proxyType : 'image' , imageTranscodes : [{ key : 'files/file-v2/proxy.webp' }] },
} as unknown as Asset )
mockStorage ( 'image/webp' )
2026-11-11 16:05:18 +08:00
const result = await invokeTool ( downloadTool (), 'call-1' , {
2026-10-27 08:09:11 +08:00
assetIds : [ 'img-1' , 'stack-1' ],
key : null ,
})
expect ( prisma . asset . findFirst ). toHaveBeenCalledWith ({
where : { parentId : 'stack-1' , isDeleted : false },
orderBy : { sortIndex : 'asc' },
include : { storageKey : true },
})
2026-11-18 15:58:57 +08:00
expect ( runnerService . downloadToRunner ). toHaveBeenCalledTimes ( 2 )
2026-10-27 08:09:11 +08:00
expect ( textOf ( result )). toContain ( 'Downloaded "banana_pig.webp" (ID: file-v2, proxy' )
})
it ( 'rejects folders' , async () => {
mockAssets ({ id : 'folder-1' , name : 'Renders' , type : 'folder' , isDeleted : false })
2026-11-11 16:05:18 +08:00
await expect ( invokeTool ( downloadTool (), 'call-1' , { assetIds : [ 'folder-1' ] })). rejects . toThrow (
2026-10-27 08:09:11 +08:00
'Asset folder-1 ("Renders") is a folder. Download the files inside it instead.' ,
)
2026-11-18 15:58:57 +08:00
expect ( runnerService . downloadToRunner ). not . toHaveBeenCalled ()
2026-10-27 08:09:11 +08:00
})
it ( 'checks Read on every asset before downloading anything' , async () => {
mockAssets ( photo )
vi . mocked ( authzService . hasPermission ). mockImplementation ( async ({ id }) => {
if ( id === 'secret' ) throw new Error ( 'Forbidden' )
})
await expect (
2026-11-11 16:05:18 +08:00
invokeTool ( downloadTool (), 'call-1' , { assetIds : [ 'img-1' , 'secret' ] }),
2026-10-27 08:09:11 +08:00
). rejects . toThrow ( 'Forbidden' )
2026-11-18 15:58:57 +08:00
expect ( runnerService . downloadToRunner ). not . toHaveBeenCalled ()
2026-10-27 08:09:11 +08:00
})
it ( 'requires assetIds or key' , async () => {
2026-11-11 16:05:18 +08:00
await expect (
invokeTool ( downloadTool (), 'call-1' , { assetIds : null , key : null }),
). rejects . toThrow ( 'Invalid input for download_asset' )
2026-10-27 08:09:11 +08:00
})
it ( 'rejects assetIds and key together' , async () => {
await expect (
2026-11-11 16:05:18 +08:00
invokeTool ( downloadTool (), 'call-1' , { assetIds : [ 'img-1' ], key : 'files/img-1/a.webp' }),
2026-10-27 08:09:11 +08:00
). rejects . toThrow ( 'Provide either "assetIds" or "key", not both.' )
})
describe ( 'by storage key' , () => {
it ( 'requires a user' , async () => {
await expect (
2026-11-11 16:05:18 +08:00
invokeTool ( downloadTool ( '' ), 'call-1' , { key : 'files/ast-1/shot.webp' }),
2026-10-27 08:09:11 +08:00
). rejects . toThrow ( 'User ID is required for authorization.' )
})
it ( 'rejects keys outside files/ and path traversal' , async () => {
await expect (
2026-11-11 16:05:18 +08:00
invokeTool ( downloadTool (), 'call-1' , { key : 'avatars/user-1.png' }),
). rejects . toThrow ( 'Invalid storage key format: key must start with "files/"' )
await expect (
invokeTool ( downloadTool (), 'call-1' , { key : 'files/../../etc/passwd' }),
2026-10-27 08:09:11 +08:00
). rejects . toThrow ( 'cannot contain ".."' )
})
it ( 'rejects keys that belong to no asset' , async () => {
vi . mocked ( prisma . asset . findUnique ). mockResolvedValue ( null )
vi . mocked ( prisma . storageKey . findFirst ). mockResolvedValue ( null )
vi . mocked ( prisma . storageKey . findUnique ). mockResolvedValue ( null )
await expect (
2026-11-11 16:05:18 +08:00
invokeTool ( downloadTool (), 'call-1' , { key : 'files/nope/shot.webp' }),
2026-10-27 08:09:11 +08:00
). rejects . toThrow ( 'does not belong to any valid asset or the asset has been deleted' )
})
it ( 'checks Read on the owning asset' , async () => {
mockAssets ({ id : 'other-project-asset' })
vi . mocked ( authzService . hasPermission ). mockRejectedValue ( new Error ( 'Forbidden' ))
await expect (
2026-11-11 16:05:18 +08:00
invokeTool ( downloadTool (), 'call-1' , { key : 'files/other-project-asset/shots/a.webp' }),
2026-10-27 08:09:11 +08:00
). rejects . toThrow ( 'Forbidden' )
expect ( authzService . hasPermission ). toHaveBeenCalledWith ({
user : { id : 'user-1' },
permission : 'Read' ,
type : 'asset' ,
id : 'other-project-asset' ,
})
2026-11-18 15:58:57 +08:00
expect ( runnerService . downloadToRunner ). not . toHaveBeenCalled ()
2026-10-27 08:09:11 +08:00
})
2026-11-18 15:58:57 +08:00
it ( 'downloads a read_asset artifact into .pi on the runner' , async () => {
2026-10-27 08:09:11 +08:00
mockAssets ({ id : 'ast-123' })
2026-11-18 15:58:57 +08:00
mockStorage ( 'image/webp' , 11 )
2026-10-27 08:09:11 +08:00
2026-11-11 16:05:18 +08:00
const result = await invokeTool ( downloadTool (), 'call-1' , {
2026-10-27 08:09:11 +08:00
key : 'files/ast-123/screenshots/shot_5.0s.webp' ,
})
2026-11-18 15:58:57 +08:00
expect ( runnerService . downloadToRunner ). toHaveBeenCalledWith ( 'runner-1' , {
url : 'https://signed.example/file' ,
destPath : path.posix.join ( '.pi' , 'shot_5.0s.webp' ),
})
2026-10-27 08:09:11 +08:00
expect ( textOf ( result )). toBe (
2026-11-18 15:58:57 +08:00
`Downloaded storage key "files/ast-123/screenshots/shot_5.0s.webp" to " ${ path . posix . join ( '.pi' , 'shot_5.0s.webp' ) } ". Remember to delete this temporary file when finished.` ,
2026-10-27 08:09:11 +08:00
)
expect ( result . details ). toMatchObject ({
key : 'files/ast-123/screenshots/shot_5.0s.webp' ,
assetId : 'ast-123' ,
2026-11-18 15:58:57 +08:00
size : 11 ,
2026-10-27 08:09:11 +08:00
})
})
it ( 'resolves original upload keys through the storage key' , async () => {
vi . mocked ( prisma . asset . findUnique ). mockResolvedValue ( null )
vi . mocked ( prisma . storageKey . findFirst ). mockResolvedValue ({
id : 'sk-1' ,
key : 'files/upload-ulid-456/photo.png' ,
assets : [{ id : 'asset-photo-1' }],
} as unknown as StorageKey & { assets : Asset [] })
vi . mocked ( s3Service . headObject ). mockResolvedValue ({
size : 8 ,
contentType : 'application/octet-stream' ,
} as Head )
2026-11-18 15:58:57 +08:00
vi . mocked ( runnerService . downloadToRunner ). mockResolvedValue ({
type : 'file.download.result' ,
executionId : 'exec-dl-2' ,
ok : true ,
size : 8 ,
mimeType : 'image/png' ,
2026-10-27 08:09:11 +08:00
})
2026-11-11 16:05:18 +08:00
const result = await invokeTool ( downloadTool (), 'call-1' , {
2026-10-27 08:09:11 +08:00
key : 'files/upload-ulid-456/photo.png' ,
})
expect ( authzService . hasPermission ). toHaveBeenCalledWith (
expect . objectContaining ({ id : 'asset-photo-1' }),
)
expect ( result . details ). toMatchObject ({ assetId : 'asset-photo-1' , contentType : 'image/png' })
})
})
})