From e55ee3a3f0a78817adb493c45037423e9fac3e47 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 10:55:22 +0800 Subject: [PATCH] feat(chatbot): add chatbot backend api support --- packages/api/src/chat.test.ts | 154 +++++++++++ packages/api/src/chat.ts | 123 +++++++++ packages/api/src/index.ts | 2 + packages/core/src/chat/chat.test.ts | 235 ++++++++++++++++ packages/core/src/chat/chat.ts | 410 ++++++++++++++++++++++++++++ packages/core/src/index.ts | 1 + packages/dtos/src/chat.ts | 47 ++++ packages/dtos/src/index.ts | 1 + 8 files changed, 973 insertions(+) create mode 100644 packages/api/src/chat.test.ts create mode 100644 packages/api/src/chat.ts create mode 100644 packages/core/src/chat/chat.test.ts create mode 100644 packages/core/src/chat/chat.ts create mode 100644 packages/dtos/src/chat.ts diff --git a/packages/api/src/chat.test.ts b/packages/api/src/chat.test.ts new file mode 100644 index 00000000..d2976b98 --- /dev/null +++ b/packages/api/src/chat.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest' +import { Hono } from 'hono' +import chatRoute from './chat' +import { chatService } from '@shumai/core/src/chat/chat' +import { authzService } from '@shumai/core/src/authz/authz' + +vi.mock('@shumai/core/src/chat/chat', async (importOriginal) => { + const original = await importOriginal() + return { + ...original, + chatService: { + listSessions: vi.fn(), + listMessages: vi.fn(), + deleteSession: vi.fn(), + startOrContinueChat: vi.fn(), + }, + } +}) +vi.mock('@shumai/core/src/authz/authz') +vi.mock('@shumai/db', () => ({ + prisma: { + agentSessionEntry: { + findMany: vi.fn(), + }, + workflowTask: { + findUnique: vi.fn(), + }, + }, +})) + +import { prisma } from '@shumai/db' + +describe('Chat API', () => { + const app = new Hono<{ Variables: { user: { id: string; name: string } } }>() + .use('*', async (c, next) => { + c.set('user', { id: 'user1', name: 'Test User' }) + await next() + }) + .route('/', chatRoute) + + beforeEach(() => { + vi.restoreAllMocks() + vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) + }) + + describe('GET /chat/sessions', () => { + it('returns list of sessions', async () => { + const mockSessions = { + data: [ + { + id: 'session1', + agentId: 'default', + userId: 'user1', + assetId: 'asset1', + userCommentId: 'comment1', + createdAt: '2026-07-07T10:00:00Z', + updatedAt: '2026-07-07T10:00:00Z', + }, + ], + pageInfo: { total: 1 }, + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.mocked(chatService.listSessions).mockResolvedValue(mockSessions as any) + + const res = await app.request('/chat/sessions?first=10') + expect(res.status).toBe(200) + const data = await res.json() + expect(data.data).toHaveLength(1) + expect(data.data[0].id).toBe('session1') + }) + }) + + describe('GET /chat/sessions/:sessionId/messages', () => { + it('returns list of messages', async () => { + const mockMessages = [ + { + id: 'msg1', + role: 'user', + content: 'hello', + timestamp: '2026-07-07T10:00:00Z', + entry: {}, + }, + ] + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.mocked(chatService.listMessages).mockResolvedValue(mockMessages as any) + + const res = await app.request('/chat/sessions/session1/messages') + expect(res.status).toBe(200) + const data = await res.json() + expect(data).toHaveLength(1) + expect(data[0].content).toBe('hello') + }) + }) + + describe('DELETE /chat/sessions/:sessionId', () => { + it('deletes a session', async () => { + vi.mocked(chatService.deleteSession).mockResolvedValue(undefined) + + const res = await app.request('/chat/sessions/session1', { + method: 'DELETE', + }) + expect(res.status).toBe(204) + expect(chatService.deleteSession).toHaveBeenCalledWith('user1', 'session1') + }) + }) + + describe('POST /chat', () => { + it('starts or continues chat and returns stream', async () => { + vi.mocked(chatService.startOrContinueChat).mockResolvedValue({ + sessionId: 'session1', + taskId: 'task1', + }) + + const mockEntries = [ + { + id: 'entry1', + sessionId: 'session1', + entry: { + type: 'message', + message: { + role: 'user', + content: [{ type: 'text', text: 'hi' }], + }, + }, + }, + ] + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.mocked(prisma.agentSessionEntry.findMany).mockResolvedValue(mockEntries as any) + + const mockTask = { + id: 'task1', + status: 'completed', + output: {}, + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.mocked(prisma.workflowTask.findUnique).mockResolvedValue(mockTask as any) + + const res = await app.request('/chat', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + textPrompt: 'hi', + }), + }) + + expect(res.status).toBe(200) + expect(res.headers.get('content-type')).toContain('text/event-stream') + + const text = await res.text() + expect(text).toContain('data:') + expect(text).toContain('entry1') + }) + }) +}) diff --git a/packages/api/src/chat.ts b/packages/api/src/chat.ts new file mode 100644 index 00000000..580387b7 --- /dev/null +++ b/packages/api/src/chat.ts @@ -0,0 +1,123 @@ +import { Hono } from 'hono' +import { zValidator } from '@hono/zod-validator' +import { streamSSE } from 'hono/streaming' +import { prisma } from '@shumai/db' +import { chatService, mapEntryToMessage } from '@shumai/core/src/chat/chat' +import { chatRequestSchema, paginationParamsSchema } from '@shumai/dtos' +import type { Prisma } from '@shumai/db' + +type User = Prisma.UserGetPayload> + +const route = new Hono<{ Variables: { user: User } }>() + .get('/chat/sessions', zValidator('query', paginationParamsSchema), async (c) => { + const user = c.get('user') + const query = c.req.valid('query') + + const res = await chatService.listSessions(user.id, query) + return c.json(res, 200) + }) + .get('/chat/sessions/:sessionId/messages', async (c) => { + const user = c.get('user') + const sessionId = c.req.param('sessionId') + + const res = await chatService.listMessages(user.id, sessionId) + return c.json(res, 200) + }) + .delete('/chat/sessions/:sessionId', async (c) => { + const user = c.get('user') + const sessionId = c.req.param('sessionId') + + await chatService.deleteSession(user.id, sessionId) + return new Response(null, { status: 204 }) + }) + .post('/chat', zValidator('json', chatRequestSchema), async (c) => { + const user = c.get('user') + const req = c.req.valid('json') + + const { sessionId, taskId } = await chatService.startOrContinueChat(user, req) + + return streamSSE(c, async (stream) => { + let lastEntryId = '' + const timeoutMs = 5 * 60 * 1000 // 5 minutes timeout + const startTime = Date.now() + + while (Date.now() - startTime < timeoutMs) { + // Query new entries from the DB + const newEntries = await prisma.agentSessionEntry.findMany({ + where: { + sessionId, + ...(lastEntryId ? { id: { gt: lastEntryId } } : {}), + }, + orderBy: { id: 'asc' }, + }) + + if (newEntries.length > 0) { + for (const record of newEntries) { + const message = mapEntryToMessage(record) + await stream.writeSSE({ + data: JSON.stringify({ + type: 'entry', + entry: message, + }), + }) + } + lastEntryId = newEntries[newEntries.length - 1].id + } + + // Check if workflow has finished + const task = await prisma.workflowTask.findUnique({ + where: { id: taskId }, + select: { status: true, output: true }, + }) + + if (task && (task.status === 'completed' || task.status === 'failed')) { + // Fetch any remaining entries one last time + const finalEntries = await prisma.agentSessionEntry.findMany({ + where: { + sessionId, + ...(lastEntryId ? { id: { gt: lastEntryId } } : {}), + }, + orderBy: { id: 'asc' }, + }) + for (const record of finalEntries) { + const message = mapEntryToMessage(record) + await stream.writeSSE({ + data: JSON.stringify({ + type: 'entry', + entry: message, + }), + }) + } + + // Send done status + const output = task.output as Record | null + await stream.writeSSE({ + data: JSON.stringify({ + type: 'done', + status: task.status, + error: + task.status === 'failed' + ? (output?.error as string) || 'Workflow failed' + : undefined, + }), + }) + break + } + + // Wait before polling again + await stream.sleep(1000) + } + + if (Date.now() - startTime >= timeoutMs) { + await stream.writeSSE({ + data: JSON.stringify({ + type: 'done', + status: 'failed', + error: 'Request timed out', + }), + }) + } + }) + }) + +export default route diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 96d2e2ff..3f8c01af 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -1,6 +1,7 @@ import type { Prisma } from '@shumai/db' import { Hono } from 'hono' import agentRoute from './agent' +import chatRoute from './chat' import attachmentRoute from './attachment' import authnRoute from './authn' import collectionRoute from './collection' @@ -54,6 +55,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>() .route('/', fileRoute) .route('/', folderRoute) .route('/', agentRoute) + .route('/', chatRoute) .route('/', attachmentRoute) .route('/', uploadRoute) .route('/', shareRoute) diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts new file mode 100644 index 00000000..43951b6b --- /dev/null +++ b/packages/core/src/chat/chat.test.ts @@ -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) + }) +}) diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts new file mode 100644 index 00000000..405fc0d1 --- /dev/null +++ b/packages/core/src/chat/chat.ts @@ -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>, +): 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 { + 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> { + 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 { + 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 { + 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() diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d3328a3e..4db2ede7 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -20,3 +20,4 @@ export * from './user/avatar' export * from './versionStack/versionStack' export * from './hyrumtoken' export * from './pagination' +export * from './chat/chat' diff --git a/packages/dtos/src/chat.ts b/packages/dtos/src/chat.ts new file mode 100644 index 00000000..acb70df6 --- /dev/null +++ b/packages/dtos/src/chat.ts @@ -0,0 +1,47 @@ +import { z } from 'zod' + +export const chatRequestSchema = z + .object({ + textPrompt: z.string().optional(), + attachedFiles: z.array(z.string()).optional(), // Uploaded file asset IDs + assetIds: z.array(z.string()).optional(), // Workspace file/folder IDs referenced + sessionId: z.string().optional(), // ID of existing session (to continue) + contextAssetId: z.string().optional(), // Active page context asset ID + projectId: z.string().optional(), // Target project ID + }) + .superRefine((data, ctx) => { + const hasPrompt = data.textPrompt && data.textPrompt.trim().length > 0 + const hasFiles = data.attachedFiles && data.attachedFiles.length > 0 + const hasAssets = data.assetIds && data.assetIds.length > 0 + if (!hasPrompt && !hasFiles && !hasAssets) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'At least one of textPrompt, attachedFiles, or assetIds must be provided.', + path: ['textPrompt'], + }) + } + }) + +export type ChatRequest = z.infer + +export const chatSessionInfoSchema = z.object({ + id: z.string(), + agentId: z.string(), + userId: z.string().nullable(), + assetId: z.string().nullable(), + userCommentId: z.string().nullable(), + createdAt: z.string(), + updatedAt: z.string(), +}) + +export type ChatSessionInfo = z.infer + +export const chatMessageSchema = z.object({ + id: z.string(), + role: z.enum(['user', 'assistant', 'toolCall', 'toolResult', 'thinking_level_change']), + content: z.string(), + timestamp: z.string(), + entry: z.unknown(), // Raw session entry data +}) + +export type ChatMessage = z.infer diff --git a/packages/dtos/src/index.ts b/packages/dtos/src/index.ts index 10f63d41..76ad3420 100644 --- a/packages/dtos/src/index.ts +++ b/packages/dtos/src/index.ts @@ -18,3 +18,4 @@ export * from './team' export * from './upload' export * from './user-metadata' export * from './versionStack' +export * from './chat'