From 4a61e87a274a838f3efc31905c13fbe27b8dabaf Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Tue, 8 Sep 2026 14:52:37 +0800 Subject: [PATCH] fix(agent): restrict pageCount and duration recommendations to matching media types (#397) --- packages/agent/src/activities/agent.test.ts | 73 ++++++++++++++++ packages/agent/src/activities/agent.ts | 9 +- .../src/workflows/agent-autofill.test.ts | 84 ++++++++++++++++++- .../agent/src/workflows/agent-autofill.ts | 21 +++-- packages/core/src/s3/s3.ts | 6 +- 5 files changed, 183 insertions(+), 10 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index c823afc9..1980151b 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -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) => Promise + }> + } + 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, + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Mock AgentHarness instance for activity test + harness: mockHarness as unknown as AgentHarness, + } + }) + + 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', () => { diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index b6219eee..3ca19d7e 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -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".`, ) diff --git a/packages/agent/src/workflows/agent-autofill.test.ts b/packages/agent/src/workflows/agent-autofill.test.ts index 4ec99849..8d6f43a6 100644 --- a/packages/agent/src/workflows/agent-autofill.test.ts +++ b/packages/agent/src/workflows/agent-autofill.test.ts @@ -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, + }), + ) + }) }) diff --git a/packages/agent/src/workflows/agent-autofill.ts b/packages/agent/src/workflows/agent-autofill.ts index 0edfba0d..082cd1e3 100644 --- a/packages/agent/src/workflows/agent-autofill.ts +++ b/packages/agent/src/workflows/agent-autofill.ts @@ -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 { const { @@ -74,13 +75,21 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise { // 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, diff --git a/packages/core/src/s3/s3.ts b/packages/core/src/s3/s3.ts index 0a756cb8..7a4ae1ad 100644 --- a/packages/core/src/s3/s3.ts +++ b/packages/core/src/s3/s3.ts @@ -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 }