mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-05 15:44:28 +00:00
feat(agent): enable read_asset tool for autofill agent (#396)
* feat(agent): enable read_asset tool for autofill agent * fix(transcode): trigger autofill task for pdf assets * fix(transcode): allow autofill task creation on all file assets * fix(agent): require targetAssetId and teamId for autofill read_asset authorization * feat(agent): instruct autofill agent to report failure directly if read_asset fails
This commit is contained in:
@@ -472,6 +472,82 @@ describe('Agent Activities', () => {
|
|||||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let capturedSystemPrompt = ''
|
||||||
|
vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => {
|
||||||
|
const params = config as {
|
||||||
|
systemPrompt?: string
|
||||||
|
customTools: Array<{
|
||||||
|
name: string
|
||||||
|
execute: (id: string, args: Record<string, unknown>) => Promise<unknown>
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
capturedSystemPrompt = params.systemPrompt ?? ''
|
||||||
|
const tool = params.customTools.find((t) => t.name === 'autofill_metadata')
|
||||||
|
if (tool) {
|
||||||
|
await tool.execute('1', { f1: 'val' })
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Mock AgentHarness instance for activity test
|
||||||
|
harness: mockHarness as unknown as AgentHarness<any, any, any, any>,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const context = {
|
||||||
|
agent: {
|
||||||
|
id: 'b1',
|
||||||
|
type: 'autofill',
|
||||||
|
provider: { name: 'google' },
|
||||||
|
modelRef: { modelId: 'gemini' },
|
||||||
|
},
|
||||||
|
dbProviders: [],
|
||||||
|
teamSkills: [],
|
||||||
|
allowedDomains: [],
|
||||||
|
} as unknown as AgentExecutionContext
|
||||||
|
|
||||||
|
await autofillAiActivity({
|
||||||
|
teamId: 't1',
|
||||||
|
assetId: 'a1',
|
||||||
|
assetName: 'test.mp4',
|
||||||
|
mediaType: 'video/mp4',
|
||||||
|
duration: 30.5,
|
||||||
|
images: [],
|
||||||
|
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
|
||||||
|
context,
|
||||||
|
})
|
||||||
|
|
||||||
|
const capturedPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? ''
|
||||||
|
expect(capturedPrompt).toContain('You are tasked with analyzing the asset "test.mp4"')
|
||||||
|
expect(capturedPrompt).toContain('Call the "read_asset" tool with assetId: "a1"')
|
||||||
|
expect(capturedPrompt).toContain(
|
||||||
|
'Video duration: 30.5s. Recommended inspection: call read_asset with videoConfig: { start: 0, end: 30.5, count: 10 }.',
|
||||||
|
)
|
||||||
|
expect(capturedPrompt).toContain(
|
||||||
|
'call the "autofill_metadata" tool to provide the extracted metadata values.',
|
||||||
|
)
|
||||||
|
expect(capturedPrompt).toContain(
|
||||||
|
'If "read_asset" fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.',
|
||||||
|
)
|
||||||
|
expect(capturedPrompt).not.toContain('<context>')
|
||||||
|
|
||||||
|
expect(capturedSystemPrompt).toContain(
|
||||||
|
"If 'read_asset' fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should include PDF page count recommendations in autofill prompt when present', async () => {
|
||||||
|
const mockHarness = {
|
||||||
|
subscribe: vi.fn(),
|
||||||
|
prompt: vi.fn().mockResolvedValue({
|
||||||
|
content: [{ type: 'text', text: 'Captured' }],
|
||||||
|
usage: { input: 5, output: 5 },
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
const mockSession = {
|
||||||
|
getEntries: vi.fn().mockResolvedValue([]),
|
||||||
|
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||||
|
}
|
||||||
|
|
||||||
vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => {
|
vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => {
|
||||||
const params = config as {
|
const params = config as {
|
||||||
customTools: Array<{
|
customTools: Array<{
|
||||||
@@ -499,14 +575,20 @@ describe('Agent Activities', () => {
|
|||||||
|
|
||||||
await autofillAiActivity({
|
await autofillAiActivity({
|
||||||
teamId: 't1',
|
teamId: 't1',
|
||||||
|
assetId: 'pdf-1',
|
||||||
|
assetName: 'report.pdf',
|
||||||
|
mediaType: 'application/pdf',
|
||||||
|
pageCount: 15,
|
||||||
images: [],
|
images: [],
|
||||||
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
|
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
|
||||||
context,
|
context,
|
||||||
})
|
})
|
||||||
|
|
||||||
const capturedPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? ''
|
const capturedPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? ''
|
||||||
expect(capturedPrompt).toContain('Analyze the provided images and extract metadata.')
|
expect(capturedPrompt).toContain('You are tasked with analyzing the asset "report.pdf"')
|
||||||
expect(capturedPrompt).not.toContain('<context>')
|
expect(capturedPrompt).toContain(
|
||||||
|
'Document pages: 15. Recommended inspection: call read_asset with docConfig: { mode: "pages", startPage: 1, endPage: 15 } or mode: "text".',
|
||||||
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -178,6 +178,10 @@ User messages may contain a <context> block detailing the user, active asset loc
|
|||||||
systemPrompt += `\n\n# Comment Threads\nWhen operating in comment mode, previous top-level messages in the conversation history may contain a <thread id="..." reply_count="..." /> tag indicating an earlier discussion thread with replies. If a user's question refers to or depends on earlier comments or discussions, you can use the 'read_thread' tool with the thread ID to inspect all replies in that thread.`
|
systemPrompt += `\n\n# Comment Threads\nWhen operating in comment mode, previous top-level messages in the conversation history may contain a <thread id="..." reply_count="..." /> tag indicating an earlier discussion thread with replies. If a user's question refers to or depends on earlier comments or discussions, you can use the 'read_thread' tool with the thread ID to inspect all replies in that thread.`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (agent.type === 'autofill') {
|
||||||
|
systemPrompt += `\n\n# Autofill Instructions\nWhen performing metadata autofill, inspect the asset content using the 'read_asset' tool. If 'read_asset' fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.`
|
||||||
|
}
|
||||||
|
|
||||||
const agentConfig = agent.config as PrismaJson.AgentConfig | null | undefined
|
const agentConfig = agent.config as PrismaJson.AgentConfig | null | undefined
|
||||||
const thinkingLevel = agentConfig?.thinkingLevel || 'off'
|
const thinkingLevel = agentConfig?.thinkingLevel || 'off'
|
||||||
|
|
||||||
@@ -210,6 +214,7 @@ User messages may contain a <context> block detailing the user, active asset loc
|
|||||||
sessionId: params.sessionId,
|
sessionId: params.sessionId,
|
||||||
userId: params.userId,
|
userId: params.userId,
|
||||||
projectId: params.projectId,
|
projectId: params.projectId,
|
||||||
|
assetId: params.assetId,
|
||||||
userCommentId: params.userCommentId,
|
userCommentId: params.userCommentId,
|
||||||
customTools: [...(params.tools || []), ...mcpTools],
|
customTools: [...(params.tools || []), ...mcpTools],
|
||||||
providers: dbProviders.map((p) => ({
|
providers: dbProviders.map((p) => ({
|
||||||
@@ -522,22 +527,25 @@ export async function agentChatActivity(params: AgentChatParams) {
|
|||||||
|
|
||||||
export interface AutofillAiParams {
|
export interface AutofillAiParams {
|
||||||
teamId: string
|
teamId: string
|
||||||
images: string[]
|
images?: string[]
|
||||||
fields: AutofillField[]
|
fields: AutofillField[]
|
||||||
context: AgentExecutionContext
|
context: AgentExecutionContext
|
||||||
assetId?: string
|
assetId?: string
|
||||||
projectId?: string
|
projectId?: string
|
||||||
|
assetName?: string
|
||||||
|
mediaType?: string
|
||||||
|
duration?: number
|
||||||
|
pageCount?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function autofillAiActivity(params: AutofillAiParams) {
|
export async function autofillAiActivity(params: AutofillAiParams) {
|
||||||
const prompt = 'Analyze the provided images and extract metadata.'
|
|
||||||
const toolSchema = fieldsToTypeBoxSchema(params.fields)
|
const toolSchema = fieldsToTypeBoxSchema(params.fields)
|
||||||
let capturedData: Record<string, unknown> | null = null
|
let capturedData: Record<string, unknown> | null = null
|
||||||
|
|
||||||
const autofillTool: AgentTool = {
|
const autofillTool: AgentTool = {
|
||||||
name: 'autofill_metadata',
|
name: 'autofill_metadata',
|
||||||
label: 'Autofill Metadata',
|
label: 'Autofill Metadata',
|
||||||
description: 'Extract metadata from the images.',
|
description: 'Provide the extracted metadata once you have analyzed the asset content.',
|
||||||
parameters: toolSchema,
|
parameters: toolSchema,
|
||||||
execute: async (_toolCallId, toolParams) => {
|
execute: async (_toolCallId, toolParams) => {
|
||||||
capturedData = toolParams as Record<string, unknown>
|
capturedData = toolParams as Record<string, unknown>
|
||||||
@@ -548,7 +556,30 @@ export async function autofillAiActivity(params: AutofillAiParams) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
const fullPrompt = `${prompt}\n\nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
|
const promptLines: string[] = [
|
||||||
|
`You are tasked with analyzing the asset "${params.assetName || params.assetId || 'unknown'}" (ID: "${params.assetId || ''}", mediaType: "${params.mediaType || 'unknown'}") to extract and autofill its metadata fields.`,
|
||||||
|
]
|
||||||
|
|
||||||
|
if (params.duration !== undefined && params.duration > 0) {
|
||||||
|
promptLines.push(
|
||||||
|
`- Video duration: ${params.duration.toFixed(1)}s. Recommended inspection: call read_asset with videoConfig: { start: 0, end: ${params.duration.toFixed(1)}, count: 10 }.`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (params.pageCount !== undefined && params.pageCount > 0) {
|
||||||
|
promptLines.push(
|
||||||
|
`- Document pages: ${params.pageCount}. Recommended inspection: call read_asset with docConfig: { mode: "pages", startPage: 1, endPage: ${Math.min(params.pageCount, 20)} } or mode: "text".`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
promptLines.push(
|
||||||
|
'',
|
||||||
|
'Instructions:',
|
||||||
|
`1. Call the "read_asset" tool with assetId: "${params.assetId || ''}" to inspect the asset content (use imageConfig, videoConfig, or docConfig according to the media type).`,
|
||||||
|
'2. After analyzing the retrieved content, call the "autofill_metadata" tool to provide the extracted metadata values.',
|
||||||
|
'3. If "read_asset" fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.',
|
||||||
|
)
|
||||||
|
|
||||||
|
const fullPrompt = promptLines.join('\n')
|
||||||
|
|
||||||
const { agent } = params.context
|
const { agent } = params.context
|
||||||
|
|
||||||
@@ -556,7 +587,7 @@ export async function autofillAiActivity(params: AutofillAiParams) {
|
|||||||
teamId: params.teamId,
|
teamId: params.teamId,
|
||||||
agentId: agent.id,
|
agentId: agent.id,
|
||||||
prompt: fullPrompt,
|
prompt: fullPrompt,
|
||||||
images: params.images,
|
images: params.images || [],
|
||||||
sessionId: undefined,
|
sessionId: undefined,
|
||||||
userId: undefined,
|
userId: undefined,
|
||||||
projectId: params.projectId,
|
projectId: params.projectId,
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ export interface CreateAgentSessionParams {
|
|||||||
sessionId?: string
|
sessionId?: string
|
||||||
userId?: string
|
userId?: string
|
||||||
projectId?: string
|
projectId?: string
|
||||||
|
assetId?: string
|
||||||
userCommentId?: string | null
|
userCommentId?: string | null
|
||||||
customTools?: AgentTool[]
|
customTools?: AgentTool[]
|
||||||
thinkingLevel?: string
|
thinkingLevel?: string
|
||||||
@@ -149,6 +150,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
|||||||
sessionId,
|
sessionId,
|
||||||
userId,
|
userId,
|
||||||
projectId,
|
projectId,
|
||||||
|
assetId,
|
||||||
userCommentId: passedUserCommentId,
|
userCommentId: passedUserCommentId,
|
||||||
customTools = [],
|
customTools = [],
|
||||||
thinkingLevel,
|
thinkingLevel,
|
||||||
@@ -316,17 +318,25 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const mediaTools: AgentTool[] = []
|
|
||||||
if (userId) {
|
|
||||||
mediaTools.push(createReadAssetTool(userId))
|
|
||||||
}
|
|
||||||
|
|
||||||
const agent = await prisma.agent.findUnique({
|
const agent = await prisma.agent.findUnique({
|
||||||
where: { id: agentId },
|
where: { id: agentId },
|
||||||
})
|
})
|
||||||
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
|
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
|
||||||
const deniedTools = agentConfig?.deniedTools ?? [...DEFAULT_DENIED_TOOLS]
|
const deniedTools = agentConfig?.deniedTools ?? [...DEFAULT_DENIED_TOOLS]
|
||||||
|
|
||||||
|
const mediaTools: AgentTool[] = []
|
||||||
|
if (userId) {
|
||||||
|
mediaTools.push(createReadAssetTool(userId))
|
||||||
|
} else if (agent?.type === 'autofill' && assetId) {
|
||||||
|
mediaTools.push(
|
||||||
|
createReadAssetTool({
|
||||||
|
teamId,
|
||||||
|
agentType: 'autofill',
|
||||||
|
targetAssetId: assetId,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
if (!deniedTools.includes('generate_image') || !deniedTools.includes('generate_video')) {
|
if (!deniedTools.includes('generate_image') || !deniedTools.includes('generate_video')) {
|
||||||
try {
|
try {
|
||||||
const { imageModels, videoModels, providerKeys } =
|
const { imageModels, videoModels, providerKeys } =
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
import { createReadAssetTool } from './read-asset'
|
import { createReadAssetTool, type ReadAssetAuthContext } from './read-asset'
|
||||||
import {
|
import {
|
||||||
prisma,
|
prisma,
|
||||||
WorkflowTaskType,
|
WorkflowTaskType,
|
||||||
@@ -641,4 +641,135 @@ describe('readAssetTool', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('ReadAssetAuthContext & Security Boundaries', () => {
|
||||||
|
it('throws authorization error if chat agent lacks userId', async () => {
|
||||||
|
const tool = createReadAssetTool({
|
||||||
|
agentType: 'chat',
|
||||||
|
teamId: 'team-1',
|
||||||
|
})
|
||||||
|
await expect(
|
||||||
|
tool.execute('call-1', {
|
||||||
|
assetId: 'asset-1',
|
||||||
|
annotationId: null,
|
||||||
|
imageConfig: null,
|
||||||
|
videoConfig: null,
|
||||||
|
docConfig: null,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('User ID is required for authorization.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('throws error if autofill agent lacks targetAssetId', async () => {
|
||||||
|
const tool = createReadAssetTool({
|
||||||
|
agentType: 'autofill',
|
||||||
|
teamId: 'team-1',
|
||||||
|
} as unknown as ReadAssetAuthContext)
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
tool.execute('call-1', {
|
||||||
|
assetId: 'asset-1',
|
||||||
|
annotationId: null,
|
||||||
|
imageConfig: null,
|
||||||
|
videoConfig: null,
|
||||||
|
docConfig: null,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('Target asset ID is required for autofill agent authorization.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('throws error if autofill agent lacks teamId', async () => {
|
||||||
|
const tool = createReadAssetTool({
|
||||||
|
agentType: 'autofill',
|
||||||
|
targetAssetId: 'asset-1',
|
||||||
|
} as unknown as ReadAssetAuthContext)
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
tool.execute('call-1', {
|
||||||
|
assetId: 'asset-1',
|
||||||
|
annotationId: null,
|
||||||
|
imageConfig: null,
|
||||||
|
videoConfig: null,
|
||||||
|
docConfig: null,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('Team ID is required for autofill agent authorization.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('denies autofill agent if asset belongs to another team', async () => {
|
||||||
|
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||||
|
id: 'asset-1',
|
||||||
|
project: { teamId: 'other-team' },
|
||||||
|
} as unknown as Asset)
|
||||||
|
|
||||||
|
const tool = createReadAssetTool({
|
||||||
|
agentType: 'autofill',
|
||||||
|
teamId: 'team-1',
|
||||||
|
targetAssetId: 'asset-1',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
tool.execute('call-1', {
|
||||||
|
assetId: 'asset-1',
|
||||||
|
annotationId: null,
|
||||||
|
imageConfig: null,
|
||||||
|
videoConfig: null,
|
||||||
|
docConfig: null,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('Access denied: asset asset-1 does not belong to team team-1.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('denies autofill agent if reading an unrelated asset not matching targetAssetId', async () => {
|
||||||
|
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||||
|
id: 'other-asset',
|
||||||
|
parentId: null,
|
||||||
|
project: { teamId: 'team-1' },
|
||||||
|
} as unknown as Asset)
|
||||||
|
|
||||||
|
const tool = createReadAssetTool({
|
||||||
|
agentType: 'autofill',
|
||||||
|
teamId: 'team-1',
|
||||||
|
targetAssetId: 'target-asset-id',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
tool.execute('call-1', {
|
||||||
|
assetId: 'other-asset',
|
||||||
|
annotationId: null,
|
||||||
|
imageConfig: null,
|
||||||
|
videoConfig: null,
|
||||||
|
docConfig: null,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('Access denied: autofill agent can only read target asset target-asset-id.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows autofill agent to read target asset without userId', async () => {
|
||||||
|
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||||
|
id: 'target-asset-id',
|
||||||
|
name: 'test.png',
|
||||||
|
mediaType: 'image/png',
|
||||||
|
storageKey: { key: 'raw/test.png' },
|
||||||
|
media: { proxyType: 'image' },
|
||||||
|
project: { teamId: 'team-1' },
|
||||||
|
} as unknown as Asset)
|
||||||
|
|
||||||
|
const tool = createReadAssetTool({
|
||||||
|
agentType: 'autofill',
|
||||||
|
teamId: 'team-1',
|
||||||
|
targetAssetId: 'target-asset-id',
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await tool.execute('call-1', {
|
||||||
|
assetId: 'target-asset-id',
|
||||||
|
annotationId: null,
|
||||||
|
s3KeyOnly: true,
|
||||||
|
imageConfig: null,
|
||||||
|
videoConfig: null,
|
||||||
|
docConfig: null,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(authzService.hasPermission).not.toHaveBeenCalled()
|
||||||
|
expect(result.content.length).toBe(1)
|
||||||
|
expect((result.content[0] as { type: 'text'; text: string }).text).toContain(
|
||||||
|
'target-asset-id',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -141,7 +141,27 @@ export function isPlainTextAsset(mediaType: string, filename: string): boolean {
|
|||||||
const MAX_TEXT_BYTES = 50 * 1024
|
const MAX_TEXT_BYTES = 50 * 1024
|
||||||
const MAX_TEXT_LINES = 1000
|
const MAX_TEXT_LINES = 1000
|
||||||
|
|
||||||
export function createReadAssetTool(userId: string): AgentTool<typeof readAssetSchema> {
|
export type ReadAssetAuthContext =
|
||||||
|
| {
|
||||||
|
userId?: string
|
||||||
|
teamId?: string
|
||||||
|
agentType?: 'chat' | 'embedding'
|
||||||
|
targetAssetId?: string
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
userId?: undefined
|
||||||
|
teamId: string
|
||||||
|
agentType: 'autofill'
|
||||||
|
targetAssetId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createReadAssetTool(
|
||||||
|
auth: string | ReadAssetAuthContext,
|
||||||
|
): AgentTool<typeof readAssetSchema> {
|
||||||
|
const authContext: ReadAssetAuthContext =
|
||||||
|
typeof auth === 'string' ? { userId: auth, agentType: 'chat' } : auth
|
||||||
|
const { userId, teamId, agentType = 'chat', targetAssetId } = authContext
|
||||||
|
|
||||||
return {
|
return {
|
||||||
name: 'read_asset',
|
name: 'read_asset',
|
||||||
label: 'Read Asset',
|
label: 'Read Asset',
|
||||||
@@ -154,16 +174,48 @@ export function createReadAssetTool(userId: string): AgentTool<typeof readAssetS
|
|||||||
execute: async (_toolCallId, params) => {
|
execute: async (_toolCallId, params) => {
|
||||||
const { assetId, annotationId, s3KeyOnly, videoConfig, docConfig } = params
|
const { assetId, annotationId, s3KeyOnly, videoConfig, docConfig } = params
|
||||||
|
|
||||||
if (!userId) {
|
if (agentType === 'autofill' && !userId) {
|
||||||
throw new Error('User ID is required for authorization.')
|
if (!targetAssetId) {
|
||||||
}
|
throw new Error('Target asset ID is required for autofill agent authorization.')
|
||||||
|
}
|
||||||
|
if (!teamId) {
|
||||||
|
throw new Error('Team ID is required for autofill agent authorization.')
|
||||||
|
}
|
||||||
|
|
||||||
await authzService.hasPermission({
|
// System background execution for Autofill Agent
|
||||||
user: { id: userId } as User,
|
const assetRecord = await prisma.asset.findUnique({
|
||||||
permission: Permission.Read,
|
where: { id: assetId },
|
||||||
type: ResourceType.Asset,
|
include: { project: true, teamRootFolder: true },
|
||||||
id: assetId,
|
})
|
||||||
})
|
if (!assetRecord) {
|
||||||
|
throw new Error(`Asset with ID ${assetId} not found.`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strict team boundary check
|
||||||
|
const assetTeamId = assetRecord.project?.teamId || assetRecord.teamRootFolder?.id
|
||||||
|
if (!assetTeamId || assetTeamId !== teamId) {
|
||||||
|
throw new Error(`Access denied: asset ${assetId} does not belong to team ${teamId}.`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strict target asset boundary check (allows the target asset or its version stack children)
|
||||||
|
if (assetRecord.id !== targetAssetId && assetRecord.parentId !== targetAssetId) {
|
||||||
|
throw new Error(
|
||||||
|
`Access denied: autofill agent can only read target asset ${targetAssetId}.`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Chat agents or user-driven executions strictly require a userId and full ACL validation
|
||||||
|
if (!userId) {
|
||||||
|
throw new Error('User ID is required for authorization.')
|
||||||
|
}
|
||||||
|
|
||||||
|
await authzService.hasPermission({
|
||||||
|
user: { id: userId } as User,
|
||||||
|
permission: Permission.Read,
|
||||||
|
type: ResourceType.Asset,
|
||||||
|
id: assetId,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
let asset = await prisma.asset.findUnique({
|
let asset = await prisma.asset.findUnique({
|
||||||
where: { id: assetId },
|
where: { id: assetId },
|
||||||
|
|||||||
@@ -27,9 +27,6 @@ describe('Agent Autofill Workflow', () => {
|
|||||||
_activityName: 'updateTaskStatusActivity',
|
_activityName: 'updateTaskStatusActivity',
|
||||||
}),
|
}),
|
||||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
|
||||||
_activityName: 'extractAiMetadataActivity',
|
|
||||||
}),
|
|
||||||
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
|
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
|
||||||
_activityName: 'getProjectAutofillFieldsActivity',
|
_activityName: 'getProjectAutofillFieldsActivity',
|
||||||
}),
|
}),
|
||||||
@@ -46,35 +43,23 @@ describe('Agent Autofill Workflow', () => {
|
|||||||
}),
|
}),
|
||||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
|
||||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
|
||||||
}),
|
|
||||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||||
_activityName: 'getAgentWorkerQueueActivity',
|
_activityName: 'getAgentWorkerQueueActivity',
|
||||||
}),
|
}),
|
||||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
|
||||||
_activityName: 'downloadMediaToTmpActivity',
|
|
||||||
}),
|
|
||||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
|
|
||||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||||
mockActivities.getAssetActivity.mockResolvedValue({
|
mockActivities.getAssetActivity.mockResolvedValue({
|
||||||
id: 'a1',
|
id: 'a1',
|
||||||
|
name: 'test.png',
|
||||||
projectId: 'p1',
|
projectId: 'p1',
|
||||||
storageKey: { key: 'asset-key' },
|
storageKey: { key: 'asset-key' },
|
||||||
project: { id: 'p1', teamId: 't1' },
|
project: { id: 'p1', teamId: 't1' },
|
||||||
mediaType: 'image/png',
|
mediaType: 'image/png',
|
||||||
media: { proxyType: 'image' },
|
media: { proxyType: 'image', duration: 10 },
|
||||||
})
|
})
|
||||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
|
||||||
filePath: '/tmp/test.png',
|
|
||||||
tmpDir: '/tmp/test-dir',
|
|
||||||
})
|
|
||||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['/tmp/test-dir/1.webp'])
|
|
||||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
||||||
{ key: 'title', config: { name: 'Title', type: 'text' }, description: 'The title' },
|
{ key: 'title', config: { name: 'Title', type: 'text' }, description: 'The title' },
|
||||||
])
|
])
|
||||||
@@ -110,7 +95,6 @@ describe('Agent Autofill Workflow', () => {
|
|||||||
|
|
||||||
// Verify queue discovery
|
// Verify queue discovery
|
||||||
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
||||||
expect(mockActivities.getTranscodeWorkerQueueActivity).toHaveBeenCalled()
|
|
||||||
|
|
||||||
// Verify task processing status
|
// Verify task processing status
|
||||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||||
@@ -129,23 +113,21 @@ describe('Agent Autofill Workflow', () => {
|
|||||||
agentId: 'agent-1',
|
agentId: 'agent-1',
|
||||||
})
|
})
|
||||||
|
|
||||||
// Verify extraction and fields fetched
|
// Verify fields and context fetched
|
||||||
expect(mockActivities.extractAiMetadataActivity).toHaveBeenCalledWith({
|
|
||||||
assetKey: 'asset-key',
|
|
||||||
type: 'autofill',
|
|
||||||
isImage: true,
|
|
||||||
})
|
|
||||||
expect(mockActivities.getProjectAutofillFieldsActivity).toHaveBeenCalledWith('p1')
|
expect(mockActivities.getProjectAutofillFieldsActivity).toHaveBeenCalledWith('p1')
|
||||||
expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalledWith({
|
expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalledWith({
|
||||||
teamId: 't1',
|
teamId: 't1',
|
||||||
})
|
})
|
||||||
|
|
||||||
// Verify AI autofill called with mapped fields
|
// Verify AI autofill called with asset details and mapped fields
|
||||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith({
|
expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith({
|
||||||
teamId: 't1',
|
teamId: 't1',
|
||||||
assetId: 'a1',
|
assetId: 'a1',
|
||||||
|
assetName: 'test.png',
|
||||||
|
mediaType: 'image/png',
|
||||||
|
duration: 10,
|
||||||
|
pageCount: undefined,
|
||||||
projectId: 'p1',
|
projectId: 'p1',
|
||||||
images: ['/tmp/test-dir/1.webp'],
|
|
||||||
fields: [
|
fields: [
|
||||||
{
|
{
|
||||||
id: 'title',
|
id: 'title',
|
||||||
@@ -189,31 +171,35 @@ describe('Agent Autofill Workflow', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should complete early if no image files could be extracted', async () => {
|
it('should pass pageCount for PDF assets to autofillAiActivity', async () => {
|
||||||
mockActivities.extractAiMetadataActivity.mockResolvedValue([])
|
mockActivities.getAssetActivity.mockResolvedValue({
|
||||||
|
id: 'a2',
|
||||||
|
name: 'document.pdf',
|
||||||
|
projectId: 'p1',
|
||||||
|
project: { id: 'p1', teamId: 't1' },
|
||||||
|
mediaType: 'application/pdf',
|
||||||
|
media: { metadata: { totalFrames: 15 } },
|
||||||
|
})
|
||||||
|
|
||||||
const task = await prisma.workflowTask.create({
|
const task = await prisma.workflowTask.create({
|
||||||
data: {
|
data: {
|
||||||
type: 'ai_metadata_autofill',
|
type: 'ai_metadata_autofill',
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
assetId: 'a1',
|
assetId: 'a2',
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
await agentAutofillMedia(task)
|
await agentAutofillMedia(task)
|
||||||
|
|
||||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith(
|
||||||
commentId: 'comment-placeholder-id',
|
expect.objectContaining({
|
||||||
message: 'Autofill completed: No images could be extracted for analysis.',
|
assetId: 'a2',
|
||||||
})
|
assetName: 'document.pdf',
|
||||||
|
mediaType: 'application/pdf',
|
||||||
expect(mockActivities.autofillAiActivity).not.toHaveBeenCalled()
|
pageCount: 15,
|
||||||
expect(mockActivities.updateAssetMetadataActivity).not.toHaveBeenCalled()
|
duration: undefined,
|
||||||
|
}),
|
||||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
)
|
||||||
taskId: task.id,
|
|
||||||
status: 'completed',
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should complete early if no autofill fields are defined in the project', async () => {
|
it('should complete early if no autofill fields are defined in the project', async () => {
|
||||||
@@ -243,7 +229,7 @@ describe('Agent Autofill Workflow', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should handle failures, update placeholder with error, set status to failed, and cleanup tmp directory', async () => {
|
it('should handle failures, update placeholder with error, and set status to failed', async () => {
|
||||||
mockActivities.getProjectAutofillFieldsActivity.mockRejectedValue(new Error('DB failure'))
|
mockActivities.getProjectAutofillFieldsActivity.mockRejectedValue(new Error('DB failure'))
|
||||||
|
|
||||||
const task = await prisma.workflowTask.create({
|
const task = await prisma.workflowTask.create({
|
||||||
@@ -270,32 +256,24 @@ describe('Agent Autofill Workflow', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should fail with non-retryable ApplicationFailure for unsupported audio files', async () => {
|
it('should fail with non-retryable ApplicationFailure when asset or project is not found', async () => {
|
||||||
mockActivities.getAssetActivity.mockResolvedValue({
|
mockActivities.getAssetActivity.mockResolvedValue(null)
|
||||||
id: 'a1',
|
|
||||||
storageKey: { key: 'asset-key' },
|
|
||||||
project: { id: 'p1', teamId: 't1' },
|
|
||||||
mediaType: 'audio/mp3',
|
|
||||||
media: { proxyType: 'audio' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const task = await prisma.workflowTask.create({
|
const task = await prisma.workflowTask.create({
|
||||||
data: {
|
data: {
|
||||||
type: 'ai_metadata_autofill',
|
type: 'ai_metadata_autofill',
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
assetId: 'a1',
|
assetId: 'a-missing',
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
await expect(agentAutofillMedia(task)).rejects.toThrow(
|
await expect(agentAutofillMedia(task)).rejects.toThrow('Asset or project not found')
|
||||||
'unsupported media type for autofill: audio/mp3',
|
|
||||||
)
|
|
||||||
|
|
||||||
// Verify task failed status
|
// Verify task failed status
|
||||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
status: 'failed',
|
status: 'failed',
|
||||||
output: { error: 'unsupported media type for autofill: audio/mp3' },
|
output: { error: 'Asset or project not found' },
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,18 +1,11 @@
|
|||||||
import type { WorkflowTask } from '@shumai/db'
|
import type { WorkflowTask } from '@shumai/db'
|
||||||
import {
|
import { executeActivity, getActivities, TaskQueueAgent } from '@shumai/workflow-core'
|
||||||
executeActivity,
|
|
||||||
getActivities,
|
|
||||||
TaskQueueAgent,
|
|
||||||
TaskQueueTranscode,
|
|
||||||
} from '@shumai/workflow-core'
|
|
||||||
import { ApplicationFailure } from '@temporalio/workflow'
|
import { ApplicationFailure } from '@temporalio/workflow'
|
||||||
import { getProxyType } from '@shumai/core/src/utils/mime'
|
|
||||||
|
|
||||||
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||||
const {
|
const {
|
||||||
updateTaskStatusActivity,
|
updateTaskStatusActivity,
|
||||||
getAssetActivity,
|
getAssetActivity,
|
||||||
extractAiMetadataActivity,
|
|
||||||
getProjectAutofillFieldsActivity,
|
getProjectAutofillFieldsActivity,
|
||||||
getAgentAutofillContextActivity,
|
getAgentAutofillContextActivity,
|
||||||
autofillAiActivity,
|
autofillAiActivity,
|
||||||
@@ -20,21 +13,15 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
updateAssetMetadataActivity,
|
updateAssetMetadataActivity,
|
||||||
createCommentActivity,
|
createCommentActivity,
|
||||||
updateCommentActivity,
|
updateCommentActivity,
|
||||||
getTranscodeWorkerQueueActivity,
|
|
||||||
getAgentWorkerQueueActivity,
|
getAgentWorkerQueueActivity,
|
||||||
} = getActivities()
|
} = getActivities()
|
||||||
|
|
||||||
let placeholderCommentId: string | undefined
|
let placeholderCommentId: string | undefined
|
||||||
let transcodeWorkerQueue: string
|
|
||||||
let agentWorkerQueue = ''
|
let agentWorkerQueue = ''
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 0. Discover queues
|
// 0. Discover queues
|
||||||
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||||
transcodeWorkerQueue = await executeActivity(
|
|
||||||
TaskQueueTranscode,
|
|
||||||
getTranscodeWorkerQueueActivity,
|
|
||||||
)
|
|
||||||
|
|
||||||
// Update status to processing
|
// Update status to processing
|
||||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||||
@@ -54,49 +41,13 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
|
|
||||||
// 1. Get Asset
|
// 1. Get Asset
|
||||||
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
|
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
|
||||||
const key = asset?.storageKey?.key
|
if (!asset || !asset.project) {
|
||||||
if (!asset || !asset.project || !key) {
|
|
||||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||||
}
|
}
|
||||||
const teamId = asset.project.teamId
|
const teamId = asset.project.teamId
|
||||||
const projectId = asset.project.id
|
const projectId = asset.project.id
|
||||||
|
|
||||||
// 2. Prepare Data (Images)
|
// 2. Get Project Autofill Fields
|
||||||
const proxyType =
|
|
||||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
|
||||||
getProxyType(asset.mediaType, asset.name)
|
|
||||||
const isImage = proxyType === 'image'
|
|
||||||
const isVideo = proxyType === 'video'
|
|
||||||
|
|
||||||
if (!isImage && !isVideo) {
|
|
||||||
throw ApplicationFailure.create({
|
|
||||||
message: `unsupported media type for autofill: ${asset.mediaType}`,
|
|
||||||
nonRetryable: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const generatedFiles = await executeActivity(transcodeWorkerQueue, extractAiMetadataActivity, {
|
|
||||||
assetKey: key,
|
|
||||||
type: 'autofill',
|
|
||||||
isImage,
|
|
||||||
})
|
|
||||||
|
|
||||||
if (generatedFiles.length === 0) {
|
|
||||||
// If no images could be extracted, we can't do much
|
|
||||||
if (placeholderCommentId) {
|
|
||||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
|
||||||
commentId: placeholderCommentId,
|
|
||||||
message: 'Autofill completed: No images could be extracted for analysis.',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
|
||||||
taskId: task.id,
|
|
||||||
status: 'completed',
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Get Project Autofill Fields
|
|
||||||
const fields = await executeActivity(
|
const fields = await executeActivity(
|
||||||
agentWorkerQueue,
|
agentWorkerQueue,
|
||||||
getProjectAutofillFieldsActivity,
|
getProjectAutofillFieldsActivity,
|
||||||
@@ -116,16 +67,28 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3b. Fetch Agent Context
|
// 3. Fetch Agent Context
|
||||||
const context = await executeActivity(agentWorkerQueue, getAgentAutofillContextActivity, {
|
const context = await executeActivity(agentWorkerQueue, getAgentAutofillContextActivity, {
|
||||||
teamId,
|
teamId,
|
||||||
})
|
})
|
||||||
|
|
||||||
// 4. Call AI Service
|
// 4. Call AI Service (inspects asset on demand via read_asset)
|
||||||
|
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
|
||||||
|
const duration = typeof mediaInfo?.duration === 'number' ? mediaInfo.duration : undefined
|
||||||
|
const pageCount =
|
||||||
|
typeof mediaInfo?.metadata?.totalFrames === 'number'
|
||||||
|
? mediaInfo.metadata.totalFrames
|
||||||
|
: typeof mediaInfo?.frames === 'number'
|
||||||
|
? mediaInfo.frames
|
||||||
|
: undefined
|
||||||
|
|
||||||
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
||||||
teamId,
|
teamId,
|
||||||
images: generatedFiles,
|
|
||||||
assetId: asset.id,
|
assetId: asset.id,
|
||||||
|
assetName: asset.name,
|
||||||
|
mediaType: asset.mediaType ?? undefined,
|
||||||
|
duration,
|
||||||
|
pageCount,
|
||||||
projectId: asset.projectId ?? undefined,
|
projectId: asset.projectId ?? undefined,
|
||||||
fields: fields.map(
|
fields: fields.map(
|
||||||
(f: { key: string; config: Record<string, unknown>; description?: string | null }) => ({
|
(f: { key: string; config: Record<string, unknown>; description?: string | null }) => ({
|
||||||
|
|||||||
@@ -35,12 +35,34 @@ describe.each(['local', 'temporal'] as const)(
|
|||||||
// Spy on the harness prompt method to intercept the LLM call while running real activities & tools
|
// Spy on the harness prompt method to intercept the LLM call while running real activities & tools
|
||||||
vi.spyOn(AgentHarness.prototype, 'prompt').mockImplementation(async function (
|
vi.spyOn(AgentHarness.prototype, 'prompt').mockImplementation(async function (
|
||||||
this: AgentHarness,
|
this: AgentHarness,
|
||||||
|
...args: unknown[]
|
||||||
) {
|
) {
|
||||||
// Find the real autofill_metadata tool configured on the harness
|
// Find the real tools configured on the harness
|
||||||
const tools = this.getTools()
|
const tools = this.getTools()
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Tool execution mock for E2E harness test
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Tool execution mock for E2E harness test
|
||||||
|
const readAssetTool = tools.find((t) => t.name === 'read_asset') as any
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Tool execution mock for E2E harness test
|
||||||
const autofillTool = tools.find((t) => t.name === 'autofill_metadata') as any
|
const autofillTool = tools.find((t) => t.name === 'autofill_metadata') as any
|
||||||
|
|
||||||
|
expect(readAssetTool).toBeDefined()
|
||||||
|
expect(autofillTool).toBeDefined()
|
||||||
|
|
||||||
|
const promptText = typeof args[0] === 'string' ? args[0] : ''
|
||||||
|
const assetIdMatch = promptText.match(/ID:\s*"([^"]+)"/)
|
||||||
|
|
||||||
|
if (readAssetTool && assetIdMatch) {
|
||||||
|
const assetId = assetIdMatch[1]
|
||||||
|
const readResult = await readAssetTool.execute(
|
||||||
|
'call-read-1',
|
||||||
|
{ assetId },
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
)
|
||||||
|
expect(readResult).toBeDefined()
|
||||||
|
expect(readResult.content).toBeDefined()
|
||||||
|
}
|
||||||
|
|
||||||
if (autofillTool) {
|
if (autofillTool) {
|
||||||
// Execute the real tool callback to perform the actual DB updates
|
// Execute the real tool callback to perform the actual DB updates
|
||||||
await autofillTool.execute(
|
await autofillTool.execute(
|
||||||
|
|||||||
@@ -1094,5 +1094,149 @@ describe('Transcode Activities', () => {
|
|||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
expect((task?.payload as any)?.agent?.agentId).toBe(autofillAgent.id)
|
expect((task?.payload as any)?.agent?.agentId).toBe(autofillAgent.id)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
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()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -932,16 +932,7 @@ export async function createAutofillTaskIfEnabledActivity(
|
|||||||
project: true,
|
project: true,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
if (!asset) {
|
if (!asset || (asset.type !== 'file' && asset.type !== 'version_stack') || asset.isDeleted) {
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const proxyType =
|
|
||||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
|
||||||
getProxyType(asset.mediaType, asset.name)
|
|
||||||
const isVideo = proxyType === 'video'
|
|
||||||
const isImage = proxyType === 'image'
|
|
||||||
if (!isVideo && !isImage) {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user