mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 03:14:11 +00:00
Merge pull request #28 from shumaiOne/refactor/split-db-agent-activities
refactor(workflow): split database and agent activities for strict database isolation
This commit is contained in:
@@ -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.
|
||||
@@ -282,6 +304,26 @@ We use a custom workflow engine that supports both **Local** (polling-based) and
|
||||
- `TemporalExecutor`: Submits tasks to a Temporal cluster.
|
||||
4. **Automatic Submission**: New `WorkflowTask` records are automatically submitted to the `WorkflowService` via a Prisma Client Extension defined in `src/db.ts`.
|
||||
|
||||
### Non-Retryable Error Handling
|
||||
|
||||
To prevent Temporal from indefinitely retrying fatal, expected business validation failures (e.g., missing records, invalid configurations, missing parameters), **never throw standard `Error` objects from workflow or activity logic.** Instead, throw a non-retryable `ApplicationFailure`.
|
||||
|
||||
**Mandatory Requirement**: You **MUST** set `nonRetryable: true` in the options object passed to `ApplicationFailure.create`. Standard errors or `ApplicationFailure` objects without `nonRetryable: true` will cause Temporal to retry the activity or workflow indefinitely.
|
||||
|
||||
- **Workflow Boundary**: In workflows, import `ApplicationFailure` from `@temporalio/workflow`:
|
||||
```typescript
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
throw ApplicationFailure.create({ message: 'agentId missing in payload', nonRetryable: true })
|
||||
```
|
||||
- **Activity Boundary**: In activities, import `ApplicationFailure` from `@temporalio/activity`:
|
||||
```typescript
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
throw ApplicationFailure.create({
|
||||
message: 'no autofill agent found for team',
|
||||
nonRetryable: true,
|
||||
})
|
||||
```
|
||||
|
||||
### Temporal Workflow Patterns
|
||||
|
||||
- **Definition**: Define workflows as exported async functions.
|
||||
|
||||
@@ -40,7 +40,6 @@ describe('file api', () => {
|
||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'getComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
|
||||
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
|
||||
|
||||
@@ -183,20 +183,6 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const comments = await assetService.listComments(fileId, req)
|
||||
return c.json(comments)
|
||||
})
|
||||
.get('/comments/:commentId', async (c) => {
|
||||
const commentId = c.req.param('commentId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Comment,
|
||||
id: commentId,
|
||||
})
|
||||
|
||||
const comment = await assetService.getComment(commentId)
|
||||
return c.json(comment)
|
||||
})
|
||||
.post('/files/restore', zValidator('json', restoreFilesRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -1,17 +1,7 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { AgentService } from './agent'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as piAgent from '@/agent'
|
||||
import { type AutofillField } from '@/agent'
|
||||
|
||||
vi.mock('@/agent', async () => {
|
||||
const actual = await vi.importActual('@/agent')
|
||||
return {
|
||||
...actual,
|
||||
createAgentSession: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AgentService', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -230,273 +220,4 @@ describe('AgentService', () => {
|
||||
expect(agents[0].modelRef).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('agent execution', () => {
|
||||
const mockProviderConfig: PrismaJson.AiProviderSettings = {
|
||||
apiKey: 'test-key',
|
||||
}
|
||||
|
||||
const mockModelConfig: PrismaJson.ModelConfig = {
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 1000,
|
||||
maxTokens: 1000,
|
||||
cost: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
test('autofill extracts metadata', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
|
||||
const team = await db.team.create({
|
||||
data: {
|
||||
name: 'Autofill Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await db.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockProviderConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await db.model.create({
|
||||
data: {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockModelConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
await db.user.create({
|
||||
data: {
|
||||
name: 'Autofiller',
|
||||
email: `autofiller-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'google',
|
||||
model: 'gemini',
|
||||
},
|
||||
},
|
||||
},
|
||||
teamMembers: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
role: 'reviewer',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
|
||||
usage: { input: 5, output: 5 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
|
||||
// Mocking createAgentSession which has complex internal types
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(piAgent.createAgentSession as any).mockImplementation(async (config: unknown) => {
|
||||
const tool = (
|
||||
config as {
|
||||
customTools: Array<{ name: string; execute: (...args: unknown[]) => Promise<unknown> }>
|
||||
}
|
||||
).customTools.find((t) => t.name === 'autofill_metadata')
|
||||
if (tool) {
|
||||
await tool.execute('1', { f1: 'data-val' }, undefined)
|
||||
}
|
||||
return { session: mockSession, harness: mockHarness }
|
||||
})
|
||||
|
||||
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Field 1', type: 'text' } }]
|
||||
const resp = await svc.autofill(team.id, 'extract data', [], fields)
|
||||
expect(resp.text).toBe('{"f1":"data-val"}')
|
||||
expect(resp.usage.inputTokens).toBe(5)
|
||||
})
|
||||
|
||||
test('chats with bot', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
|
||||
const team = await db.team.create({
|
||||
data: {
|
||||
name: 'Chat Bot Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await db.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockProviderConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await db.model.create({
|
||||
data: {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockModelConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
await db.user.create({
|
||||
data: {
|
||||
name: 'Chatter',
|
||||
email: `chatter-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'google',
|
||||
model: 'gemini',
|
||||
},
|
||||
},
|
||||
},
|
||||
teamMembers: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
role: 'reviewer',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'mock text' }],
|
||||
usage: { input: 5, output: 5 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
// Mocking createAgentSession
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(piAgent.createAgentSession as any).mockResolvedValue({
|
||||
session: mockSession,
|
||||
harness: mockHarness,
|
||||
})
|
||||
|
||||
const resp = await svc.chat(team.id, 'hello')
|
||||
expect(resp.text).toBe('mock text')
|
||||
})
|
||||
|
||||
test('chat with instruction', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
|
||||
const team = await db.team.create({
|
||||
data: {
|
||||
name: 'Pirate Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await db.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockProviderConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await db.model.create({
|
||||
data: {
|
||||
modelId: 'gemini-pro',
|
||||
name: 'Gemini Pro',
|
||||
providerId: provider.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockModelConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
const botUser = await db.user.create({
|
||||
data: { name: 'Pirate', email: 'pirate@shumai.ai', type: 'agent' },
|
||||
})
|
||||
|
||||
const agent = await db.agent.create({
|
||||
data: {
|
||||
id: botUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
soul: 'You are a pirate',
|
||||
config: {
|
||||
provider: 'google',
|
||||
model: 'gemini-pro',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: botUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Arr matey!' }],
|
||||
usage: { input: 10, output: 20 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
// Mocking createAgentSession
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(piAgent.createAgentSession as any).mockResolvedValue({
|
||||
session: mockSession,
|
||||
harness: mockHarness,
|
||||
})
|
||||
|
||||
const resp = await svc.chatWithAgent(team.id, agent.id, 'hello', [], 'Talk like a pirate')
|
||||
expect(resp.text).toBe('Arr matey!')
|
||||
expect(resp.usage.inputTokens).toBe(10)
|
||||
expect(resp.usage.outputTokens).toBe(20)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,12 +6,6 @@ import {
|
||||
UpdateAgentParams,
|
||||
} from '@/dtos/agent'
|
||||
import '@/prisma-json-types'
|
||||
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '@/agent'
|
||||
import { logger } from '@/logger'
|
||||
import { Usage } from '@/services/ai/provider/provider'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
|
||||
export class AgentService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
@@ -240,219 +234,6 @@ export class AgentService {
|
||||
})
|
||||
}
|
||||
|
||||
private async getTeam(teamId: string) {
|
||||
return this.prismaClient.team.findUnique({
|
||||
where: { id: teamId },
|
||||
})
|
||||
}
|
||||
|
||||
private async getSandbox(teamId: string) {
|
||||
return this.prismaClient.sandbox.findUnique({
|
||||
where: { teamId },
|
||||
})
|
||||
}
|
||||
|
||||
async chat(teamId: string, prompt: string): Promise<{ text: string; usage: Usage }> {
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
teamId,
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('no chat agent found for team')
|
||||
}
|
||||
const { text, usage } = await this.chatWithAgent(teamId, agent.id, prompt, [], '')
|
||||
return { text, usage }
|
||||
}
|
||||
|
||||
async chatWithAgent(
|
||||
teamId: string,
|
||||
agentId: string,
|
||||
prompt: string,
|
||||
images: string[],
|
||||
agentsInstruction: string,
|
||||
sessionId?: string,
|
||||
userId?: string,
|
||||
tools: AgentTool[] = [],
|
||||
): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
const t = await this.getTeam(teamId)
|
||||
if (!t) throw new Error('failed to get team')
|
||||
|
||||
const agent = await this.prismaClient.agent.findUnique({
|
||||
where: { id: agentId },
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!agent) {
|
||||
throw new Error(`agent ${agentId} not found`)
|
||||
}
|
||||
|
||||
if (!agent.provider) throw new Error('agent has no provider configured')
|
||||
if (!agent.modelRef) throw new Error('agent has no model configured')
|
||||
|
||||
const providerName = agent.provider.name
|
||||
const modelId = agent.modelRef.modelId
|
||||
|
||||
// Fetch the required provider configuration from database
|
||||
const dbProviders = await this.prismaClient.provider.findMany({
|
||||
where: { teamId, name: providerName },
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await this.prismaClient.skill.findMany({
|
||||
where: { teamId },
|
||||
})
|
||||
|
||||
const sandbox = await this.getSandbox(teamId)
|
||||
const allowedDomains = sandbox?.allowedDomains || []
|
||||
|
||||
let systemPrompt = '你是shumai小助手。'
|
||||
if (agentsInstruction) {
|
||||
systemPrompt = `${systemPrompt}\n\nContext and Instructions:\n${agentsInstruction}`
|
||||
}
|
||||
|
||||
const modelConfig = agent.modelRef?.config as unknown as PrismaJson.ModelConfig
|
||||
if (modelConfig?.input) {
|
||||
systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.`
|
||||
}
|
||||
|
||||
const { session, harness } = await createAgentSession({
|
||||
agentId,
|
||||
providerName,
|
||||
modelId,
|
||||
systemPrompt,
|
||||
teamSkills: teamSkills.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
})),
|
||||
allowedDomains,
|
||||
sessionId,
|
||||
userId,
|
||||
customTools: tools,
|
||||
providers: dbProviders.map((p) => ({
|
||||
name: p.name,
|
||||
config: p.config,
|
||||
models: p.models.map((m) => ({
|
||||
modelId: m.modelId,
|
||||
name: m.name,
|
||||
config: m.config,
|
||||
})),
|
||||
})),
|
||||
})
|
||||
|
||||
const imagesToPass: ImageContent[] = []
|
||||
|
||||
if (images && images.length > 0) {
|
||||
for (const key of images) {
|
||||
const { buffer, contentType } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
)
|
||||
imagesToPass.push({
|
||||
type: 'image',
|
||||
data: buffer.toString('base64'),
|
||||
mimeType: contentType,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const assistantMessage = await harness.prompt(prompt, { images: imagesToPass })
|
||||
|
||||
const sessionEntries = await session.getEntries()
|
||||
sessionEntries.forEach((entry) => {
|
||||
if (entry.type === 'message') {
|
||||
const msg = entry.message
|
||||
if (msg.role === 'toolResult') {
|
||||
const logMsg = { ...msg, content: undefined }
|
||||
logger.debug(logMsg, 'agent message')
|
||||
} else {
|
||||
logger.debug(msg, 'agent message')
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const text = assistantMessage.content
|
||||
.filter((c) => c.type === 'text')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- text property exists on text content items
|
||||
.map((c) => (c as any).text)
|
||||
.join('\n')
|
||||
|
||||
const usage: Usage = {
|
||||
model: modelId,
|
||||
inputTokens: assistantMessage.usage?.input || 0,
|
||||
outputTokens: assistantMessage.usage?.output || 0,
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- sessionId property added to DatabaseSessionStorage
|
||||
return { text, usage, sessionId: (session.getStorage() as any).sessionId }
|
||||
} finally {
|
||||
// Cleanup handled by agent session if needed
|
||||
}
|
||||
}
|
||||
|
||||
async autofill(
|
||||
teamId: string,
|
||||
prompt: string,
|
||||
images: string[],
|
||||
fields: AutofillField[],
|
||||
): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
teamId,
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('no autofill agent found for team')
|
||||
}
|
||||
|
||||
const toolSchema = fieldsToTypeBoxSchema(fields)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let capturedData: any = null
|
||||
|
||||
const autofillTool: AgentTool = {
|
||||
name: 'autofill_metadata',
|
||||
label: 'Autofill Metadata',
|
||||
description: 'Extract metadata from the images.',
|
||||
parameters: toolSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
capturedData = params
|
||||
return {
|
||||
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
|
||||
details: {},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
const fullPrompt = `${prompt}\n\nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
|
||||
|
||||
const { usage, sessionId } = await this.chatWithAgent(
|
||||
teamId,
|
||||
agent.id,
|
||||
fullPrompt,
|
||||
images,
|
||||
'',
|
||||
undefined,
|
||||
undefined,
|
||||
[autofillTool],
|
||||
)
|
||||
|
||||
return {
|
||||
text: capturedData ? JSON.stringify(capturedData) : '{}',
|
||||
usage,
|
||||
sessionId,
|
||||
}
|
||||
}
|
||||
|
||||
async getSessionEntries(params: { sessionId: string }) {
|
||||
return this.prismaClient.agentSessionEntry.findMany({
|
||||
where: { sessionId: params.sessionId },
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { aiService } from './ai'
|
||||
|
||||
const mockProviderConfig: PrismaJson.ProviderConfig = {
|
||||
api: 'openai-completions',
|
||||
baseUrl: 'http://localhost:11434/v1',
|
||||
apiKey: 'test-key',
|
||||
}
|
||||
|
||||
const mockModelConfig: PrismaJson.ModelConfig = {
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 1000,
|
||||
maxTokens: 1000,
|
||||
cost: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
}
|
||||
|
||||
describe('AiService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('transcribes', async () => {
|
||||
// Transcribe still uses provider factory
|
||||
const mockTranscribe = vi.fn().mockResolvedValue({
|
||||
text: 'mock transcription',
|
||||
usage: { model: 'whisper', inputTokens: 0, outputTokens: 0 },
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(aiService as any).providerFactory = () => ({
|
||||
transcribe: mockTranscribe,
|
||||
})
|
||||
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Transcribe Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'openai',
|
||||
teamId: team.id,
|
||||
config: mockProviderConfig,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'whisper',
|
||||
name: 'Whisper',
|
||||
providerId: provider.id,
|
||||
config: mockModelConfig,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
name: 'Transcriber',
|
||||
email: `transcriber-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'transcription',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'whisper',
|
||||
},
|
||||
},
|
||||
},
|
||||
teamMembers: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
role: 'reviewer',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const resp = await aiService.transcribe(team.id, Buffer.from(''))
|
||||
expect(resp.text).toBe('mock transcription')
|
||||
expect(mockTranscribe).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,242 +0,0 @@
|
||||
import { prisma } from '@/db'
|
||||
import { AiProvider } from '@/dtos/ai'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
|
||||
import { exec } from 'child_process'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import { promisify } from 'util'
|
||||
import { ElevenLabsProvider } from './provider/elevenlabs'
|
||||
import { GeminiProvider } from './provider/gemini'
|
||||
import { OpenAiProvider } from './provider/openai'
|
||||
import { Provider, Usage } from './provider/provider'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
export type ProviderFactory = (
|
||||
providerName: string,
|
||||
config: PrismaJson.AiProviderSettings,
|
||||
) => Provider
|
||||
|
||||
function defaultProviderFactory(
|
||||
providerName: string,
|
||||
config: PrismaJson.AiProviderSettings,
|
||||
): Provider {
|
||||
let pKey: AiProvider
|
||||
switch (providerName) {
|
||||
case AiProvider.Google:
|
||||
pKey = AiProvider.Google
|
||||
break
|
||||
case AiProvider.OpenAi:
|
||||
pKey = AiProvider.OpenAi
|
||||
break
|
||||
case AiProvider.ElevenLabs:
|
||||
pKey = AiProvider.ElevenLabs
|
||||
break
|
||||
default:
|
||||
throw new Error(`Unsupported provider: ${providerName}`)
|
||||
}
|
||||
|
||||
// Typecasting config for now to match the strict interface in providers.
|
||||
switch (pKey) {
|
||||
case AiProvider.Google:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return new GeminiProvider(config as any)
|
||||
case AiProvider.OpenAi:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return new OpenAiProvider(config as any)
|
||||
case AiProvider.ElevenLabs:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return new ElevenLabsProvider(config as any)
|
||||
default:
|
||||
throw new Error(`Provider implementation for ${providerName} not found`)
|
||||
}
|
||||
}
|
||||
|
||||
export class AiService {
|
||||
private providerFactory: ProviderFactory = defaultProviderFactory
|
||||
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
private async getTeam(teamId: string) {
|
||||
return this.prismaClient.team.findUnique({
|
||||
where: { id: teamId },
|
||||
})
|
||||
}
|
||||
|
||||
async transcribe(teamId: string, audioBuffer: Buffer): Promise<{ text: string; usage: Usage }> {
|
||||
const t = await this.getTeam(teamId)
|
||||
if (!t) throw new Error('failed to get team')
|
||||
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'transcription',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('transcription feature is disabled or agent not found')
|
||||
}
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
if (!config.provider) throw new Error('transcription provider not configured')
|
||||
if (!config.model) throw new Error('transcription model not configured')
|
||||
|
||||
const dbProvider = await this.prismaClient.provider.findFirst({
|
||||
where: { teamId, name: config.provider },
|
||||
})
|
||||
if (!dbProvider) throw new Error(`Provider ${config.provider} not found in database`)
|
||||
|
||||
const p = this.providerFactory(
|
||||
config.provider,
|
||||
dbProvider.config as PrismaJson.AiProviderSettings,
|
||||
)
|
||||
|
||||
return p.transcribe(config.model, audioBuffer)
|
||||
}
|
||||
|
||||
async generateAssetEmbeddings(teamId: string, assetId: string): Promise<Usage> {
|
||||
const t = await this.getTeam(teamId)
|
||||
if (!t) throw new Error('failed to get team')
|
||||
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('embedding feature is disabled or agent not found')
|
||||
}
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
if (!config.provider) throw new Error('embedding provider not configured')
|
||||
if (!config.model) throw new Error('embedding model not configured')
|
||||
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
|
||||
if (!asset) throw new Error('failed to get asset')
|
||||
if (!asset.mediaType) throw new Error('asset has no media type')
|
||||
|
||||
const dbProvider = await this.prismaClient.provider.findFirst({
|
||||
where: { teamId, name: config.provider },
|
||||
})
|
||||
if (!dbProvider) throw new Error(`Provider ${config.provider} not found in database`)
|
||||
|
||||
const p = this.providerFactory(
|
||||
config.provider,
|
||||
dbProvider.config as PrismaJson.AiProviderSettings,
|
||||
)
|
||||
|
||||
const usage: Usage = {
|
||||
model: config.model,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
const isImage = asset.mediaType.startsWith('image/')
|
||||
const isVideo = asset.mediaType.startsWith('video/')
|
||||
|
||||
if (!isImage && !isVideo) {
|
||||
throw new Error(`unsupported media type for embeddings: ${asset.mediaType}`)
|
||||
}
|
||||
|
||||
const key = asset.storageKey?.key
|
||||
if (!key) {
|
||||
throw new Error(`asset has no key`)
|
||||
}
|
||||
|
||||
const { buffer: data } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
|
||||
|
||||
if (isImage) {
|
||||
const embVec = await p.generateImageEmbedding(config.model, data)
|
||||
|
||||
await this.prismaClient.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${asset.id}, ${embVec}::vector, NOW())
|
||||
`
|
||||
} else if (isVideo) {
|
||||
const tmpFile = path.join(os.tmpdir(), `video-${Date.now()}.mp4`)
|
||||
fs.writeFileSync(tmpFile, data)
|
||||
|
||||
try {
|
||||
const { stdout } = await execAsync(
|
||||
`ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${tmpFile}"`,
|
||||
)
|
||||
const duration = parseFloat(stdout.trim())
|
||||
if (isNaN(duration)) throw new Error('failed to parse video duration')
|
||||
|
||||
const chunkSize = 60.0
|
||||
for (let start = 0.0; start < duration; start += chunkSize) {
|
||||
let end = start + chunkSize
|
||||
if (end > duration) end = duration
|
||||
|
||||
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`)
|
||||
await execAsync(
|
||||
`ffmpeg -y -i "${tmpFile}" -ss ${start} -t ${end - start} -c copy "${chunkTmp}"`,
|
||||
)
|
||||
|
||||
const chunkData = fs.readFileSync(chunkTmp)
|
||||
fs.unlinkSync(chunkTmp)
|
||||
|
||||
try {
|
||||
const embVec = await p.generateVideoEmbedding(config.model, chunkData)
|
||||
await this.prismaClient.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${asset.id}, ${embVec}::vector, ${start}, ${end}, NOW())
|
||||
`
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (e: any) {
|
||||
console.error(
|
||||
`failed to generate video embedding for chunk ${start}-${end}: ${e.message}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fs.unlinkSync(tmpFile)
|
||||
}
|
||||
}
|
||||
|
||||
return usage
|
||||
}
|
||||
|
||||
async generateTextEmbeddings(teamId: string, text: string): Promise<number[]> {
|
||||
const t = await this.getTeam(teamId)
|
||||
if (!t) throw new Error('failed to get team')
|
||||
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('embedding feature is disabled or agent not found')
|
||||
}
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
if (!config.provider) throw new Error('embedding provider not configured')
|
||||
if (!config.model) throw new Error('embedding model not configured')
|
||||
|
||||
const dbProvider = await this.prismaClient.provider.findFirst({
|
||||
where: { teamId, name: config.provider },
|
||||
})
|
||||
if (!dbProvider) throw new Error(`Provider ${config.provider} not found in database`)
|
||||
|
||||
const p = this.providerFactory(
|
||||
config.provider,
|
||||
dbProvider.config as PrismaJson.AiProviderSettings,
|
||||
)
|
||||
|
||||
return p.generateTextEmbedding(config.model, text)
|
||||
}
|
||||
}
|
||||
|
||||
export const aiService = new AiService()
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -190,5 +190,18 @@ describe('MetadataService', () => {
|
||||
await expect(metadataService.updateAssetMetadata(asset.id, reqs)).rejects.toThrow(
|
||||
'Field readonly-field is read-only',
|
||||
)
|
||||
|
||||
// With allowReadOnly=true, it should successfully update
|
||||
await metadataService.updateAssetMetadata(asset.id, reqs, true)
|
||||
const val = await prisma.assetMetadataValue.findUnique({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
assetId_fieldId: {
|
||||
assetId: asset.id,
|
||||
fieldId: field.key,
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(val?.stringValue).toBe('some value')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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) {}
|
||||
@@ -259,7 +258,11 @@ export class MetadataService {
|
||||
})
|
||||
}
|
||||
|
||||
async updateAssetMetadata(assetId: string, reqs: UpdateAssetMetadataRequest[]): Promise<void> {
|
||||
async updateAssetMetadata(
|
||||
assetId: string,
|
||||
reqs: UpdateAssetMetadataRequest[],
|
||||
allowReadOnly = false,
|
||||
): Promise<void> {
|
||||
const resolvedAssetId = await assetService.resolveLatestVersionId(assetId)
|
||||
|
||||
await this.client.$transaction(async (tx) => {
|
||||
@@ -267,7 +270,7 @@ export class MetadataService {
|
||||
const field = await tx.metadataField.findUnique({
|
||||
where: { key: req.key },
|
||||
})
|
||||
if (field?.readOnly) {
|
||||
if (field?.readOnly && !allowReadOnly) {
|
||||
throw new Error(`Field ${field.key} is read-only`)
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -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 },
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { prisma } from '@/db'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { transcodeService } from '@/transcode/transcode'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
|
||||
@@ -72,7 +73,7 @@ export async function getMediaInfoActivity(params: {
|
||||
if (info.audioBitDepth !== undefined)
|
||||
metadataUpdates.push({ key: 'audio_bit_depth', value: info.audioBitDepth })
|
||||
|
||||
await metadataService.updateAssetMetadata(params.assetId, metadataUpdates)
|
||||
await metadataService.updateAssetMetadata(params.assetId, metadataUpdates, true)
|
||||
} else if (isImage) {
|
||||
const info = await transcodeService.getImageInfo(params.filePath)
|
||||
mediaInfo.metadata = {
|
||||
@@ -84,10 +85,14 @@ export async function getMediaInfoActivity(params: {
|
||||
hasAudio: false,
|
||||
format: {},
|
||||
}
|
||||
await metadataService.updateAssetMetadata(params.assetId, [
|
||||
{ key: 'resolution_width', value: info.originalWidth },
|
||||
{ key: 'resolution_height', value: info.originalHeight },
|
||||
])
|
||||
await metadataService.updateAssetMetadata(
|
||||
params.assetId,
|
||||
[
|
||||
{ key: 'resolution_width', value: info.originalWidth },
|
||||
{ key: 'resolution_height', value: info.originalHeight },
|
||||
],
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
return mediaInfo
|
||||
@@ -275,7 +280,12 @@ export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityP
|
||||
include: { storageKey: true },
|
||||
})
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) throw new Error('Asset not found or has no key')
|
||||
if (!asset || !key) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Asset not found or has no key',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const infoKey = path.join(path.dirname(key), 'info.json')
|
||||
const buffer = Buffer.from(JSON.stringify(params.mediaInfo))
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(),
|
||||
@@ -119,7 +122,14 @@ describe('Transcode Workflow', () => {
|
||||
status: AssetStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
mediaInfo: expect.objectContaining({
|
||||
thumbnail: expect.objectContaining({
|
||||
key: 't.webp',
|
||||
}),
|
||||
}),
|
||||
})
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
status: AssetStatus.processed,
|
||||
@@ -131,6 +141,74 @@ describe('Transcode Workflow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('should process image transcode and thumbnail successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-image',
|
||||
assetId: 'asset-image',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
transcode: {
|
||||
imageStrategy: 'single',
|
||||
thumbnail: true,
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-image',
|
||||
storageKey: { key: 'image.jpg' },
|
||||
mediaType: 'image/jpeg',
|
||||
})
|
||||
|
||||
mockActivities.getMediaInfoActivity.mockResolvedValue({
|
||||
mimeType: 'image/jpeg',
|
||||
metadata: { originalWidth: 1000, originalHeight: 1000 },
|
||||
videoTranscodes: [],
|
||||
imageTranscodes: [],
|
||||
})
|
||||
|
||||
mockActivities.transcodeImageActivity.mockResolvedValue({
|
||||
key: 't.webp',
|
||||
width: 480,
|
||||
height: 480,
|
||||
format: 'webp',
|
||||
})
|
||||
|
||||
await transcodeMedia(task)
|
||||
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-image',
|
||||
status: AssetStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-image',
|
||||
mediaInfo: expect.objectContaining({
|
||||
thumbnail: expect.objectContaining({
|
||||
key: 't.webp',
|
||||
width: 480,
|
||||
height: 480,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-image',
|
||||
status: AssetStatus.processed,
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update task status with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
@@ -138,7 +216,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,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import {
|
||||
getActivities,
|
||||
executeActivity,
|
||||
@@ -39,7 +40,12 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
// 2. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) throw new Error('Asset not found or has no key')
|
||||
if (!asset || !key) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Asset not found or has no key',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// 3. Get Worker-Specific Queue for Transcode
|
||||
workerQueue = await executeActivity(TaskQueueTranscode, getTranscodeWorkerQueueActivity)
|
||||
@@ -52,7 +58,7 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
// 5. Get Media Info
|
||||
const spec = task.payload as PrismaJson.TaskSpec
|
||||
const spec = task.payload?.transcode || {}
|
||||
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
|
||||
filePath,
|
||||
assetId: asset.id,
|
||||
|
||||
@@ -57,31 +57,7 @@ export const MessageCard: React.FC<MessageCardProps> = ({
|
||||
onSelect,
|
||||
frameRate,
|
||||
}) => {
|
||||
const isRunning =
|
||||
!!initialMessage.sessionId &&
|
||||
!!initialMessage.message &&
|
||||
initialMessage.message in AI_PLACEHOLDERS
|
||||
|
||||
const { data: polledMessage } = useQuery({
|
||||
queryKey: ['comments', initialMessage.id],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.comments[':commentId'].$get({
|
||||
param: { commentId: initialMessage.id! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch comment')
|
||||
return (await res.json()) as CommentInfo
|
||||
},
|
||||
enabled: !!teamId && isRunning,
|
||||
refetchInterval: (query) => {
|
||||
const data = query.state.data as CommentInfo
|
||||
if (data && (!data.message || !(data.message in AI_PLACEHOLDERS))) {
|
||||
return false
|
||||
}
|
||||
return 2000
|
||||
},
|
||||
})
|
||||
|
||||
const message = polledMessage || initialMessage
|
||||
const message = initialMessage
|
||||
const hasDrawInfo =
|
||||
!!message.annotations && Array.isArray(message.annotations) && message.annotations.length > 0
|
||||
const creator = message.creator
|
||||
|
||||
@@ -1,26 +1,48 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiChatActivity } from './agent'
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
import { agentChatActivity, autofillAiActivity } from './agent'
|
||||
import * as piAgent from '@/agent'
|
||||
|
||||
vi.mock('@/services/agent/agent', () => ({
|
||||
agentService: {
|
||||
chatWithAgent: vi.fn(),
|
||||
},
|
||||
}))
|
||||
vi.mock('@/agent', async () => {
|
||||
const actual = await vi.importActual('@/agent')
|
||||
return {
|
||||
...actual,
|
||||
createAgentSession: vi.fn(),
|
||||
fieldsToTypeBoxSchema: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Activities', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should call aiChatActivity and delegate to agentService', async () => {
|
||||
vi.mocked(agentService.chatWithAgent).mockResolvedValue({
|
||||
text: 'AI response',
|
||||
usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' },
|
||||
sessionId: 'mock-session-id',
|
||||
it('should call agentChatActivity and prompt the harness', async () => {
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'AI response' }],
|
||||
usage: { input: 10, output: 20 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
|
||||
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock session type is not fully compatible with pi-agent-core Session
|
||||
session: mockSession as any,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock harness type is not fully compatible with pi-agent-core Harness
|
||||
harness: mockHarness as any,
|
||||
})
|
||||
|
||||
await aiChatActivity({
|
||||
const context = {
|
||||
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
|
||||
dbProviders: [],
|
||||
teamSkills: [],
|
||||
allowedDomains: [],
|
||||
}
|
||||
|
||||
const res = await agentChatActivity({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
message: 'Hi',
|
||||
@@ -28,16 +50,58 @@ describe('Agent Activities', () => {
|
||||
projectId: 'p1',
|
||||
folderId: 'f1',
|
||||
sessionId: 'mock-session-id',
|
||||
context,
|
||||
})
|
||||
|
||||
expect(agentService.chatWithAgent).toHaveBeenCalledWith(
|
||||
't1',
|
||||
'b1',
|
||||
'Hi',
|
||||
[],
|
||||
'',
|
||||
'mock-session-id',
|
||||
undefined,
|
||||
)
|
||||
expect(res.text).toBe('AI response')
|
||||
expect(res.usage.inputTokens).toBe(10)
|
||||
expect(res.usage.outputTokens).toBe(20)
|
||||
expect(piAgent.createAgentSession).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should call autofillAiActivity and run autofill tool', async () => {
|
||||
const mockHarness = {
|
||||
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' }),
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- config object is passed dynamically by test runner
|
||||
vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: any) => {
|
||||
// Simulate tool execution
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- customTools type is dynamic and nested
|
||||
const tool = config.customTools.find((t: any) => t.name === 'autofill_metadata')
|
||||
if (tool) {
|
||||
await tool.execute('1', { f1: 'val' })
|
||||
}
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock session type is not fully compatible with pi-agent-core Session
|
||||
session: mockSession as any,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock harness type is not fully compatible with pi-agent-core Harness
|
||||
harness: mockHarness as any,
|
||||
}
|
||||
})
|
||||
|
||||
const context = {
|
||||
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
|
||||
dbProviders: [],
|
||||
teamSkills: [],
|
||||
allowedDomains: [],
|
||||
}
|
||||
|
||||
const res = await autofillAiActivity({
|
||||
teamId: 't1',
|
||||
images: [],
|
||||
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
|
||||
context,
|
||||
})
|
||||
|
||||
expect(res.text).toBe('{"f1":"val"}')
|
||||
expect(res.usage.inputTokens).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,18 +1,142 @@
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
import type { AutofillField } from '@/agent'
|
||||
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '@/agent'
|
||||
import { logger } from '@/logger'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { type Usage } from '@/services/ai/provider/provider'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
|
||||
export interface AutofillAiParams {
|
||||
interface AgentExecutionContext {
|
||||
agent: unknown
|
||||
dbProviders: unknown[]
|
||||
teamSkills: unknown[]
|
||||
allowedDomains: string[]
|
||||
}
|
||||
|
||||
async function executeAgentPrompt(params: {
|
||||
teamId: string
|
||||
agentId: string
|
||||
prompt: string
|
||||
images: string[]
|
||||
fields: AutofillField[]
|
||||
agentsInstruction: string
|
||||
sessionId?: string
|
||||
userId?: string
|
||||
tools?: AgentTool[]
|
||||
context: AgentExecutionContext
|
||||
}): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context is a serialized JSON object from db activity
|
||||
const context = params.context as any
|
||||
const agent = context.agent
|
||||
const dbProviders = context.dbProviders
|
||||
const teamSkills = context.teamSkills
|
||||
const allowedDomains = context.allowedDomains
|
||||
|
||||
if (!agent.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'agent has no provider configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
if (!agent.modelRef) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'agent has no model configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const providerName = agent.provider.name
|
||||
const modelId = agent.modelRef.modelId
|
||||
|
||||
let systemPrompt = '你是shumai小助手。'
|
||||
if (params.agentsInstruction) {
|
||||
systemPrompt = `${systemPrompt}\n\nContext and Instructions:\n${params.agentsInstruction}`
|
||||
}
|
||||
|
||||
const modelConfig = agent.modelRef?.config as unknown as PrismaJson.ModelConfig
|
||||
if (modelConfig?.input) {
|
||||
systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.`
|
||||
}
|
||||
|
||||
const { session, harness } = await createAgentSession({
|
||||
agentId: params.agentId,
|
||||
providerName,
|
||||
modelId,
|
||||
systemPrompt,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- s is typed as any because teamSkills is dynamically deserialized JSON
|
||||
teamSkills: teamSkills.map((s: any) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
})),
|
||||
allowedDomains,
|
||||
sessionId: params.sessionId,
|
||||
userId: params.userId,
|
||||
customTools: params.tools || [],
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- p is typed as any because dbProviders is dynamically deserialized JSON
|
||||
providers: dbProviders.map((p: any) => ({
|
||||
name: p.name,
|
||||
config: p.config,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- m is typed as any because p.models is a generic dynamic JSON array from the DB context
|
||||
models: p.models.map((m: any) => ({
|
||||
modelId: m.modelId,
|
||||
name: m.name,
|
||||
config: m.config,
|
||||
})),
|
||||
})),
|
||||
})
|
||||
|
||||
const imagesToPass: ImageContent[] = []
|
||||
|
||||
if (params.images && params.images.length > 0) {
|
||||
for (const key of params.images) {
|
||||
const { buffer, contentType } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
)
|
||||
imagesToPass.push({
|
||||
type: 'image',
|
||||
data: buffer.toString('base64'),
|
||||
mimeType: contentType,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass })
|
||||
|
||||
const sessionEntries = await session.getEntries()
|
||||
sessionEntries.forEach((entry) => {
|
||||
if (entry.type === 'message') {
|
||||
const msg = entry.message
|
||||
if (msg.role === 'toolResult') {
|
||||
const logMsg = { ...msg, content: undefined }
|
||||
logger.debug(logMsg, 'agent message')
|
||||
} else {
|
||||
logger.debug(msg, 'agent message')
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const text = assistantMessage.content
|
||||
.filter((c) => c.type === 'text')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- text property exists on text content items
|
||||
.map((c) => (c as any).text)
|
||||
.join('\n')
|
||||
|
||||
const usage: Usage = {
|
||||
model: modelId,
|
||||
inputTokens: assistantMessage.usage?.input || 0,
|
||||
outputTokens: assistantMessage.usage?.output || 0,
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- sessionId property added to DatabaseSessionStorage
|
||||
return { text, usage, sessionId: (session.getStorage() as any).sessionId }
|
||||
} finally {
|
||||
// Cleanup handled by agent session if needed
|
||||
}
|
||||
}
|
||||
|
||||
export async function autofillAiActivity(params: AutofillAiParams) {
|
||||
const prompt = 'Analyze the provided images and extract metadata.'
|
||||
return agentService.autofill(params.teamId, prompt, params.images, params.fields)
|
||||
}
|
||||
|
||||
export interface AiChatParams {
|
||||
export interface AgentChatParams {
|
||||
teamId: string
|
||||
agentId: string
|
||||
message: string
|
||||
@@ -23,19 +147,73 @@ export interface AiChatParams {
|
||||
sessionId: string
|
||||
userId?: string
|
||||
explicitMention?: boolean
|
||||
context: AgentExecutionContext
|
||||
}
|
||||
|
||||
export async function aiChatActivity(params: AiChatParams) {
|
||||
export async function agentChatActivity(params: AgentChatParams) {
|
||||
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
|
||||
const sessionId = params.sessionId
|
||||
|
||||
return agentService.chatWithAgent(
|
||||
params.teamId,
|
||||
params.agentId,
|
||||
cleanMessage,
|
||||
params.imageUrls,
|
||||
params.agentsInstruction || '',
|
||||
return executeAgentPrompt({
|
||||
teamId: params.teamId,
|
||||
agentId: params.agentId,
|
||||
prompt: cleanMessage,
|
||||
images: params.imageUrls,
|
||||
agentsInstruction: params.agentsInstruction || '',
|
||||
sessionId,
|
||||
params.userId,
|
||||
)
|
||||
userId: params.userId,
|
||||
context: params.context,
|
||||
})
|
||||
}
|
||||
|
||||
export interface AutofillAiParams {
|
||||
teamId: string
|
||||
images: string[]
|
||||
fields: AutofillField[]
|
||||
context: AgentExecutionContext
|
||||
}
|
||||
|
||||
export async function autofillAiActivity(params: AutofillAiParams) {
|
||||
const prompt = 'Analyze the provided images and extract metadata.'
|
||||
const toolSchema = fieldsToTypeBoxSchema(params.fields)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let capturedData: any = null
|
||||
|
||||
const autofillTool: AgentTool = {
|
||||
name: 'autofill_metadata',
|
||||
label: 'Autofill Metadata',
|
||||
description: 'Extract metadata from the images.',
|
||||
parameters: toolSchema,
|
||||
execute: async (_toolCallId, toolParams) => {
|
||||
capturedData = toolParams
|
||||
return {
|
||||
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
|
||||
details: {},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
const fullPrompt = `${prompt}\n\nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context is a serialized JSON object from db activity
|
||||
const context = params.context as any
|
||||
const agent = context.agent
|
||||
|
||||
const { usage, sessionId } = await executeAgentPrompt({
|
||||
teamId: params.teamId,
|
||||
agentId: agent.id,
|
||||
prompt: fullPrompt,
|
||||
images: params.images,
|
||||
agentsInstruction: '',
|
||||
sessionId: undefined,
|
||||
userId: undefined,
|
||||
tools: [autofillTool],
|
||||
context: params.context,
|
||||
})
|
||||
|
||||
return {
|
||||
text: capturedData ? JSON.stringify(capturedData) : '{}',
|
||||
usage,
|
||||
sessionId,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,74 +1,50 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { getAssetActivity, generateEmbeddingActivity, getCommentActivity } from './ai'
|
||||
import { aiService } from '@/services/ai/ai'
|
||||
import { generateEmbeddingActivity } from './ai'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
|
||||
vi.mock('@/services/ai/ai', () => ({
|
||||
aiService: {
|
||||
generateAssetEmbeddings: vi.fn(),
|
||||
vi.mock('@/services/s3/s3', () => ({
|
||||
s3Service: {
|
||||
getObject: vi.fn(),
|
||||
putObject: vi.fn(),
|
||||
headObject: vi.fn(),
|
||||
listObjects: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('AI Activities', () => {
|
||||
setupTestDbHooks()
|
||||
vi.mock('@/services/ai/provider/gemini', () => {
|
||||
return {
|
||||
GeminiProvider: class {
|
||||
generateImageEmbedding = vi.fn().mockResolvedValue([0.1, 0.2, 0.3])
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
describe('AI Activities', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should get asset with project and team', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Team A' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Proj A', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.png',
|
||||
storageKey: { create: { key: 'test.png' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
project: { connect: { id: project.id } },
|
||||
},
|
||||
it('should generate image embedding', async () => {
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('test-image'),
|
||||
contentType: 'image/png',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock getObject return value needs broad any casting
|
||||
} as any)
|
||||
|
||||
const context = {
|
||||
agent: { config: { provider: 'google', model: 'gemini' } },
|
||||
asset: { id: 'a1', mediaType: 'image/png', storageKey: { key: 'test.png' } },
|
||||
dbProvider: { config: { apiKey: 'key' } },
|
||||
}
|
||||
|
||||
const res = await generateEmbeddingActivity({
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
context,
|
||||
})
|
||||
|
||||
const result = await getAssetActivity(asset.id)
|
||||
expect(result?.project?.team?.id).toBe(team.id)
|
||||
})
|
||||
|
||||
it('should call generateAssetEmbeddings', async () => {
|
||||
vi.mocked(aiService.generateAssetEmbeddings).mockResolvedValue({
|
||||
inputTokens: 1,
|
||||
outputTokens: 1,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
await generateEmbeddingActivity({ teamId: 't1', assetId: 'a1' })
|
||||
expect(aiService.generateAssetEmbeddings).toHaveBeenCalledWith('t1', 'a1')
|
||||
})
|
||||
|
||||
it('should get and update comments', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Test User', email: 'test-ai@example.com', password: 'pw' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.png',
|
||||
storageKey: { create: { key: 'test.png' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
},
|
||||
})
|
||||
|
||||
const comment = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
creatorId: user.id,
|
||||
message: 'Original',
|
||||
},
|
||||
})
|
||||
|
||||
const fetched = await getCommentActivity(comment.id)
|
||||
expect(fetched?.message).toBe('Original')
|
||||
expect(res.embeddings.length).toBe(1)
|
||||
expect(res.embeddings[0].embedding).toEqual([0.1, 0.2, 0.3])
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png')
|
||||
})
|
||||
})
|
||||
|
||||
+157
-36
@@ -1,54 +1,175 @@
|
||||
import { prisma } from '@/db'
|
||||
import { aiService } from '@/services/ai/ai'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { UpdateAssetMetadataRequest } from '@/dtos/metadata'
|
||||
import { ElevenLabsProvider } from '@/services/ai/provider/elevenlabs'
|
||||
import { GeminiProvider } from '@/services/ai/provider/gemini'
|
||||
import { OpenAiProvider } from '@/services/ai/provider/openai'
|
||||
import { Provider, Usage } from '@/services/ai/provider/provider'
|
||||
import { AiProvider } from '@/dtos/ai'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { transcodeService } from '@/transcode/transcode'
|
||||
import * as path from 'path'
|
||||
import { exec } from 'child_process'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import { promisify } from 'util'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
|
||||
export async function getAssetActivity(assetId: string) {
|
||||
return prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
function providerFactory(providerName: string, config: PrismaJson.AiProviderSettings): Provider {
|
||||
let pKey: AiProvider
|
||||
switch (providerName) {
|
||||
case AiProvider.Google:
|
||||
pKey = AiProvider.Google
|
||||
break
|
||||
case AiProvider.OpenAi:
|
||||
pKey = AiProvider.OpenAi
|
||||
break
|
||||
case AiProvider.ElevenLabs:
|
||||
pKey = AiProvider.ElevenLabs
|
||||
break
|
||||
default:
|
||||
throw ApplicationFailure.create({
|
||||
message: `Unsupported provider: ${providerName}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
switch (pKey) {
|
||||
case AiProvider.Google:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- provider config requires a broad casting since it is a JSON property of the provider model
|
||||
return new GeminiProvider(config as any)
|
||||
case AiProvider.OpenAi:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- provider config requires a broad casting since it is a JSON property of the provider model
|
||||
return new OpenAiProvider(config as any)
|
||||
case AiProvider.ElevenLabs:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- provider config requires a broad casting since it is a JSON property of the provider model
|
||||
return new ElevenLabsProvider(config as any)
|
||||
default:
|
||||
throw ApplicationFailure.create({
|
||||
message: `Provider implementation for ${providerName} not found`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export interface GeneratedEmbedding {
|
||||
embedding: number[]
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
}
|
||||
|
||||
export interface GenerateEmbeddingParams {
|
||||
teamId: string
|
||||
assetId: string
|
||||
context: {
|
||||
agent: unknown
|
||||
asset: unknown
|
||||
dbProvider: unknown
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateEmbeddingActivity(params: GenerateEmbeddingParams) {
|
||||
return aiService.generateAssetEmbeddings(params.teamId, params.assetId)
|
||||
}
|
||||
export async function generateEmbeddingActivity(params: GenerateEmbeddingParams): Promise<{
|
||||
embeddings: GeneratedEmbedding[]
|
||||
usage: Usage
|
||||
}> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context properties are fetched as JSON from the DB activity
|
||||
const { agent, asset, dbProvider } = params.context as any
|
||||
|
||||
export async function getProjectAutofillFieldsActivity(projectId: string) {
|
||||
const fields = await metadataService.listProjectFields('', projectId)
|
||||
return fields.filter((f) => f.field.aiAutofill).map((f) => f.field)
|
||||
}
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
if (!config.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'embedding provider not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
if (!config.model) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'embedding model not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateAssetMetadataParams {
|
||||
assetId: string
|
||||
metadata: UpdateAssetMetadataRequest[]
|
||||
}
|
||||
if (!asset.mediaType) {
|
||||
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
||||
}
|
||||
|
||||
export async function updateAssetMetadataActivity(params: UpdateAssetMetadataParams) {
|
||||
return metadataService.updateAssetMetadata(params.assetId, params.metadata)
|
||||
}
|
||||
const p = providerFactory(config.provider, dbProvider.config as PrismaJson.AiProviderSettings)
|
||||
|
||||
export async function getCommentActivity(commentId: string) {
|
||||
return prisma.assetComment.findUnique({
|
||||
where: { id: commentId },
|
||||
include: { attachments: { include: { asset: { include: { storageKey: true } } } } },
|
||||
})
|
||||
const usage: Usage = {
|
||||
model: config.model,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
const isImage = asset.mediaType.startsWith('image/')
|
||||
const isVideo = asset.mediaType.startsWith('video/')
|
||||
|
||||
if (!isImage && !isVideo) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `unsupported media type for embeddings: ${asset.mediaType}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const key = asset.storageKey?.key
|
||||
if (!key) {
|
||||
throw ApplicationFailure.create({ message: 'asset has no key', nonRetryable: true })
|
||||
}
|
||||
|
||||
const { buffer: data } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
|
||||
|
||||
const results: GeneratedEmbedding[] = []
|
||||
|
||||
if (isImage) {
|
||||
const embVec = await p.generateImageEmbedding(config.model, data)
|
||||
results.push({ embedding: embVec })
|
||||
} else if (isVideo) {
|
||||
const tmpFile = path.join(os.tmpdir(), `video-${Date.now()}.mp4`)
|
||||
fs.writeFileSync(tmpFile, data)
|
||||
|
||||
try {
|
||||
const { stdout } = await execAsync(
|
||||
`ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${tmpFile}"`,
|
||||
)
|
||||
const duration = parseFloat(stdout.trim())
|
||||
if (isNaN(duration)) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'failed to parse video duration',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const chunkSize = 60.0
|
||||
for (let start = 0.0; start < duration; start += chunkSize) {
|
||||
let end = start + chunkSize
|
||||
if (end > duration) end = duration
|
||||
|
||||
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`)
|
||||
await execAsync(
|
||||
`ffmpeg -y -i "${tmpFile}" -ss ${start} -t ${end - start} -c copy "${chunkTmp}"`,
|
||||
)
|
||||
|
||||
const chunkData = fs.readFileSync(chunkTmp)
|
||||
fs.unlinkSync(chunkTmp)
|
||||
|
||||
try {
|
||||
const embVec = await p.generateVideoEmbedding(config.model, chunkData)
|
||||
results.push({ embedding: embVec, startTime: start, endTime: end })
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (e: any) {
|
||||
console.error(
|
||||
`failed to generate video embedding for chunk ${start}-${end}: ${e.message}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fs.unlinkSync(tmpFile)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
embeddings: results,
|
||||
usage,
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtractAiMetadataParams {
|
||||
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
updateCommentActivity,
|
||||
deleteCommentActivity,
|
||||
initializeAgentSessionActivity,
|
||||
getAgentChatContextActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
getEmbeddingContextActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
} from './db'
|
||||
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||
|
||||
@@ -186,4 +190,129 @@ describe('Database Activities', () => {
|
||||
throw new Error('Expected entry to be a message')
|
||||
}
|
||||
})
|
||||
|
||||
it('should support context-fetching and embedding database activities', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 't_ctx' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'p_ctx', teamId: team.id },
|
||||
})
|
||||
const sk = await prisma.storageKey.create({ data: { key: 'asset-key' } })
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-asset',
|
||||
type: 'file',
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
mediaType: 'image/png',
|
||||
storageKeyId: sk.id,
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- provider config requires broad any casting since it is defined as generic Json in Prisma schema
|
||||
config: { api: 'google', apiKey: 'key' } as any,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
config: {
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 1000,
|
||||
maxTokens: 1000,
|
||||
cost: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- model config requires broad any casting since it is defined as generic Json in Prisma schema
|
||||
} as any,
|
||||
},
|
||||
})
|
||||
|
||||
const botUser = await prisma.user.create({
|
||||
data: { name: 'Pirate Bot', email: 'bot@example.com', type: 'agent' },
|
||||
})
|
||||
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: botUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: botUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Test getAgentChatContextActivity
|
||||
const chatCtx = await getAgentChatContextActivity({ teamId: team.id, agentId: agent.id })
|
||||
expect(chatCtx.agent.id).toBe(agent.id)
|
||||
expect(chatCtx.dbProviders.length).toBe(1)
|
||||
expect(chatCtx.allowedDomains).toEqual([])
|
||||
|
||||
// Test getAgentAutofillContextActivity (needs an autofill agent)
|
||||
const autofillBot = await prisma.user.create({
|
||||
data: { name: 'Autofill Bot', email: 'autobot@example.com', type: 'agent' },
|
||||
})
|
||||
const autofillAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: autofillBot.id,
|
||||
teamId: team.id,
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
const autofillCtx = await getAgentAutofillContextActivity({ teamId: team.id })
|
||||
expect(autofillCtx.agent.id).toBe(autofillAgent.id)
|
||||
|
||||
// Test getEmbeddingContextActivity (needs an embedding agent)
|
||||
const embeddingBot = await prisma.user.create({
|
||||
data: { name: 'Embedding Bot', email: 'emb@example.com', type: 'agent' },
|
||||
})
|
||||
const embeddingAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: embeddingBot.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: embeddingBot.id, role: 'reviewer' },
|
||||
})
|
||||
const embCtx = await getEmbeddingContextActivity({ teamId: team.id, assetId: asset.id })
|
||||
expect(embCtx.agent.id).toBe(embeddingAgent.id)
|
||||
expect(embCtx.asset.id).toBe(asset.id)
|
||||
|
||||
// Test saveAssetEmbeddingsActivity
|
||||
const mockEmbedding = Array(1536).fill(0.1)
|
||||
await saveAssetEmbeddingsActivity({
|
||||
assetId: asset.id,
|
||||
embeddings: [{ embedding: mockEmbedding }],
|
||||
})
|
||||
const dbEmbeddings = await prisma.assetEmbedding.findMany({
|
||||
where: { assetId: asset.id },
|
||||
})
|
||||
expect(dbEmbeddings.length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { prisma } from '@/db'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
import type { AgentMessage, SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||
import { ulid } from 'ulid'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { UpdateAssetMetadataRequest } from '@/dtos/metadata'
|
||||
import { WorkflowTaskStatus, AssetStatus } from '@/generated/prisma/client'
|
||||
|
||||
export interface InitializeAgentSessionParams {
|
||||
teamId: string
|
||||
@@ -207,7 +211,9 @@ export async function createCommentActivity(params: CreateCommentParams) {
|
||||
where: { id: params.assetId },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!asset || !asset.project) throw new Error('asset or project not found')
|
||||
if (!asset || !asset.project) {
|
||||
throw ApplicationFailure.create({ message: 'asset or project not found', nonRetryable: true })
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
|
||||
// Ensure user exists for agent
|
||||
@@ -278,3 +284,329 @@ export async function updateCommentActivity(params: UpdateCommentParams) {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// New Context-Fetching and Embedding DB Activities
|
||||
// ==========================================
|
||||
|
||||
export interface GetAgentChatContextParams {
|
||||
teamId: string
|
||||
agentId: string
|
||||
}
|
||||
|
||||
export async function getAgentChatContextActivity(params: GetAgentChatContextParams) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
if (!team) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true })
|
||||
}
|
||||
|
||||
const agent = await prisma.agent.findUnique({
|
||||
where: { id: params.agentId },
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `agent ${params.agentId} not found`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (!agent.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'agent has no provider configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
if (!agent.modelRef) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'agent has no model configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const providerName = agent.provider.name
|
||||
|
||||
// Fetch the required provider configuration from database
|
||||
const dbProviders = await prisma.provider.findMany({
|
||||
where: { teamId: params.teamId, name: providerName },
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await prisma.skill.findMany({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.allowedDomains || []
|
||||
|
||||
return {
|
||||
agent,
|
||||
dbProviders,
|
||||
teamSkills,
|
||||
allowedDomains,
|
||||
}
|
||||
}
|
||||
|
||||
export interface GetAgentAutofillContextParams {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export async function getAgentAutofillContextActivity(params: GetAgentAutofillContextParams) {
|
||||
const agent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
teamId: params.teamId,
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'no autofill agent found for team',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
if (!team) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true })
|
||||
}
|
||||
|
||||
// Find provider/model configuration
|
||||
const agentWithDetails = await prisma.agent.findUnique({
|
||||
where: { id: agent.id },
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
},
|
||||
})
|
||||
if (!agentWithDetails) {
|
||||
throw ApplicationFailure.create({ message: `agent ${agent.id} not found`, nonRetryable: true })
|
||||
}
|
||||
if (!agentWithDetails.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'agent has no provider configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
if (!agentWithDetails.modelRef) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'agent has no model configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const providerName = agentWithDetails.provider.name
|
||||
|
||||
// Fetch the required provider configuration from database
|
||||
const dbProviders = await prisma.provider.findMany({
|
||||
where: { teamId: params.teamId, name: providerName },
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await prisma.skill.findMany({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.allowedDomains || []
|
||||
|
||||
return {
|
||||
agent: agentWithDetails,
|
||||
dbProviders,
|
||||
teamSkills,
|
||||
allowedDomains,
|
||||
}
|
||||
}
|
||||
|
||||
export interface GetEmbeddingContextParams {
|
||||
teamId: string
|
||||
assetId: string
|
||||
}
|
||||
|
||||
export async function getEmbeddingContextActivity(params: GetEmbeddingContextParams) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
if (!team) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true })
|
||||
}
|
||||
|
||||
const agent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId: params.teamId } } },
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'embedding feature is disabled or agent not found',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
if (!config.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'embedding provider not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
if (!config.model) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'embedding model not configured',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
if (!asset) {
|
||||
throw ApplicationFailure.create({ message: 'failed to get asset', nonRetryable: true })
|
||||
}
|
||||
if (!asset.mediaType) {
|
||||
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
||||
}
|
||||
|
||||
const dbProvider = await prisma.provider.findFirst({
|
||||
where: { teamId: params.teamId, name: config.provider },
|
||||
})
|
||||
if (!dbProvider) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Provider ${config.provider} not found in database`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
agent,
|
||||
asset,
|
||||
dbProvider,
|
||||
}
|
||||
}
|
||||
|
||||
export interface SaveAssetEmbeddingsParams {
|
||||
assetId: string
|
||||
embeddings: Array<{
|
||||
embedding: number[]
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
}>
|
||||
}
|
||||
|
||||
export async function saveAssetEmbeddingsActivity(params: SaveAssetEmbeddingsParams) {
|
||||
for (const item of params.embeddings) {
|
||||
const embVec = JSON.stringify(item.embedding)
|
||||
if (item.startTime !== undefined && item.endTime !== undefined) {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
||||
`
|
||||
} else {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, NOW())
|
||||
`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// Moved Database Activities
|
||||
// ==========================================
|
||||
|
||||
export async function getAssetActivity(assetId: string) {
|
||||
return prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function getCommentActivity(commentId: string) {
|
||||
return prisma.assetComment.findUnique({
|
||||
where: { id: commentId },
|
||||
include: { attachments: { include: { asset: { include: { storageKey: true } } } } },
|
||||
})
|
||||
}
|
||||
|
||||
export async function getProjectAutofillFieldsActivity(projectId: string) {
|
||||
const fields = await metadataService.listProjectFields('', projectId)
|
||||
return fields.filter((f) => f.field.aiAutofill).map((f) => f.field)
|
||||
}
|
||||
|
||||
export interface UpdateAssetMetadataParams {
|
||||
assetId: string
|
||||
metadata: UpdateAssetMetadataRequest[]
|
||||
}
|
||||
|
||||
export async function updateAssetMetadataActivity(params: UpdateAssetMetadataParams) {
|
||||
return metadataService.updateAssetMetadata(params.assetId, params.metadata)
|
||||
}
|
||||
|
||||
export interface UpdateTaskStatusParams {
|
||||
taskId: string
|
||||
status: WorkflowTaskStatus
|
||||
output?: unknown
|
||||
}
|
||||
|
||||
export async function updateTaskStatusActivity(params: UpdateTaskStatusParams): Promise<void> {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateAssetStatusParams {
|
||||
assetId: string
|
||||
status: AssetStatus
|
||||
}
|
||||
|
||||
export async function updateAssetStatusActivity(params: UpdateAssetStatusParams): Promise<void> {
|
||||
await prisma.asset.update({
|
||||
where: { id: params.assetId },
|
||||
data: { status: params.status },
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateTaskUsageParams {
|
||||
taskId: string
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
model: string
|
||||
}
|
||||
|
||||
export async function updateTaskUsageActivity(params: UpdateTaskUsageParams): Promise<void> {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
inputTokens: params.inputTokens,
|
||||
outputTokens: params.outputTokens,
|
||||
model: params.model,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import {
|
||||
updateTaskStatusActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskUsageActivity,
|
||||
} from './task'
|
||||
import { updateTaskStatusActivity, updateAssetStatusActivity, updateTaskUsageActivity } from './db'
|
||||
import { WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@/generated/prisma/client'
|
||||
|
||||
describe('Task Activities', () => {
|
||||
|
||||
@@ -1,52 +1,3 @@
|
||||
import { prisma } from '@/db'
|
||||
import { WorkflowTaskStatus, AssetStatus } from '@/generated/prisma/client'
|
||||
|
||||
export interface UpdateTaskStatusParams {
|
||||
taskId: string
|
||||
status: WorkflowTaskStatus
|
||||
output?: unknown
|
||||
}
|
||||
|
||||
export async function updateTaskStatusActivity(params: UpdateTaskStatusParams): Promise<void> {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateAssetStatusParams {
|
||||
assetId: string
|
||||
status: AssetStatus
|
||||
}
|
||||
|
||||
export async function updateAssetStatusActivity(params: UpdateAssetStatusParams): Promise<void> {
|
||||
await prisma.asset.update({
|
||||
where: { id: params.assetId },
|
||||
data: { status: params.status },
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateTaskUsageParams {
|
||||
taskId: string
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
model: string
|
||||
}
|
||||
|
||||
export async function updateTaskUsageActivity(params: UpdateTaskUsageParams): Promise<void> {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
inputTokens: params.inputTokens,
|
||||
outputTokens: params.outputTokens,
|
||||
model: params.model,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function getTranscodeWorkerQueueActivity(): Promise<string> {
|
||||
return 'transcode_queue'
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@ import { prisma } from '@/db'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import { Executor } from './executor'
|
||||
import { aiTranscriptionMedia } from './workflows/ai-transcription'
|
||||
import { aiEmbeddingMedia } from './workflows/ai-embedding'
|
||||
import { aiAutofillMedia } from './workflows/ai-autofill'
|
||||
import { aiChat } from './workflows/ai-chat'
|
||||
import { agentEmbeddingMedia } from './workflows/agent-embedding'
|
||||
import { agentAutofillMedia } from './workflows/agent-autofill'
|
||||
import { agentChat } from './workflows/agent-chat'
|
||||
import { transcodeMedia } from '@/transcode/workflows/transcode'
|
||||
import { activities } from './activities/index'
|
||||
import { logger } from '@/logger'
|
||||
@@ -87,13 +87,13 @@ export class LocalExecutor implements Executor {
|
||||
await aiTranscriptionMedia(task)
|
||||
break
|
||||
case WorkflowTaskType.ai_embedding:
|
||||
await aiEmbeddingMedia(task)
|
||||
await agentEmbeddingMedia(task)
|
||||
break
|
||||
case WorkflowTaskType.ai_metadata_autofill:
|
||||
await aiAutofillMedia(task)
|
||||
await agentAutofillMedia(task)
|
||||
break
|
||||
case WorkflowTaskType.chat:
|
||||
await aiChat(task)
|
||||
await agentChat(task)
|
||||
break
|
||||
case WorkflowTaskType.transcode:
|
||||
await transcodeMedia(task)
|
||||
|
||||
@@ -20,13 +20,13 @@ export class TemporalExecutor implements Executor {
|
||||
workflowName = 'aiTranscriptionWorkflow'
|
||||
break
|
||||
case WorkflowTaskType.ai_embedding:
|
||||
workflowName = 'aiEmbeddingWorkflow'
|
||||
workflowName = 'agentEmbeddingWorkflow'
|
||||
break
|
||||
case WorkflowTaskType.ai_metadata_autofill:
|
||||
workflowName = 'aiAutofillWorkflow'
|
||||
workflowName = 'agentAutofillWorkflow'
|
||||
break
|
||||
case WorkflowTaskType.chat:
|
||||
workflowName = 'aiChatWorkflow'
|
||||
workflowName = 'agentChatWorkflow'
|
||||
break
|
||||
case WorkflowTaskType.transcode:
|
||||
workflowName = 'transcodeWorkflow'
|
||||
|
||||
@@ -139,4 +139,49 @@ describe('WorkflowService', () => {
|
||||
// Even if it fails due to missing API keys, the fact that it's no longer 'pending' means the workflow was triggered.
|
||||
expect(finishedTask?.status).not.toBe(WorkflowTaskStatus.pending)
|
||||
}, 15000)
|
||||
|
||||
it('should propagate ApplicationFailure correctly in local executor', async () => {
|
||||
// Creating an ai_embedding task without any embedding agent configured for the team
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Failure Team' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Failure Project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.png',
|
||||
storageKey: { create: { key: 'test/failure-test.png' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
project: { connect: { id: project.id } },
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
let finishedTask = null
|
||||
for (let i = 0; i < 20; i++) {
|
||||
finishedTask = await prisma.workflowTask.findUnique({
|
||||
where: { id: task.id },
|
||||
})
|
||||
if (finishedTask?.status === WorkflowTaskStatus.failed) {
|
||||
break
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 500))
|
||||
}
|
||||
|
||||
expect(finishedTask?.status).toBe(WorkflowTaskStatus.failed)
|
||||
expect((finishedTask?.output as Record<string, unknown>)?.error).toBe(
|
||||
'embedding feature is disabled or agent not found',
|
||||
)
|
||||
}, 15000)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentAutofillMedia } from './agent-autofill'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async () => {
|
||||
const actual = await vi.importActual('@/workflow/workflow-utils')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Autofill Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent autofill workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractAiMetadataActivity',
|
||||
}),
|
||||
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getProjectAutofillFieldsActivity',
|
||||
}),
|
||||
getAgentAutofillContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentAutofillContextActivity',
|
||||
}),
|
||||
autofillAiActivity: Object.assign(vi.fn(), { _activityName: 'autofillAiActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
updateAssetMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMetadataActivity',
|
||||
}),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
}
|
||||
|
||||
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.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
|
||||
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.getAgentAutofillContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: '{"f1":"val"}',
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_metadata_autofill',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
},
|
||||
})
|
||||
|
||||
await agentAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import {
|
||||
getActivities,
|
||||
@@ -7,12 +8,13 @@ import {
|
||||
TaskQueueTranscode,
|
||||
} from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
extractAiMetadataActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
autofillAiActivity,
|
||||
updateTaskUsageActivity,
|
||||
updateAssetMetadataActivity,
|
||||
@@ -36,12 +38,12 @@ export async function aiAutofillMedia(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
|
||||
|
||||
@@ -49,7 +51,7 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !asset.project || !key) {
|
||||
throw new Error('Asset or project not found')
|
||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
const projectId = asset.project.id
|
||||
@@ -107,6 +109,11 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
// 3b. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getAgentAutofillContextActivity, {
|
||||
teamId,
|
||||
})
|
||||
|
||||
// 4. Call AI Service
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
@@ -118,6 +125,7 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
config: f.config as unknown as PrismaJson.FieldConfig,
|
||||
description: f.description,
|
||||
})),
|
||||
context,
|
||||
})
|
||||
|
||||
if (aiResult.usage) {
|
||||
@@ -159,7 +167,7 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
status: 'completed',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiAutofillMedia failed for task ${task.id}:`, err)
|
||||
console.error(`AgentAutofillMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
@@ -191,4 +199,4 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export const aiAutofillWorkflow = aiAutofillMedia
|
||||
export const agentAutofillWorkflow = agentAutofillMedia
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentChat } from './agent-chat'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async () => {
|
||||
const actual = await vi.importActual('@/workflow/workflow-utils')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Chat Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent chat workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getCommentActivity: Object.assign(vi.fn(), { _activityName: 'getCommentActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
initializeAgentSessionActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'initializeAgentSessionActivity',
|
||||
}),
|
||||
getAgentChatContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentChatContextActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
agentChatActivity: Object.assign(vi.fn(), { _activityName: 'agentChatActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
|
||||
}
|
||||
|
||||
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')
|
||||
mockActivities.getAgentChatContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.agentChatActivity.mockResolvedValue({
|
||||
text: 'arr matey!',
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { userCommentId: 'c1', agentId: 'b1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
expect(mockActivities.getAgentChatContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import {
|
||||
executeActivity,
|
||||
@@ -6,12 +7,13 @@ import {
|
||||
TaskQueueDb,
|
||||
} from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
getCommentActivity,
|
||||
aiChatActivity,
|
||||
getAgentChatContextActivity,
|
||||
agentChatActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
updateTaskUsageActivity,
|
||||
@@ -29,23 +31,37 @@ export async function aiChat(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 ApplicationFailure.create({ message: 'Task payload is missing', nonRetryable: true })
|
||||
}
|
||||
|
||||
let sessionId = payload?.sessionId || payload?.session_id
|
||||
const agentId = payload.agent?.agentId
|
||||
if (!agentId) {
|
||||
throw ApplicationFailure.create({ message: 'agentId missing in payload', nonRetryable: true })
|
||||
}
|
||||
|
||||
let sessionId = payload.agent?.sessionId
|
||||
|
||||
// 1. Get User Comment
|
||||
const userCommentId = payload?.userCommentId
|
||||
if (!userCommentId) throw new Error('userCommentId missing in payload')
|
||||
const userCommentId = payload.agent?.userCommentId
|
||||
if (!userCommentId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'userCommentId missing in payload',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId)
|
||||
if (!userComment) throw new Error('User comment not found')
|
||||
if (!userComment) {
|
||||
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
|
||||
}
|
||||
|
||||
// 2. Create Placeholder Comment
|
||||
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
|
||||
assetId: task.assetId,
|
||||
message: '__CHAT__',
|
||||
sessionId: sessionId || 'pending',
|
||||
agentId: payload?.agentId,
|
||||
agentId: agentId,
|
||||
replyToId: userComment.replyToId ?? userComment.id,
|
||||
})
|
||||
placeholderCommentId = placeholder.id
|
||||
@@ -53,7 +69,7 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
// 3. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
throw new Error('Asset or project not found')
|
||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
|
||||
@@ -61,20 +77,24 @@ export async function aiChat(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: 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,7 +107,7 @@ export async function aiChat(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__.`
|
||||
@@ -103,17 +123,18 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, aiChatActivity, {
|
||||
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,
|
||||
})
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
@@ -146,7 +167,7 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
output: { sessionId: aiResult.sessionId },
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiChat failed for task ${task.id}:`, err)
|
||||
console.error(`AgentChat failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
@@ -175,4 +196,4 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export const aiChatWorkflow = aiChat
|
||||
export const agentChatWorkflow = agentChat
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentEmbeddingMedia } from './agent-embedding'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async () => {
|
||||
const actual = await vi.importActual('@/workflow/workflow-utils')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Embedding Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent embedding workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getEmbeddingContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getEmbeddingContextActivity',
|
||||
}),
|
||||
generateEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateEmbeddingActivity',
|
||||
}),
|
||||
saveAssetEmbeddingsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'saveAssetEmbeddingsActivity',
|
||||
}),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
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] }],
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
teamId: 't1',
|
||||
},
|
||||
})
|
||||
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.getEmbeddingContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+31
-11
@@ -1,10 +1,13 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '../workflow-utils'
|
||||
|
||||
export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getEmbeddingContextActivity,
|
||||
generateEmbeddingActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
updateTaskUsageActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
@@ -21,16 +24,24 @@ export async function aiEmbeddingMedia(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
|
||||
|
||||
if (!task.teamId) throw new Error('Task has no teamId')
|
||||
if (!task.teamId) {
|
||||
throw ApplicationFailure.create({ message: 'Task has no teamId', nonRetryable: true })
|
||||
}
|
||||
|
||||
// 1. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getEmbeddingContextActivity, {
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
})
|
||||
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
@@ -38,15 +49,24 @@ export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
const result = await executeActivity(agentWorkerQueue, generateEmbeddingActivity, {
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
context,
|
||||
})
|
||||
|
||||
// Save computed embeddings
|
||||
if (result.embeddings.length > 0) {
|
||||
await executeActivity(TaskQueueDb, saveAssetEmbeddingsActivity, {
|
||||
assetId: task.assetId,
|
||||
embeddings: result.embeddings,
|
||||
})
|
||||
}
|
||||
|
||||
// Update Usage
|
||||
if (result) {
|
||||
if (result.usage) {
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: result.inputTokens,
|
||||
outputTokens: result.outputTokens,
|
||||
model: result.model,
|
||||
inputTokens: result.usage.inputTokens,
|
||||
outputTokens: result.usage.outputTokens,
|
||||
model: result.usage.model,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -64,7 +84,7 @@ export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
status: 'completed',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiEmbeddingMedia failed for task ${task.id}:`, err)
|
||||
console.error(`AgentEmbeddingMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
@@ -88,4 +108,4 @@ export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export const aiEmbeddingWorkflow = aiEmbeddingMedia
|
||||
export const agentEmbeddingWorkflow = agentEmbeddingMedia
|
||||
@@ -1,203 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiAutofillMedia } from './ai-autofill'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AIAutofill Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractAiMetadataActivity',
|
||||
}),
|
||||
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getProjectAutofillFieldsActivity',
|
||||
}),
|
||||
autofillAiActivity: Object.assign(vi.fn(), { _activityName: 'autofillAiActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
updateAssetMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMetadataActivity',
|
||||
}),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/test.mp4',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
})
|
||||
|
||||
it('should process AI autofill successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-1-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
storageKey: { key: 'test.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
project: { id: 'proj-1', teamId: 'team-1' },
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['frame1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
||||
{ id: 'field-1', config: { type: 'text', name: 'Field 1' } },
|
||||
])
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: JSON.stringify({ 'field-1': 'Extracted Value' }),
|
||||
usage: { inputTokens: 10, outputTokens: 5, model: 'gpt-4v' },
|
||||
})
|
||||
|
||||
await aiAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__AUTOFILL__',
|
||||
sessionId: 'task-1',
|
||||
agentId: 'default',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateAssetMetadataActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
metadata: [{ key: 'field-1', value: 'Extracted Value' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('should use agentId from payload if provided', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: { agentId: 'real-agent-id' },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-1-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
storageKey: { key: 'test.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
project: { id: 'proj-1', teamId: 'team-1' },
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['frame1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
||||
{ id: 'field-1', config: { type: 'text', name: 'Field 1' } },
|
||||
])
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: JSON.stringify({ 'field-1': 'Extracted Value' }),
|
||||
usage: { inputTokens: 10, outputTokens: 5, model: 'gpt-4v' },
|
||||
})
|
||||
|
||||
await aiAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__AUTOFILL__',
|
||||
sessionId: 'task-1',
|
||||
agentId: 'real-agent-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update task status with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-fail-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-err' })
|
||||
mockActivities.getAssetActivity.mockRejectedValue(new Error('Asset missing'))
|
||||
|
||||
await expect(aiAutofillMedia(task)).rejects.toThrow('Asset missing')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('failed'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'Asset missing' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,327 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiChat } from './ai-chat'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AIChat Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getCommentActivity: Object.assign(vi.fn(), { _activityName: 'getCommentActivity' }),
|
||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractAiMetadataActivity',
|
||||
}),
|
||||
aiChatActivity: Object.assign(vi.fn(), { _activityName: 'aiChatActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
|
||||
initializeAgentSessionActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'initializeAgentSessionActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
|
||||
mockActivities.initializeAgentSessionActivity.mockResolvedValue('mock-session-id')
|
||||
})
|
||||
|
||||
it('should process AI chat successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
projectId: 'proj-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'test.png',
|
||||
mediaType: 'image/png',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'comment-1',
|
||||
message: 'Hello AI',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-1',
|
||||
})
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: 'Hello Human',
|
||||
usage: { inputTokens: 10, outputTokens: 20, model: 'gpt-4' },
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__CHAT__',
|
||||
sessionId: 'pending',
|
||||
agentId: 'bot-1',
|
||||
replyToId: 'comment-1',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-1',
|
||||
message: 'Hello Human',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
inputTokens: 10,
|
||||
outputTokens: 20,
|
||||
model: 'gpt-4',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: { sessionId: undefined },
|
||||
})
|
||||
})
|
||||
|
||||
it('should attach AI response to thread root if triggering comment is a reply', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-nested',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'reply-1',
|
||||
agentId: 'bot-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-nested',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'reply-1',
|
||||
replyToId: 'root-comment-id',
|
||||
message: 'Nested reply message',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-nested' })
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: 'AI response to root',
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__CHAT__',
|
||||
sessionId: 'pending',
|
||||
agentId: 'bot-1',
|
||||
replyToId: 'root-comment-id', // MUST be root, not reply-1
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update placeholder with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-err',
|
||||
})
|
||||
|
||||
mockActivities.getAssetActivity.mockRejectedValue(new Error('DB Down'))
|
||||
|
||||
await expect(aiChat(task)).rejects.toThrow('DB Down')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('error'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'DB Down' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should pass explicitMention payload parameter and format instruction when true', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-explicit',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
explicitMention: true,
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-explicit',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'comment-1',
|
||||
message: 'Hello AI',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-1',
|
||||
})
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: 'Hello Human',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt-4' },
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.aiChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
explicitMention: true,
|
||||
agentsInstruction: expect.stringContaining('MUST reply to this message'),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should delete placeholder comment when AI response is __NO_REPLY__', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-no-reply',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
explicitMention: false,
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-no-reply',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'comment-1',
|
||||
message: 'Hello AI',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-delete-me',
|
||||
})
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: ' __NO_REPLY__ ',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt-4' },
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.deleteCommentActivity).toHaveBeenCalledWith('placeholder-delete-me')
|
||||
expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,179 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiEmbeddingMedia } from './ai-embedding'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '../workflow-utils'
|
||||
|
||||
vi.mock('../workflow-utils', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AIEmbedding Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
generateEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateEmbeddingActivity',
|
||||
}),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
|
||||
})
|
||||
|
||||
it('should generate embeddings successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
teamId: 'team-1',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
await aiEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__EMBEDDING__',
|
||||
sessionId: 'task-1',
|
||||
agentId: 'default',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-1',
|
||||
message: expect.stringContaining('successfully'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
})
|
||||
})
|
||||
|
||||
it('should use agentId from payload if provided', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId: 'team-1',
|
||||
output: null,
|
||||
payload: { agentId: 'real-agent-id' },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
await aiEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__EMBEDDING__',
|
||||
sessionId: 'task-1',
|
||||
agentId: 'real-agent-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update task status with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
teamId: 'team-1',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-err' })
|
||||
mockActivities.generateEmbeddingActivity.mockRejectedValue(new Error('Embedding error'))
|
||||
|
||||
await expect(aiEmbeddingMedia(task)).rejects.toThrow('Embedding error')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('failed'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'Embedding error' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import {
|
||||
getActivities,
|
||||
@@ -31,12 +32,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
|
||||
|
||||
@@ -44,7 +45,7 @@ export async function aiTranscriptionMedia(task: WorkflowTask): Promise<void> {
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) {
|
||||
throw new Error('Asset not found')
|
||||
throw ApplicationFailure.create({ message: 'Asset not found', nonRetryable: true })
|
||||
}
|
||||
|
||||
// 2. Extract Audio (Requires FFmpeg)
|
||||
@@ -67,7 +68,10 @@ export async function aiTranscriptionMedia(task: WorkflowTask): Promise<void> {
|
||||
})
|
||||
|
||||
if (generatedFiles.length === 0) {
|
||||
throw new Error('Failed to extract audio for transcription')
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Failed to extract audio for transcription',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Simulate work
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export * from './ai-transcription'
|
||||
export * from './ai-embedding'
|
||||
export * from './ai-autofill'
|
||||
export * from './ai-chat'
|
||||
export * from './agent-embedding'
|
||||
export * from './agent-autofill'
|
||||
export * from './agent-chat'
|
||||
export * from '@/transcode/workflows/transcode'
|
||||
|
||||
Reference in New Issue
Block a user