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`
- 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
- 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
// ----------------------------------------------------------------------
export type WorkflowTaskPayload = Record<string, unknown> | TaskSpec | AiTaskPayload
export interface WorkflowTaskPayload {
projectId: string
transcode?: TaskSpec
agent?: AgentTaskPayload
}
// ----------------------------------------------------------------------
// Task Spec & Payload
@@ -254,8 +258,12 @@ declare global {
poster?: boolean
}
export interface AiTaskPayload {
projectId: string
export interface AgentTaskPayload {
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' },
})
expect(tasks.length).toBe(2)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(tasks.some((t) => (t.payload as any).agentId === agent.id)).toBe(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(tasks.some((t) => (t.payload as any).agentId === 'default')).toBe(true)
expect(tasks.some((t) => t.payload?.agent?.agentId === agent.id)).toBe(true)
expect(tasks.some((t) => t.payload?.agent?.agentId === 'default')).toBe(true)
})
it('implements agent comment interaction rules (Rule 1, 2, 3)', async () => {
@@ -902,14 +900,13 @@ describe('AssetService', () => {
})
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)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const p1 = tasksRule1[0].payload as any
expect(p1.agentId).toBe(agent.id)
expect(p1.sessionId).toBeUndefined()
expect(p1.explicitMention).toBe(true)
const p1 = tasksRule1[0].payload
expect(p1?.agent?.agentId).toBe(agent.id)
expect(p1?.agent?.sessionId).toBeUndefined()
expect(p1?.agent?.explicitMention).toBe(true)
// Rule 2: user mentions agent in reply, and root is not an agent comment
const reply1 = await assetService.createComment({
@@ -921,14 +918,13 @@ describe('AssetService', () => {
})
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)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const p2 = tasksRule2[0].payload as any
expect(p2.agentId).toBe(agent.id)
expect(p2.sessionId).toBeUndefined()
expect(p2.explicitMention).toBe(true)
const p2 = tasksRule2[0].payload
expect(p2?.agent?.agentId).toBe(agent.id)
expect(p2?.agent?.sessionId).toBeUndefined()
expect(p2?.agent?.explicitMention).toBe(true)
// Create a root user comment
const userRoot = await prisma.assetComment.create({
@@ -975,14 +971,16 @@ describe('AssetService', () => {
expect(dbReply3a?.replyToId).toBe(userRoot.id)
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)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const p3a = tasksRule3a[0].payload as any
expect(p3a.agentId).toBe(botUser.id)
expect(p3a.sessionId).toBe('test-session-rule3')
expect(p3a.explicitMention).toBe(false)
const p3a = tasksRule3a[0].payload
expect(p3a?.agent?.agentId).toBe(botUser.id)
expect(p3a?.agent?.sessionId).toBe('test-session-rule3')
expect(p3a?.agent?.explicitMention).toBe(false)
// Rule 3b: any user creates a reply directly to the agent comment, explicitly mentions agent
const reply3b = await assetService.createComment({
@@ -1000,14 +998,16 @@ describe('AssetService', () => {
expect(dbReply3b?.replyToId).toBe(userRoot.id)
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)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const p3b = tasksRule3b[0].payload as any
expect(p3b.agentId).toBe(botUser.id)
expect(p3b.sessionId).toBe('test-session-rule3')
expect(p3b.explicitMention).toBe(true)
const p3b = tasksRule3b[0].payload
expect(p3b?.agent?.agentId).toBe(botUser.id)
expect(p3b?.agent?.sessionId).toBe('test-session-rule3')
expect(p3b?.agent?.explicitMention).toBe(true)
})
it('updates asset order correctly', async () => {
+11 -7
View File
@@ -1274,11 +1274,13 @@ export class AssetService {
teamId: a.project.team.id,
projectId: a.project.id,
payload: {
userCommentId: comment.id,
agentId: rootAgentId,
projectId: a.project.id,
sessionId: rootSessionId || undefined,
explicitMention,
agent: {
userCommentId: comment.id,
agentId: rootAgentId,
sessionId: rootSessionId || undefined,
explicitMention,
},
},
},
})
@@ -1307,10 +1309,12 @@ export class AssetService {
teamId: a.project.team.id,
projectId: a.project.id,
payload: {
userCommentId: comment.id,
agentId: agentId,
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 type { Prisma } from '@/generated/prisma/client.ts'
import { systemFields } from './system_fields'
import { ulid } from 'ulid'
import {
CreateFieldRequest,
UpdateFieldRequest,
ProjectFieldOrder,
UpdateAssetMetadataRequest,
UpdateFieldRequest,
} 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 { systemFields } from './system_fields'
export class MetadataService {
constructor(private client: typeof prisma = prisma) {}
+11 -5
View File
@@ -125,9 +125,12 @@ describe('UploadService', () => {
})
expect(workflowTask).toBeDefined()
expect(workflowTask?.payload).toEqual({
videoStrategy: 'single',
sprite: true,
poster: true,
projectId: projectId,
transcode: {
videoStrategy: 'single',
sprite: true,
poster: true,
},
})
})
@@ -159,8 +162,11 @@ describe('UploadService', () => {
})
expect(workflowTask).toBeDefined()
expect(workflowTask?.payload).toEqual({
imageStrategy: 'single',
thumbnail: true,
projectId: projectId,
transcode: {
imageStrategy: 'single',
thumbnail: true,
},
})
})
+12 -3
View File
@@ -254,7 +254,10 @@ export class UploadService {
status: WorkflowTaskStatus.pending,
teamId: team.id,
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,
teamId: team.id,
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,
teamId: team.id,
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 () => {
const task = (await transcodeService.createVideoTranscodeTask('asset-123', {
const task = (await transcodeService.createVideoTranscodeTask('asset-123', 'proj-123', {
videoStrategy: 'single',
thumbnail: true,
})) as WorkflowTask
@@ -224,7 +224,7 @@ describe('TranscodeService', () => {
expect(task.assetId).toBe('asset-123')
expect(task.type).toBe('transcode')
expect(task.status).toBe('pending')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((task.payload as any).videoStrategy).toBe('single')
expect(task.payload?.projectId).toBe('proj-123')
expect(task.payload?.transcode?.videoStrategy).toBe('single')
})
})
+12 -6
View File
@@ -400,26 +400,32 @@ export class TranscodeService {
// --- Task Creation Helpers ---
async createVideoTranscodeTask(assetId: string, spec: PrismaJson.TaskSpec) {
async createVideoTranscodeTask(assetId: string, projectId: string, spec: PrismaJson.TaskSpec) {
return this.prismaClient.workflowTask.create({
data: {
assetId,
projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload: spec as any,
payload: {
projectId,
transcode: spec,
},
},
})
}
async createImageTranscodeTask(assetId: string, spec: PrismaJson.TaskSpec) {
async createImageTranscodeTask(assetId: string, projectId: string, spec: PrismaJson.TaskSpec) {
return this.prismaClient.workflowTask.create({
data: {
assetId,
projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload: spec as any,
payload: {
projectId,
transcode: spec,
},
},
})
}
+8 -2
View File
@@ -40,7 +40,10 @@ export class VideoTranscoder {
projectId: this.projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
payload: this.spec,
payload: {
projectId: this.projectId,
transcode: this.spec,
},
},
})
return task.id
@@ -75,7 +78,10 @@ export class ImageTranscoder {
projectId: this.projectId,
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
payload: this.spec,
payload: {
projectId: this.projectId,
transcode: this.spec,
},
},
})
return task.id
+8 -3
View File
@@ -74,8 +74,11 @@ describe('Transcode Workflow', () => {
status: WorkflowTaskStatus.pending,
output: null,
payload: {
videoStrategy: 'single',
thumbnail: true,
projectId: 'proj-1',
transcode: {
videoStrategy: 'single',
thumbnail: true,
},
},
createdAt: new Date(),
updatedAt: new Date(),
@@ -138,7 +141,9 @@ describe('Transcode Workflow', () => {
type: WorkflowTaskType.transcode,
status: WorkflowTaskStatus.pending,
output: null,
payload: {},
payload: {
projectId: 'proj-1',
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
+13 -3
View File
@@ -55,11 +55,21 @@ describe('Agent Autofill Workflow', () => {
}
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.downloadMediaToTmpActivity.mockResolvedValue({ filePath: '/tmp/test.png', tmpDir: '/tmp' })
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/test.png',
tmpDir: '/tmp',
})
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.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.autofillAiActivity.mockResolvedValue({
+3 -3
View File
@@ -37,12 +37,12 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
})
// 0. Create Placeholder Comment
const payload = task.payload as Record<string, unknown>
const payload = task.payload
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__AUTOFILL__',
sessionId: (payload?.session_id as string) || task.id,
agentId: (payload?.agentId as string) || 'default',
sessionId: payload?.agent?.sessionId || task.id,
agentId: payload?.agent?.agentId || 'default',
})
placeholderCommentId = placeholder.id
+9 -2
View File
@@ -43,7 +43,11 @@ describe('Agent Chat Workflow', () => {
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.getAssetActivity.mockResolvedValue({ id: 'a1', project: { teamId: 't1' } })
mockActivities.initializeAgentSessionActivity.mockResolvedValue('session-123')
@@ -67,7 +71,10 @@ describe('Agent Chat Workflow', () => {
type: 'chat',
status: 'pending',
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',
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const payload = task.payload as any
const payload = task.payload
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
const userCommentId = payload?.userCommentId
const userCommentId = payload.agent?.userCommentId
if (!userCommentId) throw new Error('userCommentId missing in payload')
const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId)
if (!userComment) throw new Error('User comment not found')
@@ -46,7 +49,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
assetId: task.assetId,
message: '__CHAT__',
sessionId: sessionId || 'pending',
agentId: payload?.agentId,
agentId: agentId,
replyToId: userComment.replyToId ?? userComment.id,
})
placeholderCommentId = placeholder.id
@@ -62,26 +65,24 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
if (!sessionId) {
sessionId = await executeActivity(TaskQueueDb, initializeAgentSessionActivity, {
teamId,
agentId: payload.agentId,
agentId: agentId,
userCommentId,
userId: payload.userId,
userId: payload.agent?.userId,
})
}
// 4b. Fetch Agent Context (Database Activity on db_queue)
const context = await executeActivity(TaskQueueDb, getAgentChatContextActivity, {
teamId,
agentId: payload.agentId,
agentId: agentId,
})
// 5. Prepare Images (Attachments only)
const attachmentImageUrls: string[] = []
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const userCommentWithAttachments = userComment as any
if (userCommentWithAttachments?.attachments) {
for (const att of userCommentWithAttachments.attachments) {
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.key) {
attachmentImageUrls.push(att.asset.key)
if (userComment?.attachments) {
for (const att of userComment.attachments) {
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) {
attachmentImageUrls.push(att.asset.storageKey.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).`
if (payload?.explicitMention) {
if (payload.agent?.explicitMention) {
instruction += `\n\nThe user explicitly mentioned you in their message. You MUST reply to this message.`
} 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__.`
@@ -112,15 +113,15 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
teamId,
agentId: payload.agentId,
agentId: agentId,
message: userComment.message || '',
imageUrls: attachmentImageUrls,
projectId: payload.projectId,
folderId,
agentsInstruction: instruction,
sessionId,
userId: payload.userId,
explicitMention: payload?.explicitMention,
userId: payload.agent?.userId,
explicitMention: payload.agent?.explicitMention,
context,
})
@@ -43,7 +43,11 @@ describe('Agent Embedding Workflow', () => {
}
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.generateEmbeddingActivity.mockResolvedValue({
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
const payload = task.payload as Record<string, unknown>
const payload = task.payload
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__EMBEDDING__',
sessionId: (payload?.session_id as string) || task.id,
agentId: (payload?.agentId as string) || 'default',
sessionId: payload?.agent?.sessionId || task.id,
agentId: payload?.agent?.agentId || 'default',
})
placeholderCommentId = placeholder.id
+3 -3
View File
@@ -31,12 +31,12 @@ export async function aiTranscriptionMedia(task: WorkflowTask): Promise<void> {
})
// 0. Create Placeholder Comment
const payload = task.payload as Record<string, unknown>
const payload = task.payload
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__TRANSCRIPTION__',
sessionId: (payload?.session_id as string) || task.id,
agentId: (payload?.agentId as string) || 'default',
sessionId: payload?.agent?.sessionId || task.id,
agentId: payload?.agent?.agentId || 'default',
})
placeholderCommentId = placeholder.id