feat(chatbot): add chatbot backend api support

This commit is contained in:
yiling
2026-07-07 10:55:22 +08:00
parent 5e73fcf4aa
commit e55ee3a3f0
8 changed files with 973 additions and 0 deletions
+235
View File
@@ -0,0 +1,235 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { chatService } from '@shumai/core/src/chat/chat'
import { describe, expect, it } from 'vitest'
describe('ChatService', () => {
setupTestDbHooks()
async function setupBasicData() {
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com`, password: 'pw' },
})
const team = await prisma.team.create({
data: {
name: 'Test Team',
settings: { transcode: { videoStrategy: 'best_match' } },
sandbox: { create: {} },
},
})
const teamMember = await prisma.teamMember.create({
data: {
teamId: team.id,
userId: user.id,
role: 'owner',
},
})
const project = await prisma.project.create({
data: {
name: 'Test Project',
teamId: team.id,
},
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: 'root',
status: 'processed',
projectId: project.id,
},
})
await prisma.project.update({
where: { id: project.id },
data: { rootFolderId: rootFolder.id },
})
return { user, team, teamMember, project, rootFolder }
}
it('should start a new chat session and trigger workflow', async () => {
const { user, project, rootFolder } = await setupBasicData()
const { sessionId, taskId } = await chatService.startOrContinueChat(user, {
textPrompt: 'hello world',
projectId: project.id,
})
expect(sessionId).toBeDefined()
expect(taskId).toBeDefined()
// Verify AgentSession is created
const session = await prisma.agentSession.findUnique({
where: { id: sessionId },
})
expect(session).toBeDefined()
expect(session?.userId).toBe(user.id)
expect(session?.assetId).toBe(rootFolder.id)
// Verify comment is created
const comment = await prisma.assetComment.findFirst({
where: { sessionId },
})
expect(comment).toBeDefined()
expect(comment?.message).toBe('hello world')
expect(comment?.creatorId).toBe(user.id)
// Verify session entry is created
const entry = await prisma.agentSessionEntry.findFirst({
where: { sessionId },
})
expect(entry).toBeDefined()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const payload = entry?.entry as any
expect(payload.message.content[0].text).toBe('hello world')
// Verify WorkflowTask is created
const task = await prisma.workflowTask.findUnique({
where: { id: taskId },
})
expect(task).toBeDefined()
expect(task?.type).toBe('chat')
expect(task?.status).toBe('pending')
})
it('should continue an existing chat session', async () => {
const { user, project } = await setupBasicData()
// Start
const { sessionId } = await chatService.startOrContinueChat(user, {
textPrompt: 'first message',
projectId: project.id,
})
// Continue
const { sessionId: nextSessionId, taskId: nextTaskId } = await chatService.startOrContinueChat(
user,
{
textPrompt: 'second message',
sessionId,
},
)
expect(nextSessionId).toBe(sessionId)
expect(nextTaskId).toBeDefined()
// Verify entries order
const entries = await prisma.agentSessionEntry.findMany({
where: { sessionId },
orderBy: { id: 'asc' },
})
expect(entries).toHaveLength(2)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((entries[0].entry as any).message.content[0].text).toBe('first message')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((entries[1].entry as any).message.content[0].text).toBe('second message')
// Verify reply comment
const comments = await prisma.assetComment.findMany({
where: { sessionId },
orderBy: { id: 'asc' },
})
expect(comments).toHaveLength(2)
expect(comments[0].replyToId).toBeNull()
expect(comments[1].replyToId).toBe(comments[0].id)
})
it('should inject context of referenced assets and attached files', async () => {
const { user, project, rootFolder } = await setupBasicData()
const childFolder = await prisma.asset.create({
data: {
name: 'child_folder',
type: 'folder',
status: 'processed',
projectId: project.id,
parentId: rootFolder.id,
},
})
const textFile = await prisma.asset.create({
data: {
name: 'doc.txt',
type: 'file',
mediaType: 'text/plain',
status: 'processed',
projectId: project.id,
parentId: childFolder.id,
},
})
const { sessionId } = await chatService.startOrContinueChat(user, {
textPrompt: 'process file',
projectId: project.id,
assetIds: [childFolder.id],
attachedFiles: [textFile.id],
})
const comment = await prisma.assetComment.findFirst({
where: { sessionId },
})
expect(comment?.message).toContain('[Context: Attached Files & Referenced Assets]')
expect(comment?.message).toContain('doc.txt')
expect(comment?.message).toContain('child_folder')
expect(comment?.message).toContain('text/plain')
expect(comment?.message).toContain('child_folder/doc.txt')
expect(comment?.message).toContain('process file')
})
it('should list sessions of a user', async () => {
const { user, project } = await setupBasicData()
await chatService.startOrContinueChat(user, {
textPrompt: 'chat 1',
projectId: project.id,
})
await chatService.startOrContinueChat(user, {
textPrompt: 'chat 2',
projectId: project.id,
})
const list = await chatService.listSessions(user.id, { first: 10 })
expect(list.data).toHaveLength(2)
})
it('should list messages mapped correctly', async () => {
const { user, project } = await setupBasicData()
const { sessionId } = await chatService.startOrContinueChat(user, {
textPrompt: 'hello',
projectId: project.id,
})
const messages = await chatService.listMessages(user.id, sessionId)
expect(messages).toHaveLength(1)
expect(messages[0].role).toBe('user')
expect(messages[0].content).toBe('hello')
})
it('should delete session and cascade', async () => {
const { user, project } = await setupBasicData()
const { sessionId } = await chatService.startOrContinueChat(user, {
textPrompt: 'to delete',
projectId: project.id,
})
await chatService.deleteSession(user.id, sessionId)
const session = await prisma.agentSession.findUnique({
where: { id: sessionId },
})
expect(session).toBeNull()
const entries = await prisma.agentSessionEntry.findMany({
where: { sessionId },
})
expect(entries).toHaveLength(0)
})
})
+410
View File
@@ -0,0 +1,410 @@
import { prisma } from '@shumai/db'
import type { Prisma } from '@shumai/db'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { paginateQuery, type PaginatedData } from '@shumai/core/src/pagination'
import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos'
import { ulid } from 'ulid'
export function mapEntryToMessage(
entryRecord: Prisma.AgentSessionEntryGetPayload<Record<string, never>>,
): ChatMessage {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const entry = entryRecord.entry as any
const id = entryRecord.id
const timestamp = entry.timestamp || new Date().toISOString()
let role: ChatMessage['role']
let content = ''
if (entry.type === 'message') {
const rawRole = entry.message?.role
if (
rawRole === 'user' ||
rawRole === 'assistant' ||
rawRole === 'toolCall' ||
rawRole === 'toolResult'
) {
role = rawRole
} else {
role = 'user'
}
if (Array.isArray(entry.message?.content)) {
content = entry.message.content
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.filter((c: any) => c.type === 'text')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map((c: any) => c.text)
.join('\n')
} else if (typeof entry.message?.content === 'string') {
content = entry.message.content
}
} else if (entry.type === 'thinking_level_change') {
role = 'thinking_level_change'
content = `Thinking level changed to ${entry.thinkingLevel}`
} else {
role = 'toolCall'
content = JSON.stringify(entry)
}
return {
id,
role,
content,
timestamp,
entry,
}
}
export class ChatService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
private async getAssetPath(assetId: string): Promise<string> {
const parts: string[] = []
let currentId: string | null = assetId
while (currentId) {
const dbAssetNode = (await prisma.asset.findUnique({
where: { id: currentId },
select: { id: true, name: true, parentId: true, type: true },
})) as { id: string; name: string; parentId: string | null; type: unknown } | null
if (!dbAssetNode) break
if (dbAssetNode.type === 'root' || dbAssetNode.type === 'share_root') {
break
}
parts.unshift(dbAssetNode.name)
currentId = dbAssetNode.parentId
}
return parts.join('/')
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async startOrContinueChat(
user: any,
req: ChatRequest,
): Promise<{ sessionId: string; taskId: string }> {
const {
textPrompt,
attachedFiles = [],
assetIds = [],
sessionId: passedSessionId,
contextAssetId,
projectId: passedProjectId,
} = req
// 1. Permissions verification
if (contextAssetId) {
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: contextAssetId,
})
}
for (const fileId of attachedFiles) {
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: fileId,
})
}
for (const assetId of assetIds) {
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Asset,
id: assetId,
})
}
// 2. Project / Asset scoping resolution
let targetAssetId = ''
if (passedSessionId) {
const session = await this.prismaClient.agentSession.findUnique({
where: { id: passedSessionId },
include: { asset: { include: { project: true } } },
})
if (!session) throw new Error('Session not found')
if (session.userId !== user.id) throw new Error('Unauthorized session access')
if (!session.assetId) throw new Error('Session has no associated asset')
targetAssetId = session.assetId
} else {
// Start a new session
if (contextAssetId) {
const asset = await this.prismaClient.asset.findUnique({
where: { id: contextAssetId },
include: { project: true },
})
if (!asset) throw new Error('Context asset not found')
targetAssetId = contextAssetId
} else if (passedProjectId) {
const project = await this.prismaClient.project.findUnique({
where: { id: passedProjectId },
})
if (!project || !project.rootFolderId) throw new Error('Project or root folder not found')
targetAssetId = project.rootFolderId
} else {
// Find default project from user's first team
const teamMember = await this.prismaClient.teamMember.findFirst({
where: { userId: user.id },
include: { team: { include: { projects: { include: { rootFolder: true } } } } },
})
const project = teamMember?.team?.projects?.[0]
if (!project || !project.rootFolderId) {
throw new Error('No active project found for the user. Please specify a projectId.')
}
targetAssetId = project.rootFolderId
}
}
// 3. Context Prompt construction
let contextPrompt = ''
if (attachedFiles.length > 0 || assetIds.length > 0) {
contextPrompt += '[Context: Attached Files & Referenced Assets]\n'
if (attachedFiles.length > 0) {
contextPrompt += 'Attached Files:\n'
for (const fileId of attachedFiles) {
const file = await this.prismaClient.asset.findUnique({
where: { id: fileId },
})
if (file) {
const filePath = await this.getAssetPath(file.id)
contextPrompt += `- Name: ${file.name} (ID: ${file.id}, Type: ${file.type}, Media Type: ${file.mediaType || 'unknown'}, Project ID: ${file.projectId || 'unknown'}, Path: ${filePath})\n`
}
}
}
if (assetIds.length > 0) {
contextPrompt += 'Referenced Workspace Assets:\n'
for (const assetId of assetIds) {
const asset = await this.prismaClient.asset.findUnique({
where: { id: assetId },
})
if (asset) {
const assetPath = await this.getAssetPath(asset.id)
contextPrompt += `- Name: ${asset.name} (ID: ${asset.id}, Type: ${asset.type}, Media Type: ${asset.mediaType || 'unknown'}, Project ID: ${asset.projectId || 'unknown'}, Path: ${assetPath})\n`
}
}
}
contextPrompt += '\n---\n'
}
const finalPrompt = `${contextPrompt}${textPrompt || ''}`
// 4. Create database records in a transaction
return await this.prismaClient.$transaction(async (tx) => {
const asset = await tx.asset.findUnique({
where: { id: targetAssetId },
include: { project: { include: { team: true } } },
})
if (!asset || !asset.project) {
throw new Error('Resolved asset or project not found')
}
const teamId = asset.project.teamId
const projectId = asset.project.id
// Ensure AI agent configuration exists
const agentId = 'default'
const userExists = await tx.user.findUnique({ where: { id: agentId } })
if (!userExists) {
await tx.user.create({
data: {
id: agentId,
name: 'Ai Agent',
email: `${agentId}@shumai.ai`,
type: 'agent',
},
})
}
const agentExists = await tx.agent.findUnique({ where: { id: agentId } })
if (!agentExists) {
await tx.agent.create({
data: {
id: agentId,
teamId,
type: 'chat',
config: {
provider: 'openai',
model: 'gpt-4',
},
},
})
}
let activeSessionId = passedSessionId
let existingSession = null
if (activeSessionId) {
existingSession = await tx.agentSession.findUnique({
where: { id: activeSessionId },
})
if (!existingSession) throw new Error('Session not found')
} else {
const newSession = await tx.agentSession.create({
data: {
agentId,
userId: user.id,
cwd: process.cwd(),
assetId: asset.id,
},
})
activeSessionId = newSession.id
}
// Create comment representing the user's message
const replyToId = passedSessionId ? existingSession?.userCommentId : undefined
const comment = await tx.assetComment.create({
data: {
assetId: asset.id,
creatorId: user.id,
message: finalPrompt,
sessionId: activeSessionId,
replyToId: replyToId || null,
},
})
// Link attachment assets if provided
if (attachedFiles.length > 0) {
for (const fileId of attachedFiles) {
const fileAsset = await tx.asset.findUnique({
where: { id: fileId },
})
if (fileAsset) {
await tx.assetCommentAttachment.create({
data: {
assetId: fileAsset.id,
commentId: comment.id,
},
})
}
}
}
// Append entry for user's message
const parentId = passedSessionId ? existingSession?.leafId : null
const entryId = ulid()
const entryJson = {
type: 'message' as const,
id: entryId,
parentId: parentId || null,
timestamp: new Date().toISOString(),
message: {
role: 'user' as const,
content: [{ type: 'text' as const, text: finalPrompt }],
timestamp: Date.now(),
},
}
await tx.agentSessionEntry.create({
data: {
id: entryId,
sessionId: activeSessionId!,
entry: entryJson,
},
})
// Update session's state
await tx.agentSession.update({
where: { id: activeSessionId },
data: {
leafId: entryId,
...(!passedSessionId ? { userCommentId: comment.id } : {}),
},
})
// Trigger chat workflow
const task = await tx.workflowTask.create({
data: {
assetId: asset.id,
type: 'chat',
status: 'pending',
teamId,
projectId,
payload: {
projectId,
agent: {
userCommentId: comment.id,
agentId,
sessionId: activeSessionId,
userId: user.id,
},
},
},
})
return {
sessionId: activeSessionId!,
taskId: task.id,
}
})
}
async listSessions(
userId: string,
params: { first?: number; after?: string },
): Promise<PaginatedData<ChatSessionInfo[]>> {
const where: Prisma.AgentSessionWhereInput = {
userId,
}
return await paginateQuery(
async (skip, take) => {
const sessions = await this.prismaClient.agentSession.findMany({
where,
skip,
take,
orderBy: { id: 'desc' },
})
return sessions.map((s) => ({
id: s.id,
agentId: s.agentId,
userId: s.userId,
assetId: s.assetId,
userCommentId: s.userCommentId,
createdAt: s.createdAt.toISOString(),
updatedAt: s.updatedAt.toISOString(),
}))
},
async () => this.prismaClient.agentSession.count({ where }),
params,
)
}
async listMessages(userId: string, sessionId: string): Promise<ChatMessage[]> {
const session = await this.prismaClient.agentSession.findUnique({
where: { id: sessionId },
})
if (!session) {
throw new Error('Session not found')
}
if (session.userId !== userId) {
throw new Error('Unauthorized session access')
}
const entries = await this.prismaClient.agentSessionEntry.findMany({
where: { sessionId },
orderBy: { id: 'asc' },
})
return entries.map(mapEntryToMessage)
}
async deleteSession(userId: string, sessionId: string): Promise<void> {
const session = await this.prismaClient.agentSession.findUnique({
where: { id: sessionId },
})
if (!session) {
throw new Error('Session not found')
}
if (session.userId !== userId) {
throw new Error('Unauthorized session access')
}
await this.prismaClient.agentSession.delete({
where: { id: sessionId },
})
}
}
export const chatService = new ChatService()
+1
View File
@@ -20,3 +20,4 @@ export * from './user/avatar'
export * from './versionStack/versionStack'
export * from './hyrumtoken'
export * from './pagination'
export * from './chat/chat'