refactor(workflow): enforce strict nested type safety for WorkflowTaskPayload

This commit is contained in:
yiling
2026-05-28 09:48:05 +08:00
parent 911e369782
commit 11d2e89a48
18 changed files with 185 additions and 98 deletions
+22
View File
@@ -233,6 +233,28 @@ describe('Team API', () => {
- Generated Client: `src/generated/prisma` - Generated Client: `src/generated/prisma`
- Config: `prisma.config.ts` (Required for Prisma 7+) - Config: `prisma.config.ts` (Required for Prisma 7+)
### Strict JSON Typing
We use `prisma-json-types-generator` to enforce strict type-safety for Prisma `Json` columns, rather than typing them as generic `JsonValue`.
- **Defining Types**: In `prisma/schema.prisma`, annotate the JSON column with a triple-slash comment specifying the type name from `src/prisma-json-types.ts`:
```prisma
model WorkflowTask {
/// [WorkflowTaskPayload]
payload Json?
}
```
- **Declaring Types**: All typed JSON shapes must be defined in `src/prisma-json-types.ts` under the global `PrismaJson` namespace:
```typescript
declare global {
namespace PrismaJson {
export type WorkflowTaskPayload = Record<string, unknown> | TaskSpec | AiTaskPayload
}
}
```
- **Usage**: When accessing these columns on the Prisma client (e.g. `task.payload`), the field will automatically be typed as the declared shape (e.g., `PrismaJson.WorkflowTaskPayload | null`).
- **Accessing Properties**: When working with union types or custom structures in the JSON payload, use proper narrowing or type guards instead of casting to `any`. Direct `as any` casting should be avoided.
### Migration Workflow ### Migration Workflow
- Development: Use `bun --bun run prisma migrate dev` to create and apply migrations during development. - Development: Use `bun --bun run prisma migrate dev` to create and apply migrations during development.
+11 -3
View File
@@ -241,7 +241,11 @@ declare global {
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// Workflow Task Payload // Workflow Task Payload
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
export type WorkflowTaskPayload = Record<string, unknown> | TaskSpec | AiTaskPayload export interface WorkflowTaskPayload {
projectId: string
transcode?: TaskSpec
agent?: AgentTaskPayload
}
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// Task Spec & Payload // Task Spec & Payload
@@ -254,8 +258,12 @@ declare global {
poster?: boolean poster?: boolean
} }
export interface AiTaskPayload { export interface AgentTaskPayload {
projectId: string agentId?: string
userId?: string
sessionId?: string
userCommentId?: string
explicitMention?: boolean
} }
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
+28 -28
View File
@@ -856,10 +856,8 @@ describe('AssetService', () => {
where: { assetId: file.id, type: 'chat' }, where: { assetId: file.id, type: 'chat' },
}) })
expect(tasks.length).toBe(2) expect(tasks.length).toBe(2)
// eslint-disable-next-line @typescript-eslint/no-explicit-any expect(tasks.some((t) => t.payload?.agent?.agentId === agent.id)).toBe(true)
expect(tasks.some((t) => (t.payload as any).agentId === agent.id)).toBe(true) expect(tasks.some((t) => t.payload?.agent?.agentId === 'default')).toBe(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(tasks.some((t) => (t.payload as any).agentId === 'default')).toBe(true)
}) })
it('implements agent comment interaction rules (Rule 1, 2, 3)', async () => { it('implements agent comment interaction rules (Rule 1, 2, 3)', async () => {
@@ -902,14 +900,13 @@ describe('AssetService', () => {
}) })
const tasksRule1 = await prisma.workflowTask.findMany({ const tasksRule1 = await prisma.workflowTask.findMany({
where: { assetId: file.id, payload: { path: ['userCommentId'], equals: c1.id } }, where: { assetId: file.id, payload: { path: ['agent', 'userCommentId'], equals: c1.id } },
}) })
expect(tasksRule1.length).toBe(1) expect(tasksRule1.length).toBe(1)
// eslint-disable-next-line @typescript-eslint/no-explicit-any const p1 = tasksRule1[0].payload
const p1 = tasksRule1[0].payload as any expect(p1?.agent?.agentId).toBe(agent.id)
expect(p1.agentId).toBe(agent.id) expect(p1?.agent?.sessionId).toBeUndefined()
expect(p1.sessionId).toBeUndefined() expect(p1?.agent?.explicitMention).toBe(true)
expect(p1.explicitMention).toBe(true)
// Rule 2: user mentions agent in reply, and root is not an agent comment // Rule 2: user mentions agent in reply, and root is not an agent comment
const reply1 = await assetService.createComment({ const reply1 = await assetService.createComment({
@@ -921,14 +918,13 @@ describe('AssetService', () => {
}) })
const tasksRule2 = await prisma.workflowTask.findMany({ const tasksRule2 = await prisma.workflowTask.findMany({
where: { assetId: file.id, payload: { path: ['userCommentId'], equals: reply1.id } }, where: { assetId: file.id, payload: { path: ['agent', 'userCommentId'], equals: reply1.id } },
}) })
expect(tasksRule2.length).toBe(1) expect(tasksRule2.length).toBe(1)
// eslint-disable-next-line @typescript-eslint/no-explicit-any const p2 = tasksRule2[0].payload
const p2 = tasksRule2[0].payload as any expect(p2?.agent?.agentId).toBe(agent.id)
expect(p2.agentId).toBe(agent.id) expect(p2?.agent?.sessionId).toBeUndefined()
expect(p2.sessionId).toBeUndefined() expect(p2?.agent?.explicitMention).toBe(true)
expect(p2.explicitMention).toBe(true)
// Create a root user comment // Create a root user comment
const userRoot = await prisma.assetComment.create({ const userRoot = await prisma.assetComment.create({
@@ -975,14 +971,16 @@ describe('AssetService', () => {
expect(dbReply3a?.replyToId).toBe(userRoot.id) expect(dbReply3a?.replyToId).toBe(userRoot.id)
const tasksRule3a = await prisma.workflowTask.findMany({ const tasksRule3a = await prisma.workflowTask.findMany({
where: { assetId: file.id, payload: { path: ['userCommentId'], equals: reply3a.id } }, where: {
assetId: file.id,
payload: { path: ['agent', 'userCommentId'], equals: reply3a.id },
},
}) })
expect(tasksRule3a.length).toBe(1) expect(tasksRule3a.length).toBe(1)
// eslint-disable-next-line @typescript-eslint/no-explicit-any const p3a = tasksRule3a[0].payload
const p3a = tasksRule3a[0].payload as any expect(p3a?.agent?.agentId).toBe(botUser.id)
expect(p3a.agentId).toBe(botUser.id) expect(p3a?.agent?.sessionId).toBe('test-session-rule3')
expect(p3a.sessionId).toBe('test-session-rule3') expect(p3a?.agent?.explicitMention).toBe(false)
expect(p3a.explicitMention).toBe(false)
// Rule 3b: any user creates a reply directly to the agent comment, explicitly mentions agent // Rule 3b: any user creates a reply directly to the agent comment, explicitly mentions agent
const reply3b = await assetService.createComment({ const reply3b = await assetService.createComment({
@@ -1000,14 +998,16 @@ describe('AssetService', () => {
expect(dbReply3b?.replyToId).toBe(userRoot.id) expect(dbReply3b?.replyToId).toBe(userRoot.id)
const tasksRule3b = await prisma.workflowTask.findMany({ const tasksRule3b = await prisma.workflowTask.findMany({
where: { assetId: file.id, payload: { path: ['userCommentId'], equals: reply3b.id } }, where: {
assetId: file.id,
payload: { path: ['agent', 'userCommentId'], equals: reply3b.id },
},
}) })
expect(tasksRule3b.length).toBe(1) expect(tasksRule3b.length).toBe(1)
// eslint-disable-next-line @typescript-eslint/no-explicit-any const p3b = tasksRule3b[0].payload
const p3b = tasksRule3b[0].payload as any expect(p3b?.agent?.agentId).toBe(botUser.id)
expect(p3b.agentId).toBe(botUser.id) expect(p3b?.agent?.sessionId).toBe('test-session-rule3')
expect(p3b.sessionId).toBe('test-session-rule3') expect(p3b?.agent?.explicitMention).toBe(true)
expect(p3b.explicitMention).toBe(true)
}) })
it('updates asset order correctly', async () => { it('updates asset order correctly', async () => {
+11 -7
View File
@@ -1274,11 +1274,13 @@ export class AssetService {
teamId: a.project.team.id, teamId: a.project.team.id,
projectId: a.project.id, projectId: a.project.id,
payload: { payload: {
userCommentId: comment.id,
agentId: rootAgentId,
projectId: a.project.id, projectId: a.project.id,
sessionId: rootSessionId || undefined, agent: {
explicitMention, userCommentId: comment.id,
agentId: rootAgentId,
sessionId: rootSessionId || undefined,
explicitMention,
},
}, },
}, },
}) })
@@ -1307,10 +1309,12 @@ export class AssetService {
teamId: a.project.team.id, teamId: a.project.team.id,
projectId: a.project.id, projectId: a.project.id,
payload: { payload: {
userCommentId: comment.id,
agentId: agentId,
projectId: a.project.id, projectId: a.project.id,
explicitMention: true, agent: {
userCommentId: comment.id,
agentId: agentId,
explicitMention: true,
},
}, },
}, },
}) })
+4 -5
View File
@@ -1,15 +1,14 @@
import { prisma } from '@/db' import { prisma } from '@/db'
import type { Prisma } from '@/generated/prisma/client.ts'
import { systemFields } from './system_fields'
import { ulid } from 'ulid'
import { import {
CreateFieldRequest, CreateFieldRequest,
UpdateFieldRequest,
ProjectFieldOrder, ProjectFieldOrder,
UpdateAssetMetadataRequest, UpdateAssetMetadataRequest,
UpdateFieldRequest,
} from '@/dtos/metadata' } from '@/dtos/metadata'
import '@/prisma-json-types' import type { Prisma } from '@/generated/prisma/client.ts'
import { ulid } from 'ulid'
import { assetService } from '../asset/asset' import { assetService } from '../asset/asset'
import { systemFields } from './system_fields'
export class MetadataService { export class MetadataService {
constructor(private client: typeof prisma = prisma) {} constructor(private client: typeof prisma = prisma) {}
+11 -5
View File
@@ -125,9 +125,12 @@ describe('UploadService', () => {
}) })
expect(workflowTask).toBeDefined() expect(workflowTask).toBeDefined()
expect(workflowTask?.payload).toEqual({ expect(workflowTask?.payload).toEqual({
videoStrategy: 'single', projectId: projectId,
sprite: true, transcode: {
poster: true, videoStrategy: 'single',
sprite: true,
poster: true,
},
}) })
}) })
@@ -159,8 +162,11 @@ describe('UploadService', () => {
}) })
expect(workflowTask).toBeDefined() expect(workflowTask).toBeDefined()
expect(workflowTask?.payload).toEqual({ expect(workflowTask?.payload).toEqual({
imageStrategy: 'single', projectId: projectId,
thumbnail: true, transcode: {
imageStrategy: 'single',
thumbnail: true,
},
}) })
}) })
+12 -3
View File
@@ -254,7 +254,10 @@ export class UploadService {
status: WorkflowTaskStatus.pending, status: WorkflowTaskStatus.pending,
teamId: team.id, teamId: team.id,
projectId: asset.projectId, projectId: asset.projectId,
payload: { projectId: asset.projectId, agentId: autofillAgent.id }, payload: {
projectId: asset.projectId!,
agent: { agentId: autofillAgent.id },
},
}, },
}) })
} }
@@ -275,7 +278,10 @@ export class UploadService {
status: WorkflowTaskStatus.pending, status: WorkflowTaskStatus.pending,
teamId: team.id, teamId: team.id,
projectId: asset.projectId, projectId: asset.projectId,
payload: { projectId: asset.projectId, agentId: transcriptionAgent.id }, payload: {
projectId: asset.projectId!,
agent: { agentId: transcriptionAgent.id },
},
}, },
}) })
} }
@@ -298,7 +304,10 @@ export class UploadService {
status: WorkflowTaskStatus.pending, status: WorkflowTaskStatus.pending,
teamId: team.id, teamId: team.id,
projectId: asset.projectId, projectId: asset.projectId,
payload: { projectId: asset.projectId, agentId: embeddingAgent.id }, payload: {
projectId: asset.projectId!,
agent: { agentId: embeddingAgent.id },
},
}, },
}) })
} }
+3 -3
View File
@@ -216,7 +216,7 @@ describe('TranscodeService', () => {
}) })
it('should create transcode tasks correctly', async () => { it('should create transcode tasks correctly', async () => {
const task = (await transcodeService.createVideoTranscodeTask('asset-123', { const task = (await transcodeService.createVideoTranscodeTask('asset-123', 'proj-123', {
videoStrategy: 'single', videoStrategy: 'single',
thumbnail: true, thumbnail: true,
})) as WorkflowTask })) as WorkflowTask
@@ -224,7 +224,7 @@ describe('TranscodeService', () => {
expect(task.assetId).toBe('asset-123') expect(task.assetId).toBe('asset-123')
expect(task.type).toBe('transcode') expect(task.type).toBe('transcode')
expect(task.status).toBe('pending') expect(task.status).toBe('pending')
// eslint-disable-next-line @typescript-eslint/no-explicit-any expect(task.payload?.projectId).toBe('proj-123')
expect((task.payload as any).videoStrategy).toBe('single') expect(task.payload?.transcode?.videoStrategy).toBe('single')
}) })
}) })
+12 -6
View File
@@ -400,26 +400,32 @@ export class TranscodeService {
// --- Task Creation Helpers --- // --- Task Creation Helpers ---
async createVideoTranscodeTask(assetId: string, spec: PrismaJson.TaskSpec) { async createVideoTranscodeTask(assetId: string, projectId: string, spec: PrismaJson.TaskSpec) {
return this.prismaClient.workflowTask.create({ return this.prismaClient.workflowTask.create({
data: { data: {
assetId, assetId,
projectId,
type: WorkflowTaskType.transcode, type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending, status: WorkflowTaskStatus.pending,
// eslint-disable-next-line @typescript-eslint/no-explicit-any payload: {
payload: spec as any, projectId,
transcode: spec,
},
}, },
}) })
} }
async createImageTranscodeTask(assetId: string, spec: PrismaJson.TaskSpec) { async createImageTranscodeTask(assetId: string, projectId: string, spec: PrismaJson.TaskSpec) {
return this.prismaClient.workflowTask.create({ return this.prismaClient.workflowTask.create({
data: { data: {
assetId, assetId,
projectId,
type: WorkflowTaskType.transcode, type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending, status: WorkflowTaskStatus.pending,
// eslint-disable-next-line @typescript-eslint/no-explicit-any payload: {
payload: spec as any, projectId,
transcode: spec,
},
}, },
}) })
} }
+8 -2
View File
@@ -40,7 +40,10 @@ export class VideoTranscoder {
projectId: this.projectId, projectId: this.projectId,
type: WorkflowTaskType.transcode, type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending, status: WorkflowTaskStatus.pending,
payload: this.spec, payload: {
projectId: this.projectId,
transcode: this.spec,
},
}, },
}) })
return task.id return task.id
@@ -75,7 +78,10 @@ export class ImageTranscoder {
projectId: this.projectId, projectId: this.projectId,
type: WorkflowTaskType.transcode, type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending, status: WorkflowTaskStatus.pending,
payload: this.spec, payload: {
projectId: this.projectId,
transcode: this.spec,
},
}, },
}) })
return task.id return task.id
+8 -3
View File
@@ -74,8 +74,11 @@ describe('Transcode Workflow', () => {
status: WorkflowTaskStatus.pending, status: WorkflowTaskStatus.pending,
output: null, output: null,
payload: { payload: {
videoStrategy: 'single', projectId: 'proj-1',
thumbnail: true, transcode: {
videoStrategy: 'single',
thumbnail: true,
},
}, },
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
@@ -138,7 +141,9 @@ describe('Transcode Workflow', () => {
type: WorkflowTaskType.transcode, type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending, status: WorkflowTaskStatus.pending,
output: null, output: null,
payload: {}, payload: {
projectId: 'proj-1',
},
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
heartbeat: null, heartbeat: null,
+13 -3
View File
@@ -55,11 +55,21 @@ describe('Agent Autofill Workflow', () => {
} }
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' }) mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', storageKey: { key: 'asset-key' }, project: { id: 'p1', teamId: 't1' }, mediaType: 'image/png' }) mockActivities.getAssetActivity.mockResolvedValue({
id: 'a1',
storageKey: { key: 'asset-key' },
project: { id: 'p1', teamId: 't1' },
mediaType: 'image/png',
})
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue') mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({ filePath: '/tmp/test.png', tmpDir: '/tmp' }) mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/test.png',
tmpDir: '/tmp',
})
mockActivities.extractAiMetadataActivity.mockResolvedValue(['/tmp/1.webp']) mockActivities.extractAiMetadataActivity.mockResolvedValue(['/tmp/1.webp'])
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([{ id: 'f1', config: { name: 'F1', type: 'text' } }]) mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
{ id: 'f1', config: { name: 'F1', type: 'text' } },
])
mockActivities.getAgentAutofillContextActivity.mockResolvedValue({ agent: { id: 'b1' } }) mockActivities.getAgentAutofillContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.autofillAiActivity.mockResolvedValue({ mockActivities.autofillAiActivity.mockResolvedValue({
+3 -3
View File
@@ -37,12 +37,12 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
}) })
// 0. Create Placeholder Comment // 0. Create Placeholder Comment
const payload = task.payload as Record<string, unknown> const payload = task.payload
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, { const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId, assetId: task.assetId,
message: '__AUTOFILL__', message: '__AUTOFILL__',
sessionId: (payload?.session_id as string) || task.id, sessionId: payload?.agent?.sessionId || task.id,
agentId: (payload?.agentId as string) || 'default', agentId: payload?.agent?.agentId || 'default',
}) })
placeholderCommentId = placeholder.id placeholderCommentId = placeholder.id
+9 -2
View File
@@ -43,7 +43,11 @@ describe('Agent Chat Workflow', () => {
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }), deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
} }
mockActivities.getCommentActivity.mockResolvedValue({ id: 'c1', message: 'hello', replyToId: null }) mockActivities.getCommentActivity.mockResolvedValue({
id: 'c1',
message: 'hello',
replyToId: null,
})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' }) mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', project: { teamId: 't1' } }) mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', project: { teamId: 't1' } })
mockActivities.initializeAgentSessionActivity.mockResolvedValue('session-123') mockActivities.initializeAgentSessionActivity.mockResolvedValue('session-123')
@@ -67,7 +71,10 @@ describe('Agent Chat Workflow', () => {
type: 'chat', type: 'chat',
status: 'pending', status: 'pending',
assetId: 'a1', assetId: 'a1',
payload: { userCommentId: 'c1', agentId: 'b1' }, payload: {
projectId: 'p1',
agent: { userCommentId: 'c1', agentId: 'b1' },
},
}, },
}) })
+19 -18
View File
@@ -30,13 +30,16 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
status: 'processing', status: 'processing',
}) })
// eslint-disable-next-line @typescript-eslint/no-explicit-any const payload = task.payload
const payload = task.payload as any if (!payload) throw new Error('Task payload is missing')
let sessionId = payload?.sessionId || payload?.session_id const agentId = payload.agent?.agentId
if (!agentId) throw new Error('agentId missing in payload')
let sessionId = payload.agent?.sessionId
// 1. Get User Comment // 1. Get User Comment
const userCommentId = payload?.userCommentId const userCommentId = payload.agent?.userCommentId
if (!userCommentId) throw new Error('userCommentId missing in payload') if (!userCommentId) throw new Error('userCommentId missing in payload')
const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId) const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId)
if (!userComment) throw new Error('User comment not found') if (!userComment) throw new Error('User comment not found')
@@ -46,7 +49,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
assetId: task.assetId, assetId: task.assetId,
message: '__CHAT__', message: '__CHAT__',
sessionId: sessionId || 'pending', sessionId: sessionId || 'pending',
agentId: payload?.agentId, agentId: agentId,
replyToId: userComment.replyToId ?? userComment.id, replyToId: userComment.replyToId ?? userComment.id,
}) })
placeholderCommentId = placeholder.id placeholderCommentId = placeholder.id
@@ -62,26 +65,24 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
if (!sessionId) { if (!sessionId) {
sessionId = await executeActivity(TaskQueueDb, initializeAgentSessionActivity, { sessionId = await executeActivity(TaskQueueDb, initializeAgentSessionActivity, {
teamId, teamId,
agentId: payload.agentId, agentId: agentId,
userCommentId, userCommentId,
userId: payload.userId, userId: payload.agent?.userId,
}) })
} }
// 4b. Fetch Agent Context (Database Activity on db_queue) // 4b. Fetch Agent Context (Database Activity on db_queue)
const context = await executeActivity(TaskQueueDb, getAgentChatContextActivity, { const context = await executeActivity(TaskQueueDb, getAgentChatContextActivity, {
teamId, teamId,
agentId: payload.agentId, agentId: agentId,
}) })
// 5. Prepare Images (Attachments only) // 5. Prepare Images (Attachments only)
const attachmentImageUrls: string[] = [] const attachmentImageUrls: string[] = []
// eslint-disable-next-line @typescript-eslint/no-explicit-any if (userComment?.attachments) {
const userCommentWithAttachments = userComment as any for (const att of userComment.attachments) {
if (userCommentWithAttachments?.attachments) { if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) {
for (const att of userCommentWithAttachments.attachments) { attachmentImageUrls.push(att.asset.storageKey.key)
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.key) {
attachmentImageUrls.push(att.asset.key)
} }
} }
} }
@@ -94,7 +95,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
instruction += `\n\nIf you need to view the asset's media content (frames/images/video), call the 'analyze_asset_media' tool by passing the appropriate 'key' from the Asset Media Info above. Choose the most suitable format based on your capabilities and the user's request (e.g., use a poster or sprite for quick visual checks, or a transcode/raw file for detailed analysis).` instruction += `\n\nIf you need to view the asset's media content (frames/images/video), call the 'analyze_asset_media' tool by passing the appropriate 'key' from the Asset Media Info above. Choose the most suitable format based on your capabilities and the user's request (e.g., use a poster or sprite for quick visual checks, or a transcode/raw file for detailed analysis).`
if (payload?.explicitMention) { if (payload.agent?.explicitMention) {
instruction += `\n\nThe user explicitly mentioned you in their message. You MUST reply to this message.` instruction += `\n\nThe user explicitly mentioned you in their message. You MUST reply to this message.`
} else { } else {
instruction += `\n\nThe user did not explicitly mention you, but is replying in a thread where you are the participant. Let's decide if you should reply or not. If the user is not directly addressing you or doesn't need a response from you, you may choose to not reply. To choose not to reply, respond with exactly and only the text: __NO_REPLY__.` instruction += `\n\nThe user did not explicitly mention you, but is replying in a thread where you are the participant. Let's decide if you should reply or not. If the user is not directly addressing you or doesn't need a response from you, you may choose to not reply. To choose not to reply, respond with exactly and only the text: __NO_REPLY__.`
@@ -112,15 +113,15 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, { const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
teamId, teamId,
agentId: payload.agentId, agentId: agentId,
message: userComment.message || '', message: userComment.message || '',
imageUrls: attachmentImageUrls, imageUrls: attachmentImageUrls,
projectId: payload.projectId, projectId: payload.projectId,
folderId, folderId,
agentsInstruction: instruction, agentsInstruction: instruction,
sessionId, sessionId,
userId: payload.userId, userId: payload.agent?.userId,
explicitMention: payload?.explicitMention, explicitMention: payload.agent?.explicitMention,
context, context,
}) })
@@ -43,7 +43,11 @@ describe('Agent Embedding Workflow', () => {
} }
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' }) mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.getEmbeddingContextActivity.mockResolvedValue({ agent: { id: 'b1' }, asset: { id: 'a1' }, dbProvider: { name: 'google' } }) mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: { id: 'a1' },
dbProvider: { name: 'google' },
})
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.generateEmbeddingActivity.mockResolvedValue({ mockActivities.generateEmbeddingActivity.mockResolvedValue({
embeddings: [{ embedding: [0.1, 0.2] }], embeddings: [{ embedding: [0.1, 0.2] }],
+3 -3
View File
@@ -23,12 +23,12 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
}) })
// 0. Create Placeholder Comment // 0. Create Placeholder Comment
const payload = task.payload as Record<string, unknown> const payload = task.payload
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, { const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId, assetId: task.assetId,
message: '__EMBEDDING__', message: '__EMBEDDING__',
sessionId: (payload?.session_id as string) || task.id, sessionId: payload?.agent?.sessionId || task.id,
agentId: (payload?.agentId as string) || 'default', agentId: payload?.agent?.agentId || 'default',
}) })
placeholderCommentId = placeholder.id placeholderCommentId = placeholder.id
+3 -3
View File
@@ -31,12 +31,12 @@ export async function aiTranscriptionMedia(task: WorkflowTask): Promise<void> {
}) })
// 0. Create Placeholder Comment // 0. Create Placeholder Comment
const payload = task.payload as Record<string, unknown> const payload = task.payload
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, { const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId, assetId: task.assetId,
message: '__TRANSCRIPTION__', message: '__TRANSCRIPTION__',
sessionId: (payload?.session_id as string) || task.id, sessionId: payload?.agent?.sessionId || task.id,
agentId: (payload?.agentId as string) || 'default', agentId: payload?.agent?.agentId || 'default',
}) })
placeholderCommentId = placeholder.id placeholderCommentId = placeholder.id