mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 19:27:14 +00:00
fix(agent): restrict pageCount and duration recommendations to matching media types (#397)
This commit is contained in:
@@ -590,6 +590,79 @@ describe('Agent Activities', () => {
|
||||
'Document pages: 15. Recommended inspection: call read_asset with docConfig: { mode: "pages", startPage: 1, endPage: 15 } or mode: "text".',
|
||||
)
|
||||
})
|
||||
|
||||
it('should ignore inappropriate mediaType recommendations in autofillAiActivity', 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) => {
|
||||
const params = config as {
|
||||
customTools: Array<{
|
||||
name: string
|
||||
execute: (id: string, args: Record<string, unknown>) => Promise<unknown>
|
||||
}>
|
||||
}
|
||||
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', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
|
||||
dbProviders: [],
|
||||
teamSkills: [],
|
||||
allowedDomains: [],
|
||||
} as unknown as AgentExecutionContext
|
||||
|
||||
// For a video asset, pageCount should NOT produce Document pages recommendation
|
||||
await autofillAiActivity({
|
||||
teamId: 't1',
|
||||
assetId: 'video-1',
|
||||
assetName: 'video.mp4',
|
||||
mediaType: 'video/mp4',
|
||||
duration: 10.1,
|
||||
pageCount: 300,
|
||||
images: [],
|
||||
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
|
||||
context,
|
||||
})
|
||||
|
||||
const videoPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? ''
|
||||
expect(videoPrompt).toContain('Video duration: 10.1s')
|
||||
expect(videoPrompt).not.toContain('Document pages')
|
||||
|
||||
// For a PDF asset, duration should NOT produce Video duration recommendation
|
||||
await autofillAiActivity({
|
||||
teamId: 't1',
|
||||
assetId: 'pdf-2',
|
||||
assetName: 'document.pdf',
|
||||
mediaType: 'application/pdf',
|
||||
duration: 10.1,
|
||||
pageCount: 50,
|
||||
images: [],
|
||||
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
|
||||
context,
|
||||
})
|
||||
|
||||
const pdfPrompt = mockHarness.prompt.mock.calls[1]?.[0] ?? ''
|
||||
expect(pdfPrompt).toContain('Document pages: 50')
|
||||
expect(pdfPrompt).not.toContain('Video duration')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Agent Database Activities Integration', () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
|
||||
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
|
||||
import { quotaService, QuotaExceededError } from '@shumai/core/src/quota/quota-service'
|
||||
import { getProxyType } from '@shumai/core/src/utils/mime'
|
||||
import {
|
||||
UpdateAssetMetadataRequest,
|
||||
type ShumaiMessageContext,
|
||||
@@ -560,12 +561,16 @@ export async function autofillAiActivity(params: AutofillAiParams) {
|
||||
`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) {
|
||||
const proxyType = getProxyType(params.mediaType, params.assetName)
|
||||
const isVideoOrAudio = proxyType === 'video' || proxyType === 'audio'
|
||||
const isPdf = proxyType === 'pdf'
|
||||
|
||||
if (params.duration !== undefined && params.duration > 0 && (!proxyType || isVideoOrAudio)) {
|
||||
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) {
|
||||
if (params.pageCount !== undefined && params.pageCount > 0 && (!proxyType || isPdf)) {
|
||||
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".`,
|
||||
)
|
||||
|
||||
@@ -125,7 +125,7 @@ describe('Agent Autofill Workflow', () => {
|
||||
assetId: 'a1',
|
||||
assetName: 'test.png',
|
||||
mediaType: 'image/png',
|
||||
duration: 10,
|
||||
duration: undefined,
|
||||
pageCount: undefined,
|
||||
projectId: 'p1',
|
||||
fields: [
|
||||
@@ -276,4 +276,86 @@ describe('Agent Autofill Workflow', () => {
|
||||
output: { error: 'Asset or project not found' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should not pass pageCount for video assets when calling autofillAiActivity', async () => {
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'v1',
|
||||
name: 'test.mp4',
|
||||
projectId: 'p1',
|
||||
storageKey: { key: 'asset-video-key' },
|
||||
project: { id: 'p1', teamId: 't1' },
|
||||
mediaType: 'video/mp4',
|
||||
media: {
|
||||
proxyType: 'video',
|
||||
duration: 10.1,
|
||||
frames: 300,
|
||||
metadata: { totalFrames: 300 },
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_metadata_autofill',
|
||||
status: 'pending',
|
||||
assetId: 'v1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { sessionId: 's1', agentId: 'agent-1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'v1',
|
||||
assetName: 'test.mp4',
|
||||
mediaType: 'video/mp4',
|
||||
duration: 10.1,
|
||||
pageCount: undefined,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should pass pageCount and no duration for pdf assets when calling autofillAiActivity', async () => {
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'doc1',
|
||||
name: 'test.pdf',
|
||||
projectId: 'p1',
|
||||
storageKey: { key: 'asset-doc-key' },
|
||||
project: { id: 'p1', teamId: 't1' },
|
||||
mediaType: 'application/pdf',
|
||||
media: {
|
||||
proxyType: 'pdf',
|
||||
duration: 0,
|
||||
frames: 25,
|
||||
metadata: { totalFrames: 25 },
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_metadata_autofill',
|
||||
status: 'pending',
|
||||
assetId: 'doc1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { sessionId: 's1', agentId: 'agent-1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'doc1',
|
||||
assetName: 'test.pdf',
|
||||
mediaType: 'application/pdf',
|
||||
duration: undefined,
|
||||
pageCount: 25,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { executeActivity, getActivities, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import { getProxyType } from '@shumai/core/src/utils/mime'
|
||||
|
||||
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
@@ -74,13 +75,21 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 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 proxyType = mediaInfo?.proxyType || getProxyType(asset.mediaType, asset.name) || undefined
|
||||
|
||||
const duration =
|
||||
(proxyType === 'video' || proxyType === 'audio') && typeof mediaInfo?.duration === 'number'
|
||||
? mediaInfo.duration
|
||||
: undefined
|
||||
|
||||
const pageCount =
|
||||
typeof mediaInfo?.metadata?.totalFrames === 'number'
|
||||
? mediaInfo.metadata.totalFrames
|
||||
: typeof mediaInfo?.frames === 'number'
|
||||
? mediaInfo.frames
|
||||
: undefined
|
||||
proxyType === 'pdf'
|
||||
? typeof mediaInfo?.metadata?.totalFrames === 'number'
|
||||
? mediaInfo.metadata.totalFrames
|
||||
: typeof mediaInfo?.frames === 'number'
|
||||
? mediaInfo.frames
|
||||
: undefined
|
||||
: undefined
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
||||
teamId,
|
||||
|
||||
@@ -232,9 +232,13 @@ export class S3StorageService implements S3Service {
|
||||
return
|
||||
}
|
||||
|
||||
const writeStream = fs.createWriteStream(filePath)
|
||||
try {
|
||||
await pipeline(res.Body as unknown as NodeJS.ReadableStream, fs.createWriteStream(filePath))
|
||||
await pipeline(res.Body as unknown as NodeJS.ReadableStream, writeStream)
|
||||
} catch (err) {
|
||||
if (!writeStream.closed) {
|
||||
await new Promise((resolve) => writeStream.once('close', resolve))
|
||||
}
|
||||
await fs.promises.unlink(filePath).catch(() => {})
|
||||
throw err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user