initial commit

This commit is contained in:
yiling
2026-05-19 16:05:09 +08:00
commit 9cad96210c
370 changed files with 131609 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { setupTestDbHooks } from '@/db-test-hooks'
import { aiChatActivity } from './agent'
import { agentExecutor } from '../executor'
vi.mock('../executor', () => ({
agentExecutor: {
chatWithAgent: vi.fn(),
},
}))
describe('Agent Activities', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should call aiChatActivity', async () => {
vi.mocked(agentExecutor.chatWithAgent).mockResolvedValue({
text: 'AI response',
usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' },
sessionId: 'mock-session-id',
})
await aiChatActivity({
teamId: 't1',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
})
expect(agentExecutor.chatWithAgent).toHaveBeenCalledWith(
't1',
'b1',
'Hi',
[],
'',
undefined,
undefined,
)
})
})
+70
View File
@@ -0,0 +1,70 @@
import { agentExecutor, AutofillField } from '../executor'
import { prisma } from '@/db'
export interface AutofillAiParams {
teamId: string
images: string[]
fields: AutofillField[]
}
export async function autofillAiActivity(params: AutofillAiParams) {
const prompt = 'Analyze the provided images and extract metadata.'
return agentExecutor.autofill(params.teamId, prompt, params.images, params.fields)
}
export interface AiChatParams {
teamId: string
agentId: string
message: string
imageUrls: string[]
projectId: string
folderId: string
agentsInstruction?: string
sessionId?: string
userId?: string
}
export async function aiChatActivity(params: AiChatParams) {
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
return agentExecutor.chatWithAgent(
params.teamId,
params.agentId,
cleanMessage,
params.imageUrls,
params.agentsInstruction || '',
params.sessionId,
params.userId,
)
}
export interface CreateCommentParams {
assetId: string
message: string
isAi?: boolean
agentId?: string | null
replyToId?: string | null
}
export async function createCommentActivity(params: CreateCommentParams) {
return prisma.assetComment.create({
data: {
assetId: params.assetId,
message: params.message,
isAi: params.isAi ?? false,
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
replyToId: params.replyToId,
},
})
}
export interface UpdateCommentParams {
commentId: string
message: string
}
export async function updateCommentActivity(params: UpdateCommentParams) {
return prisma.assetComment.update({
where: { id: params.commentId },
data: { message: params.message },
})
}
+146
View File
@@ -0,0 +1,146 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { DatabaseSessionManager } from './database-session-manager'
import { s3Service } from '@/services/s3/s3'
vi.mock('@/services/s3/s3', () => ({
s3Service: {
getObject: vi.fn(),
},
}))
describe('DatabaseSessionManager', () => {
setupTestDbHooks()
let agentId: string
beforeEach(async () => {
const user = await prisma.user.create({
data: { name: 'Test Agent', email: 'agent@test.com', type: 'agent' },
})
await prisma.agent.create({
data: {
id: user.id,
type: 'chat',
config: { provider: 'openai', model: 'gpt-4o' },
},
})
agentId = user.id
})
it('creates a new session in DB', async () => {
const manager = await DatabaseSessionManager.create({ agentId })
const sessionId = manager.getDbSessionId()
expect(sessionId).toBeDefined()
const session = await prisma.agentSession.findUnique({ where: { id: sessionId } })
expect(session).toBeDefined()
expect(session?.agentId).toBe(agentId)
})
it('persists message entries to DB', async () => {
const manager = await DatabaseSessionManager.create({ agentId })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
manager.appendMessage({ role: 'user', content: 'Hello' } as any)
await manager.waitForSync()
const sessionId = manager.getDbSessionId()
const entries = await prisma.agentSessionEntry.findMany({ where: { sessionId } })
expect(entries).toHaveLength(1)
// In simplified schema, type/parentId are part of the entry object
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const entry = entries[0].entry as any
expect(entry.type).toBe('message')
expect(entry.message.content).toBe('Hello')
const session = await prisma.agentSession.findUnique({ where: { id: sessionId } })
expect(session?.leafId).toBe(entries[0].id)
})
it('loads existing session from DB', async () => {
const manager1 = await DatabaseSessionManager.create({ agentId })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msgId = manager1.appendMessage({ role: 'user', content: 'Message 1' } as any)
await manager1.waitForSync()
const sessionId = manager1.getDbSessionId()
const manager2 = await DatabaseSessionManager.create({ agentId, sessionId })
expect(manager2.getDbSessionId()).toBe(sessionId)
expect(manager2.getLeafId()).toBe(msgId)
const context = manager2.buildSessionContext()
expect(context.messages).toHaveLength(1)
expect(context.messages[0].content).toBe('Message 1')
})
it('re-injects image data from S3', async () => {
const session = await prisma.agentSession.create({
data: { agentId, cwd: '/tmp' },
})
const entry = {
id: 'e1',
type: 'message',
message: {
role: 'toolResult',
content: [
{ type: 'image', data: '__S3_DATA__' },
],
details: { sourceKeys: ['key1'] },
},
}
await prisma.agentSessionEntry.create({
data: {
id: entry.id,
sessionId: session.id,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
entry: entry as any,
},
})
vi.mocked(s3Service.getObject).mockResolvedValue({
buffer: Buffer.from('fake-image-data'),
contentType: 'image/png',
})
const manager = await DatabaseSessionManager.create({ agentId, sessionId: session.id })
const context = manager.buildSessionContext()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const reInjectedMessage = context.messages[0] as any
expect(reInjectedMessage.content[0].data).toBe(Buffer.from('fake-image-data').toString('base64'))
expect(s3Service.getObject).toHaveBeenCalledWith(expect.any(String), 'key1')
})
it('handles branching', async () => {
const manager = await DatabaseSessionManager.create({ agentId })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const m1Id = manager.appendMessage({ role: 'user', content: 'M1' } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
manager.appendMessage({ role: 'assistant', content: 'A1' } as any)
await manager.waitForSync()
// Branch from M1
manager.branch(m1Id)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const m2Id = manager.appendMessage({ role: 'user', content: 'M2' } as any)
await manager.waitForSync()
const sessionId = manager.getDbSessionId()
const entries = await prisma.agentSessionEntry.findMany({ where: { sessionId } })
expect(entries).toHaveLength(3)
const m2Entry = entries.find((e) => e.id === m2Id)
// parentId is now inside the entry object
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((m2Entry?.entry as any).parentId).toBe(m1Id)
const context = manager.buildSessionContext()
expect(context.messages).toHaveLength(2)
expect(context.messages[0].content).toBe('M1')
expect(context.messages[1].content).toBe('M2')
})
})
+136
View File
@@ -0,0 +1,136 @@
import { prisma } from '@/db'
import { s3Service } from '@/services/s3/s3'
import { SessionEntry, SessionManager } from '@mariozechner/pi-coding-agent'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export class DatabaseSessionManager extends (SessionManager as any) {
private dbSessionId: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private writeQueue: Promise<any> = Promise.resolve()
private constructor(sessionId: string, cwd: string) {
super(cwd, '', undefined, false) // persist = false, we handle it manually
this.dbSessionId = sessionId
}
static async create(params: {
agentId: string
userId?: string
sessionId?: string
cwd?: string
}): Promise<DatabaseSessionManager> {
const sessionId = params.sessionId
const cwd = params.cwd || process.cwd()
if (sessionId) {
const session = await prisma.agentSession.findUnique({
where: { id: sessionId },
include: { entries: { orderBy: { id: 'asc' } } },
})
if (!session) {
throw new Error(`Session ${sessionId} not found`)
}
const manager = new DatabaseSessionManager(sessionId, session.cwd)
// Load entries into in-memory SessionManager
for (const e of session.entries) {
const entry = e.entry
// Dynamically re-inject image data if it was stripped
if (entry.type === 'message' && entry.message.role === 'toolResult') {
const msg = entry.message
const details = msg.details as { sourceKeys?: string[] } | undefined
if (Array.isArray(msg.content) && details?.sourceKeys) {
const sourceKeys = details.sourceKeys
let keyIdx = 0
for (const item of msg.content) {
if (item.type === 'image' && item.data === '__S3_DATA__' && sourceKeys[keyIdx]) {
const key = sourceKeys[keyIdx]
try {
const { buffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
item.data = buffer.toString('base64')
} catch (err) {
console.error(`Failed to re-inject image data for key ${key}:`, err)
}
keyIdx++
}
}
}
}
manager._appendEntry(entry, false) // false to avoid re-saving
}
return manager
} else {
const session = await prisma.agentSession.create({
data: {
agentId: params.agentId,
userId: params.userId,
cwd: cwd,
},
})
return new DatabaseSessionManager(session.id, cwd)
}
}
// Override _appendEntry to save to database
// Note: we use (manager as any)._appendEntry = ... in static factory if needed,
// but since we extend it, we can just define it here.
// We need to match the signature of the base class.
protected _appendEntry(entry: SessionEntry, shouldSave = true) {
// Call super._appendEntry (which is private, so we use the prototype)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const superAppendEntry = (SessionManager.prototype as any)['_appendEntry']
superAppendEntry.call(this, entry)
if (shouldSave) {
this.saveEntryToDb(entry)
}
}
private saveEntryToDb(entry: SessionEntry) {
this.writeQueue = this.writeQueue.then(async () => {
try {
// Deep clone to avoid stripping data from the in-memory session manager
const strippedEntry = JSON.parse(JSON.stringify(entry)) as SessionEntry
// Strip image data before saving to DB
if (strippedEntry.type === 'message' && strippedEntry.message.role === 'toolResult') {
const msg = strippedEntry.message
const details = msg.details as { sourceKeys?: string[] } | undefined
if (Array.isArray(msg.content) && details?.sourceKeys) {
const sourceKeys = details.sourceKeys
let keyIdx = 0
msg.content.forEach((item) => {
if (item.type === 'image' && sourceKeys[keyIdx]) {
item.data = '__S3_DATA__'
keyIdx++
}
})
}
}
await prisma.agentSessionEntry.create({
data: {
id: strippedEntry.id,
sessionId: this.dbSessionId,
entry: strippedEntry,
},
})
await prisma.agentSession.update({
where: { id: this.dbSessionId },
data: { leafId: strippedEntry.id },
})
} catch (err) {
console.error('Failed to save session entry to DB:', err)
}
})
}
async waitForSync() {
await this.writeQueue
}
getDbSessionId() {
return this.dbSessionId
}
}
+250
View File
@@ -0,0 +1,250 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { agentExecutor, type AutofillField } from './executor'
import * as piAgent from '@mariozechner/pi-coding-agent'
vi.mock('@mariozechner/pi-coding-agent', async () => {
const actual = await vi.importActual('@mariozechner/pi-coding-agent')
return {
...actual,
createAgentSession: vi.fn(),
}
})
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('AgentExecutor', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('autofills with agent', async () => {
const team = await prisma.team.create({
data: {
name: 'Autofill Team',
},
})
const provider = await prisma.provider.create({
data: {
name: 'openai',
teamId: team.id,
config: mockProviderConfig,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gpt-4',
name: 'GPT-4',
providerId: provider.id,
config: mockModelConfig,
},
})
await prisma.user.create({
data: {
name: 'Autofiller',
email: `autofiller-${Date.now()}@shumai.ai`,
type: 'agent',
agent: {
create: {
type: 'autofill',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: {
provider: 'openai',
model: 'gpt-4',
},
},
},
teamMembers: {
create: {
teamId: team.id,
role: 'reviewer',
},
},
},
})
const mockSession = {
sendUserMessage: vi.fn().mockImplementation(async () => {
// Find the tool in the session's customTools and call its execute
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const tool = (mockSession as any).customTools.find(
(t: unknown) => (t as { name: string }).name === 'autofill_metadata',
)
if (tool) {
await tool.execute('call_1', { data: 1 })
}
}),
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 5, output: 5 } }),
getLastAssistantText: vi.fn().mockReturnValue('{"data": 1}'),
state: { tools: [], systemPrompt: '', messages: [] },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
customTools: [] as any[],
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(piAgent.createAgentSession as any).mockImplementation(async (config: any) => {
mockSession.customTools = config.customTools
return { session: mockSession }
})
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Field 1', type: 'text' } }]
const resp = await agentExecutor.autofill(team.id, 'extract data', [], fields)
expect(resp.text).toBe('{"data":1}')
expect(resp.usage.inputTokens).toBe(5)
})
it('chats with bot', async () => {
const team = await prisma.team.create({
data: {
name: 'Chat Bot Team',
},
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
config: mockProviderConfig,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini',
name: 'Gemini',
providerId: provider.id,
config: mockModelConfig,
},
})
await prisma.user.create({
data: {
name: 'Chatter',
email: `chatter-${Date.now()}@shumai.ai`,
type: 'agent',
agent: {
create: {
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: {
provider: 'google',
model: 'gemini',
},
},
},
teamMembers: {
create: {
teamId: team.id,
role: 'reviewer',
},
},
},
})
const mockSession = {
sendUserMessage: vi.fn().mockResolvedValue(undefined),
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 5, output: 5 } }),
getLastAssistantText: vi.fn().mockReturnValue('mock text'),
state: { tools: [], systemPrompt: '', messages: [] },
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(piAgent.createAgentSession as any).mockResolvedValue({ session: mockSession })
const resp = await agentExecutor.chat(team.id, 'hello')
expect(resp.text).toBe('mock text')
})
it('chat with instruction', async () => {
const team = await prisma.team.create({
data: {
name: 'Pirate Team',
},
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
config: mockProviderConfig,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini-pro',
name: 'Gemini Pro',
providerId: provider.id,
config: mockModelConfig,
},
})
const botUser = await prisma.user.create({
data: { name: 'Pirate', email: 'pirate@shumai.ai', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: botUser.id,
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
soul: 'You are a pirate',
config: {
provider: 'google',
model: 'gemini-pro',
},
},
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: botUser.id, role: 'reviewer' },
})
const mockSession = {
sendUserMessage: vi.fn().mockResolvedValue(undefined),
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 10, output: 20 } }),
getLastAssistantText: vi.fn().mockReturnValue('Arr matey!'),
state: { tools: [], systemPrompt: '', messages: [] },
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(piAgent.createAgentSession as any).mockResolvedValue({ session: mockSession })
const resp = await agentExecutor.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)
})
})
+328
View File
@@ -0,0 +1,328 @@
import { prisma } from '@/db'
import { logger } from '@/logger'
import { s3Service } from '@/services/s3/s3'
import { getModel, type ImageContent, type TextContent } from '@mariozechner/pi-ai'
import {
AuthStorage,
createAgentSession,
DefaultResourceLoader,
ModelRegistry,
SessionManager,
SettingsManager,
defineTool,
} from '@mariozechner/pi-coding-agent'
import { Type, type TSchema } from '@sinclair/typebox'
import * as fs from 'fs'
import * as path from 'path'
import { DatabaseSessionManager } from './database-session-manager'
import { analyzeAssetMediaTool } from './tools/analyze-asset-media'
import { readSkillTool } from './tools/read-skill'
import { Usage } from '@/services/ai/provider/provider'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Tool = any
export interface AutofillField {
id: string
config: PrismaJson.FieldConfig
description?: string | null
}
export class AgentExecutor {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
private async getTeam(teamId: string) {
return this.prismaClient.team.findUnique({
where: { id: teamId },
})
}
async chat(teamId: string, prompt: string): Promise<{ text: string; usage: Usage }> {
const agent = await this.prismaClient.agent.findFirst({
where: {
type: 'chat',
enabled: true,
user: {
teamMembers: {
some: { 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: Tool[] = [],
): 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
const agentDir = path.join(process.cwd(), '.pi', 'agents', agent.id)
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
const authStorage = AuthStorage.create(path.join(agentDir, 'auth.json'))
const modelRegistry = ModelRegistry.create(authStorage)
modelRegistry.getAll()
// Fetch and register the required provider from database
const dbProviders = await this.prismaClient.provider.findMany({
where: { teamId, name: providerName },
include: { models: true },
})
for (const p of dbProviders) {
// Ensure each model has a name (fallback to ID) to satisfy registerProvider's strict requirement
const config = {
...p.config,
models: p.models.map((m) => ({
...m.config,
id: m.modelId,
name: m.name || m.modelId,
})),
}
modelRegistry.registerProvider(p.name, config)
}
// Setup credentials
const dbProvider = dbProviders[0]
if (dbProvider?.config.apiKey) {
authStorage.set(providerName, { type: 'api_key', key: dbProvider.config.apiKey })
}
// Fetch team skills
const teamSkills = await this.prismaClient.skill.findMany({
where: { teamId },
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const model = (getModel as any)(providerName, modelId)
const settingsManager = SettingsManager.create(process.cwd(), agentDir)
const resourceLoader = new DefaultResourceLoader({
cwd: process.cwd(),
agentDir,
settingsManager,
systemPromptOverride: () => {
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(', ')}.`
}
if (teamSkills.length > 0) {
systemPrompt += '\n\nAvailable Skills:\n'
for (const s of teamSkills) {
systemPrompt += `- ${s.name} (ID: ${s.id}): ${s.description || 'No description'}\n`
}
systemPrompt +=
'\nTo use a skill, first use the "read_skill" tool with the skill ID to read its instructions.'
}
return systemPrompt
},
noContextFiles: true,
})
await resourceLoader.reload()
const sessionManager = await DatabaseSessionManager.create({
agentId,
userId,
sessionId,
cwd: process.cwd(),
})
const { session } = await createAgentSession({
cwd: process.cwd(),
agentDir,
authStorage,
modelRegistry,
model,
resourceLoader,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sessionManager: sessionManager as any as SessionManager,
customTools: [analyzeAssetMediaTool, readSkillTool, ...tools],
})
const content: (TextContent | ImageContent)[] = []
if (agentsInstruction) {
session.state.systemPrompt = `${session.state.systemPrompt}\n\nContext and Instructions:\n${agentsInstruction}`
}
content.push({ type: 'text', text: prompt })
if (images && images.length > 0) {
for (const key of images) {
const { buffer, contentType } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
key,
)
content.push({
type: 'image',
data: buffer.toString('base64'),
mimeType: contentType,
})
}
}
try {
await session.sendUserMessage(content)
session.state.messages.forEach((msg) => {
if (msg.role === 'toolResult') {
// For tool results, log details (metadata) instead of content (which may have large images)
const logMsg = { ...msg, content: undefined }
logger.debug(logMsg, 'agent message')
} else {
logger.debug(msg, 'agent message')
}
})
const stats = session.getSessionStats()
const text = session.getLastAssistantText() || ''
if (!text) {
const lastMessage = session.messages[session.messages.length - 1]
if (lastMessage && lastMessage.role === 'assistant' && lastMessage.errorMessage) {
throw new Error(`AI error: ${lastMessage.errorMessage}`)
}
}
const usage: Usage = {
model: modelId,
inputTokens: stats.tokens.input || 0,
outputTokens: stats.tokens.output || 0,
}
await sessionManager.waitForSync()
return { text, usage, sessionId: sessionManager.getDbSessionId() }
} finally {
// Cleanup handled by agent session if needed
}
}
async autofill(
teamId: string,
prompt: string,
images: string[],
fields: AutofillField[],
): Promise<{ text: string; usage: Usage }> {
const agent = await this.prismaClient.agent.findFirst({
where: {
type: 'autofill',
enabled: true,
user: {
teamMembers: {
some: { 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 = defineTool({
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 } = await this.chatWithAgent(
teamId,
agent.id,
fullPrompt,
images,
'',
undefined,
undefined,
[autofillTool],
)
return {
text: capturedData ? JSON.stringify(capturedData) : '{}',
usage,
}
}
}
export const agentExecutor = new AgentExecutor()
export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
const properties: Record<string, TSchema> = {}
for (const f of fields) {
let schema: TSchema
switch (f.config.type) {
case 'text':
case 'longText':
schema = Type.String()
break
case 'number':
case 'rating':
schema = Type.Number()
break
case 'toggle':
schema = Type.Boolean()
break
case 'select':
schema = Type.String({
enum: f.config.select?.options?.map((o) => o.id) || [],
})
break
default:
schema = Type.String()
}
if (f.description) {
schema.description = f.description
}
properties[f.id] = schema
}
return Type.Object(properties)
}
+61
View File
@@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest'
import { fieldsToTypeBoxSchema, type AutofillField } from './executor'
describe('fieldsToTypeBoxSchema', () => {
it('converts text fields', () => {
const fields: AutofillField[] = [
{ id: 'f1', config: { name: 'Title', type: 'text' }, description: 'The title' },
{ id: 'f2', config: { name: 'Desc', type: 'longText' } },
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('string')
expect(schema.properties.f1.description).toBe('The title')
expect(schema.properties.f2.type).toBe('string')
})
it('converts numeric fields', () => {
const fields: AutofillField[] = [
{ id: 'f1', config: { name: 'Price', type: 'number' } },
{ id: 'f2', config: { name: 'Rating', type: 'rating' } },
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('number')
expect(schema.properties.f2.type).toBe('number')
})
it('converts toggle fields', () => {
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Active', type: 'toggle' } }]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('boolean')
})
it('converts select fields with enums', () => {
const fields: AutofillField[] = [
{
id: 'f1',
config: {
name: 'Status',
type: 'select',
select: {
options: [
{ id: 'opt1', displayName: 'Option 1', color: 'red' },
{ id: 'opt2', displayName: 'Option 2', color: 'blue' },
],
},
},
},
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('string')
expect(schema.properties.f1.enum).toEqual(['opt1', 'opt2'])
})
it('defaults to string for unknown types', () => {
const fields: AutofillField[] = [
// @ts-ignore
{ id: 'f1', config: { name: 'Unknown', type: 'invalid' } },
]
const schema = fieldsToTypeBoxSchema(fields)
expect(schema.properties.f1.type).toBe('string')
})
})
@@ -0,0 +1,70 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { analyzeAssetMediaTool } from './analyze-asset-media'
import { s3Service } from '@/services/s3/s3'
vi.mock('@/services/s3/s3')
describe('analyzeAssetMediaTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should analyze media by S3 key and return image content', async () => {
// Mock S3 with WEBP magic bytes
const buffer = Buffer.from([
0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50,
])
vi.mocked(s3Service.getObject).mockResolvedValue({ buffer, contentType: 'image/webp' })
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/test.webp' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
expect(result.content[0].type).toBe('image')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).mimeType).toBe('image/webp')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.details as any).sourceKey).toBe('assets/test.webp')
})
it('should infer mimeType from content if S3 response has generic mimeType', async () => {
// Mock S3 with MP4 magic bytes
const buffer = Buffer.from([
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d,
])
vi.mocked(s3Service.getObject).mockResolvedValue({ buffer, contentType: 'application/octet-stream' })
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/no-extension-but-mp4' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
expect(result.content[0].type).toBe('image') // Wrapped as image type for base64
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).mimeType).toBe('video/mp4')
})
it('should return error if S3 getObject fails', async () => {
// Mock S3 failure
vi.mocked(s3Service.getObject).mockRejectedValue(new Error('S3 error'))
const result = await analyzeAssetMediaTool.execute(
'1',
{ key: 'assets/non-existent' },
undefined,
undefined,
{} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const textContent = (result.content[0] as any).text
expect(textContent).toContain('Error analyzing media: S3 error')
})
})
+74
View File
@@ -0,0 +1,74 @@
import { s3Service } from '@/services/s3/s3'
import { Type } from '@sinclair/typebox'
import { defineTool } from '@mariozechner/pi-coding-agent'
import { ImageContent, TextContent } from '@mariozechner/pi-ai'
import { detectSupportedMimeType } from '@/utils/mime'
const analyzeAssetMediaSchema = Type.Object({
key: Type.String({
description:
'The S3 key of the media file to analyze. This MUST be a key obtained from the asset media info.',
}),
})
export interface MediaAnalysisDetails {
sourceKey: string
}
export const analyzeAssetMediaTool = defineTool<
typeof analyzeAssetMediaSchema,
MediaAnalysisDetails
>({
name: 'analyze_asset_media',
label: 'Analyze Asset Media',
description:
'Retrieves and views the media content (images/video) by its S3 key. The key must be obtained from the asset media info provided in the context.',
parameters: analyzeAssetMediaSchema,
execute: async (_toolCallId, params) => {
try {
const { key } = params
if (!key) {
return {
content: [{ type: 'text', text: 'S3 key is required.' }],
details: { sourceKey: '' },
}
}
const bucket = process.env.S3_BUCKET || 'shumai'
const { buffer, contentType } = await s3Service.getObject(bucket, key)
const uint8Array = new Uint8Array(buffer)
let mimeType = contentType
if (mimeType === 'application/octet-stream') {
mimeType = detectSupportedMimeType(uint8Array) || 'application/octet-stream'
}
const content: (TextContent | ImageContent)[] = [
{
type: 'image',
data: buffer.toString('base64'),
mimeType,
},
]
return {
content,
details: {
sourceKey: key,
},
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error analyzing media: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
details: { sourceKey: params.key || '' },
}
}
},
})
+121
View File
@@ -0,0 +1,121 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { readSkillTool } from './read-skill'
import { s3Service } from '@/services/s3/s3'
import * as fs from 'fs'
vi.mock('@/services/s3/s3')
vi.mock('fs')
vi.mock('adm-zip', () => {
return {
default: class {
extractAllTo = vi.fn()
},
}
})
describe('readSkillTool', () => {
setupTestDbHooks()
beforeEach(() => {
vi.clearAllMocks()
})
it('should return error if skill not found', async () => {
const result = await readSkillTool.execute(
'1',
{ skillId: 'non-existent' },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toContain('not found')
})
it('should read skill from cache if hash matches', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'Test Skill',
assetId: 'asset1',
hash: 'match-hash',
teamId: team.id,
},
})
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return 'match-hash'
if (path.toString().endsWith('SKILL.md')) return '# Test Skill Content'
return ''
})
const result = await readSkillTool.execute(
'1',
{ skillId: skill.id },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Test Skill Content')
expect(s3Service.getObject).not.toHaveBeenCalled()
})
it('should download and extract skill if cache missing or hash mismatch', async () => {
const team = await prisma.team.create({ data: { name: 'Test Team' } })
const skill = await prisma.skill.create({
data: {
name: 'New Skill',
assetId: 'asset1',
hash: 'new-hash',
teamId: team.id,
},
})
await prisma.asset.create({
data: {
id: 'asset1',
name: 'skill.zip',
key: 'skills/skill.zip',
type: 'file',
status: 'uploaded',
},
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'existsSync').mockImplementation((path: any) => {
if (path.toString().endsWith('.hash')) return false
if (path.toString().endsWith('SKILL.md')) return true
return true
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
if (path.toString().endsWith('SKILL.md')) return '# Extracted Content'
return ''
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
;(s3Service.getObject as any).mockResolvedValue({ buffer: Buffer.from('zipdata'), contentType: 'application/zip' })
const result = await readSkillTool.execute(
'1',
{ skillId: skill.id },
undefined,
undefined,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking AgentSession is too complex for this test
{} as unknown as any,
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((result.content[0] as any).text).toBe('# Extracted Content')
expect(s3Service.getObject).toHaveBeenCalled()
expect(fs.writeFileSync).toHaveBeenCalledWith(expect.stringContaining('.hash'), 'new-hash')
})
})
+101
View File
@@ -0,0 +1,101 @@
import { prisma } from '@/db'
import { s3Service } from '@/services/s3/s3'
import { Type } from '@sinclair/typebox'
import { defineTool } from '@mariozechner/pi-coding-agent'
import * as path from 'path'
import * as fs from 'fs'
import AdmZip from 'adm-zip'
const readSkillSchema = Type.Object({
skillId: Type.String({ description: 'The ID of the skill to read' }),
})
export const readSkillTool = defineTool<typeof readSkillSchema, { skillId: string }>({
name: 'read_skill',
label: 'Read Agent Skill',
description: 'Downloads and reads an agent skill to understand how to use it.',
parameters: readSkillSchema,
execute: async (_toolCallId, params) => {
try {
const skill = await prisma.skill.findUnique({
where: { id: params.skillId },
})
if (!skill) {
return {
content: [{ type: 'text', text: `Skill with ID ${params.skillId} not found.` }],
details: { skillId: params.skillId },
}
}
const skillDir = path.join(process.cwd(), '.pi', 'skills', skill.id)
const hashFile = path.join(skillDir, '.hash')
let needsDownload = true
if (fs.existsSync(hashFile)) {
const localHash = fs.readFileSync(hashFile, 'utf8')
if (localHash === skill.hash) {
needsDownload = false
}
}
if (needsDownload) {
if (fs.existsSync(skillDir)) {
fs.rmSync(skillDir, { recursive: true, force: true })
}
fs.mkdirSync(skillDir, { recursive: true })
const asset = await prisma.asset.findUnique({
where: { id: skill.assetId },
})
if (!asset || !asset.key) {
throw new Error('Skill asset not found or has no key')
}
const { buffer: zipBuffer } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', asset.key)
const zip = new AdmZip(zipBuffer)
zip.extractAllTo(skillDir, true)
fs.writeFileSync(hashFile, skill.hash)
}
// Read SKILL.md
let skillMdPath = path.join(skillDir, 'SKILL.md')
if (!fs.existsSync(skillMdPath)) {
skillMdPath = path.join(skillDir, 'skill.md')
}
if (!fs.existsSync(skillMdPath)) {
return {
content: [
{
type: 'text',
text: `Skill downloaded but SKILL.md not found in ${skillDir}`,
},
],
details: { skillId: params.skillId },
}
}
const skillMdContent = fs.readFileSync(skillMdPath, 'utf8')
return {
content: [{ type: 'text', text: skillMdContent }],
details: { skillId: params.skillId },
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error reading skill ${params.skillId}: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
details: { skillId: params.skillId },
}
}
},
})
+203
View File
@@ -0,0 +1,203 @@
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',
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__',
isAi: true,
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',
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__',
isAi: true,
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' },
})
})
})
+192
View File
@@ -0,0 +1,192 @@
import type { WorkflowTask } from '@/generated/prisma/client'
import {
getActivities,
executeActivity,
TaskQueueDb,
TaskQueueAgent,
TaskQueueTranscode,
} from '@/workflow/workflow-utils'
export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
const {
updateTaskStatusActivity,
getAssetActivity,
extractAiMetadataActivity,
getProjectAutofillFieldsActivity,
autofillAiActivity,
updateTaskUsageActivity,
updateAssetMetadataActivity,
createCommentActivity,
updateCommentActivity,
getTranscodeWorkerQueueActivity,
getAgentWorkerQueueActivity,
downloadMediaToTmpActivity,
cleanupTmpDirActivity,
} = getActivities()
let placeholderCommentId: string | undefined
let tmpDir: string | undefined
let transcodeWorkerQueue: string | undefined
try {
// Update status to processing
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
// 0. Create Placeholder Comment
const payload = task.payload as Record<string, unknown>
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__AUTOFILL__',
isAi: true,
agentId: (payload?.agentId as string) || 'default',
})
placeholderCommentId = placeholder.id
// 1. Get Asset
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
if (!asset || !asset.project) {
throw new Error('Asset or project not found')
}
const teamId = asset.project.teamId
const projectId = asset.project.id
// 2. Prepare Data (Images)
const isImage = asset.mediaType?.startsWith('image/') || false
// Extraction requires FFmpeg, run on Transcode worker
transcodeWorkerQueue = await executeActivity(
TaskQueueTranscode,
getTranscodeWorkerQueueActivity,
)
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
assetKey: asset.key || '',
})
const { filePath } = download
tmpDir = download.tmpDir
const generatedFiles = await executeActivity(transcodeWorkerQueue, extractAiMetadataActivity, {
assetKey: asset.key || '',
filePath,
type: 'autofill',
isImage,
})
if (generatedFiles.length === 0) {
// If no images could be extracted, we can't do much
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed: No images could be extracted for analysis.',
})
}
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
return
}
// 3. Get Project Autofill Fields
const fields = await executeActivity(TaskQueueDb, getProjectAutofillFieldsActivity, projectId)
if (fields.length === 0) {
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed: No autofill fields defined in project.',
})
}
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
return
}
// 4. Call AI Service
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
teamId,
images: generatedFiles,
fields: fields.map((f) => ({
id: f.id,
config: f.config as unknown as PrismaJson.FieldConfig,
description: f.description,
})),
})
if (aiResult.usage) {
// Update Usage
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: aiResult.usage.inputTokens,
outputTokens: aiResult.usage.outputTokens,
model: aiResult.usage.model,
})
}
// 6. Update Asset Metadata
const result = JSON.parse(aiResult.text)
const metadataUpdates = Object.entries(result).map(([key, value]) => ({
key,
value,
}))
if (metadataUpdates.length > 0) {
await executeActivity(TaskQueueDb, updateAssetMetadataActivity, {
assetId: asset.id,
metadata: metadataUpdates,
})
}
// 7. Update Placeholder Comment
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: 'Autofill completed successfully.',
})
}
// Update status to completed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
})
} catch (err) {
console.error(`AiAutofillMedia failed for task ${task.id}:`, err)
// Update placeholder comment with error message
if (placeholderCommentId) {
try {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
})
} catch (commentErr) {
console.error('Failed to update error comment:', commentErr)
}
}
// Update status to failed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
throw err
} finally {
if (tmpDir && transcodeWorkerQueue) {
try {
await executeActivity(transcodeWorkerQueue, cleanupTmpDirActivity, { tmpDir })
} catch (cleanupErr) {
console.error('Failed to cleanup tmp dir:', cleanupErr)
}
}
}
}
export const aiAutofillWorkflow = aiAutofillMedia
+222
View File
@@ -0,0 +1,222 @@
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',
}),
}
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 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__',
isAi: true,
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__',
isAi: true,
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' },
})
})
})
+150
View File
@@ -0,0 +1,150 @@
import type { WorkflowTask } from '@/generated/prisma/client'
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '@/workflow/workflow-utils'
export async function aiChat(task: WorkflowTask): Promise<void> {
const {
updateTaskStatusActivity,
getAssetActivity,
getCommentActivity,
aiChatActivity,
createCommentActivity,
updateCommentActivity,
updateTaskUsageActivity,
getAgentWorkerQueueActivity,
} = getActivities()
let placeholderCommentId: string | undefined
try {
// Update status to processing
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'processing',
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const payload = task.payload as any
// 1. Get User Comment
const userCommentId = payload?.userCommentId
if (!userCommentId) throw new Error('userCommentId missing in payload')
const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId)
if (!userComment) throw new Error('User comment not found')
// 2. Create Placeholder Comment
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
assetId: task.assetId,
message: '__CHAT__',
isAi: true,
agentId: payload?.agentId,
replyToId: userComment.replyToId ?? userComment.id,
})
placeholderCommentId = placeholder.id
// 3. Get Asset
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
if (!asset || !asset.project) {
throw new Error('Asset or project not found')
}
const teamId = asset.project.teamId
// 4. 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)
}
}
}
let instruction = `The user is discussing an asset with ID: ${asset.id}.`
if (asset.media) {
instruction += `\n\nAsset Media Info:\n${JSON.stringify(asset.media, null, 2)}`
}
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).`
// 5. Call AI Chat
let folderId = ''
if (asset.type === 'folder') {
folderId = asset.id
} else if (asset.parentId) {
folderId = asset.parentId
}
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
const aiResult = await executeActivity(agentWorkerQueue, aiChatActivity, {
teamId,
agentId: payload.agentId,
message: userComment.message || '',
imageUrls: attachmentImageUrls,
projectId: payload.projectId,
folderId,
agentsInstruction: instruction,
sessionId: payload.session_id,
userId: payload.userId,
})
// 6. Update Placeholder Comment
if (placeholderCommentId) {
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: aiResult.text,
})
// Also store sessionId in comment's metadata if we had such a field,
// but for now we just return it in task status.
}
// 7. Update Usage
if (aiResult.usage) {
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
taskId: task.id,
inputTokens: aiResult.usage.inputTokens,
outputTokens: aiResult.usage.outputTokens,
model: aiResult.usage.model,
})
}
// Update status to completed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'completed',
output: { sessionId: aiResult.sessionId },
})
} catch (err) {
console.error(`AiChat failed for task ${task.id}:`, err)
// Update placeholder comment with error message
if (placeholderCommentId) {
try {
const errorMessage =
err instanceof Error && err.message.startsWith('AI error:')
? `AI error: ${err.message.substring(9)}`
: 'Sorry, I encountered an error while processing your request.'
await executeActivity(TaskQueueDb, updateCommentActivity, {
commentId: placeholderCommentId,
message: errorMessage,
})
} catch (commentErr) {
console.error('Failed to update error comment:', commentErr)
}
}
// Update status to failed
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
throw err
}
}
export const aiChatWorkflow = aiChat