From e55ee3a3f0a78817adb493c45037423e9fac3e47 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 10:55:22 +0800 Subject: [PATCH 01/12] 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' From ccf742e158a685100eaef4da67be8d657c5de98b Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 11:04:51 +0800 Subject: [PATCH 02/12] refactor(chatbot): make user parameter in startOrContinueChat type-safe --- packages/core/src/chat/chat.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 405fc0d1..8d2db667 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -5,6 +5,8 @@ import { paginateQuery, type PaginatedData } from '@shumai/core/src/pagination' import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos' import { ulid } from 'ulid' +type User = Prisma.UserGetPayload> + export function mapEntryToMessage( entryRecord: Prisma.AgentSessionEntryGetPayload>, ): ChatMessage { @@ -77,9 +79,8 @@ export class ChatService { return parts.join('/') } - // eslint-disable-next-line @typescript-eslint/no-explicit-any async startOrContinueChat( - user: any, + user: User, req: ChatRequest, ): Promise<{ sessionId: string; taskId: string }> { const { From 63590d53297de72a91658d382fe329c9b168e064 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 11:12:15 +0800 Subject: [PATCH 03/12] feat(chatbot): decouple chatbot sessions from AssetComment table --- packages/agent/src/workflows/agent-chat.ts | 76 +++++++++++++--------- packages/core/src/chat/chat.test.ts | 67 +++++++++++-------- packages/core/src/chat/chat.ts | 45 ++++--------- packages/db/src/prisma-json-types.ts | 2 + 4 files changed, 99 insertions(+), 91 deletions(-) diff --git a/packages/agent/src/workflows/agent-chat.ts b/packages/agent/src/workflows/agent-chat.ts index 5face496..48e183a7 100644 --- a/packages/agent/src/workflows/agent-chat.ts +++ b/packages/agent/src/workflows/agent-chat.ts @@ -46,26 +46,42 @@ export async function agentChat(task: WorkflowTask): Promise { // 1. Get User Comment const userCommentId = payload.agent?.userCommentId - if (!userCommentId) { - throw ApplicationFailure.create({ - message: 'userCommentId missing in payload', - nonRetryable: true, - }) - } - const userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId) - if (!userComment) { - throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true }) - } + let prompt = '' + let attachmentImageUrls: string[] = [] + let commentTimestamp: number | undefined - // 2. Create Placeholder Comment - const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, { - assetId: task.assetId, - message: '__CHAT__', - sessionId: sessionId || 'pending', - agentId: agentId, - replyToId: userComment.replyToId ?? userComment.id, - }) - placeholderCommentId = placeholder.id + if (userCommentId) { + const userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId) + if (!userComment) { + throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true }) + } + prompt = userComment.message || '' + if (userComment.second !== null && userComment.second !== undefined) { + commentTimestamp = userComment.second + } + + // 2. Create Placeholder Comment + const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, { + assetId: task.assetId, + message: '__CHAT__', + sessionId: sessionId || 'pending', + agentId: agentId, + replyToId: userComment.replyToId ?? userComment.id, + }) + placeholderCommentId = placeholder.id + + // 5. Prepare Images (Attachments only) + if (userComment.attachments) { + for (const att of userComment.attachments) { + if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) { + attachmentImageUrls.push(att.asset.storageKey.key) + } + } + } + } else { + prompt = payload.agent?.prompt || '' + attachmentImageUrls = payload.agent?.imageUrls || [] + } // 3. Get Asset const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId) @@ -76,6 +92,12 @@ export async function agentChat(task: WorkflowTask): Promise { // 4. Initialize Session if missing if (!sessionId) { + if (!userCommentId) { + throw ApplicationFailure.create({ + message: 'sessionId is required when userCommentId is missing', + nonRetryable: true, + }) + } sessionId = await executeActivity(agentWorkerQueue, initializeAgentSessionActivity, { teamId, agentId: agentId, @@ -90,16 +112,6 @@ export async function agentChat(task: WorkflowTask): Promise { agentId: agentId, }) - // 5. Prepare Images (Attachments only) - const attachmentImageUrls: string[] = [] - if (userComment?.attachments) { - for (const att of userComment.attachments) { - if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) { - attachmentImageUrls.push(att.asset.storageKey.key) - } - } - } - const pathContext = await executeActivity( agentWorkerQueue, getAssetPathContextActivity, @@ -113,7 +125,7 @@ export async function agentChat(task: WorkflowTask): Promise { const instruction = new AgentChatPromptBuilder(asset.id) .withPathContext(pathContext) .withAssetDetails(asset.name, asset.mediaType, duration) - .withCommentTimestamp(userComment.second) + .withCommentTimestamp(commentTimestamp) .withExplicitMention(payload.agent?.explicitMention) .build() @@ -128,14 +140,14 @@ export async function agentChat(task: WorkflowTask): Promise { const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, { teamId, agentId: agentId, - message: userComment.message || '', + message: prompt, imageUrls: attachmentImageUrls, projectId: payload.projectId, folderId, agentsInstruction: instruction, sessionId, userId: payload.agent?.userId, - userCommentId, + userCommentId: userCommentId || undefined, explicitMention: payload.agent?.explicitMention, context, }) diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index 43951b6b..c11b930a 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -70,13 +70,11 @@ describe('ChatService', () => { expect(session?.userId).toBe(user.id) expect(session?.assetId).toBe(rootFolder.id) - // Verify comment is created + // Verify no 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) + expect(comment).toBeNull() // Verify session entry is created const entry = await prisma.agentSessionEntry.findFirst({ @@ -87,13 +85,16 @@ describe('ChatService', () => { const payload = entry?.entry as any expect(payload.message.content[0].text).toBe('hello world') - // Verify WorkflowTask is created + // Verify WorkflowTask is created with correct payload const task = await prisma.workflowTask.findUnique({ where: { id: taskId }, }) expect(task).toBeDefined() expect(task?.type).toBe('chat') expect(task?.status).toBe('pending') + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const taskPayload = task?.payload as any + expect(taskPayload?.agent?.prompt).toBe('hello world') }) it('should continue an existing chat session', async () => { @@ -128,14 +129,14 @@ describe('ChatService', () => { // 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' }, + // Verify WorkflowTask is created with correct payload + const task = await prisma.workflowTask.findUnique({ + where: { id: nextTaskId }, }) - expect(comments).toHaveLength(2) - expect(comments[0].replyToId).toBeNull() - expect(comments[1].replyToId).toBe(comments[0].id) + expect(task).toBeDefined() + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const taskPayload = task?.payload as any + expect(taskPayload?.agent?.prompt).toBe('second message') }) it('should inject context of referenced assets and attached files', async () => { @@ -151,34 +152,44 @@ describe('ChatService', () => { }, }) - const textFile = await prisma.asset.create({ + const storageKey = await prisma.storageKey.create({ data: { - name: 'doc.txt', - type: 'file', - mediaType: 'text/plain', - status: 'processed', - projectId: project.id, - parentId: childFolder.id, + key: 'doc_s3_key', }, }) - const { sessionId } = await chatService.startOrContinueChat(user, { + const textFile = await prisma.asset.create({ + data: { + name: 'doc.jpg', + type: 'file', + mediaType: 'image/jpeg', + status: 'processed', + projectId: project.id, + parentId: childFolder.id, + storageKeyId: storageKey.id, + }, + }) + + const { taskId } = await chatService.startOrContinueChat(user, { textPrompt: 'process file', projectId: project.id, assetIds: [childFolder.id], attachedFiles: [textFile.id], }) - const comment = await prisma.assetComment.findFirst({ - where: { sessionId }, + const task = await prisma.workflowTask.findUnique({ + where: { id: taskId }, }) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const taskPayload = task?.payload as any - 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') + expect(taskPayload?.agent?.prompt).toContain('[Context: Attached Files & Referenced Assets]') + expect(taskPayload?.agent?.prompt).toContain('doc.jpg') + expect(taskPayload?.agent?.prompt).toContain('child_folder') + expect(taskPayload?.agent?.prompt).toContain('image/jpeg') + expect(taskPayload?.agent?.prompt).toContain('child_folder/doc.jpg') + expect(taskPayload?.agent?.prompt).toContain('process file') + expect(taskPayload?.agent?.imageUrls).toContain('doc_s3_key') }) it('should list sessions of a user', async () => { diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 8d2db667..5690f1ad 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -194,6 +194,17 @@ export class ChatService { const finalPrompt = `${contextPrompt}${textPrompt || ''}` + const resolvedImageUrls: string[] = [] + for (const fileId of attachedFiles) { + const file = await this.prismaClient.asset.findUnique({ + where: { id: fileId }, + include: { storageKey: true }, + }) + if (file && file.mediaType?.startsWith('image/') && file.storageKey?.key) { + resolvedImageUrls.push(file.storageKey.key) + } + } + // 4. Create database records in a transaction return await this.prismaClient.$transaction(async (tx) => { const asset = await tx.asset.findUnique({ @@ -254,35 +265,6 @@ export class ChatService { 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() @@ -311,7 +293,6 @@ export class ChatService { where: { id: activeSessionId }, data: { leafId: entryId, - ...(!passedSessionId ? { userCommentId: comment.id } : {}), }, }) @@ -326,7 +307,9 @@ export class ChatService { payload: { projectId, agent: { - userCommentId: comment.id, + prompt: finalPrompt, + imageUrls: resolvedImageUrls, + explicitMention: true, agentId, sessionId: activeSessionId, userId: user.id, diff --git a/packages/db/src/prisma-json-types.ts b/packages/db/src/prisma-json-types.ts index 717a4343..72b1d0a3 100644 --- a/packages/db/src/prisma-json-types.ts +++ b/packages/db/src/prisma-json-types.ts @@ -288,6 +288,8 @@ declare global { sessionId?: string userCommentId?: string explicitMention?: boolean + prompt?: string + imageUrls?: string[] } // ---------------------------------------------------------------------- From 7b6db5b56c7d9ccc3f486ff9a66f5ed74f53edb4 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 11:27:29 +0800 Subject: [PATCH 04/12] feat(chatbot): require agentId in ChatRequest and validate agent presence --- packages/api/src/chat.test.ts | 1 + packages/core/src/chat/chat.test.ts | 43 ++++++++++++++++++++++++----- packages/core/src/chat/chat.ts | 29 +++---------------- packages/dtos/src/chat.ts | 1 + 4 files changed, 42 insertions(+), 32 deletions(-) diff --git a/packages/api/src/chat.test.ts b/packages/api/src/chat.test.ts index d2976b98..a1dad133 100644 --- a/packages/api/src/chat.test.ts +++ b/packages/api/src/chat.test.ts @@ -139,6 +139,7 @@ describe('Chat API', () => { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ + agentId: 'agent1', textPrompt: 'hi', }), }) diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index c11b930a..101f452d 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -48,13 +48,35 @@ describe('ChatService', () => { data: { rootFolderId: rootFolder.id }, }) - return { user, team, teamMember, project, rootFolder } + const agentUser = await prisma.user.create({ + data: { + id: 'test-agent-id', + name: 'Test Agent', + email: 'test-agent@shumai.ai', + type: 'agent', + }, + }) + + const agent = await prisma.agent.create({ + data: { + id: 'test-agent-id', + teamId: team.id, + type: 'chat', + config: { + provider: 'openai', + model: 'gpt-4', + }, + }, + }) + + return { user, team, teamMember, project, rootFolder, agent, agentUser } } it('should start a new chat session and trigger workflow', async () => { - const { user, project, rootFolder } = await setupBasicData() + const { user, project, rootFolder, agent } = await setupBasicData() const { sessionId, taskId } = await chatService.startOrContinueChat(user, { + agentId: agent.id, textPrompt: 'hello world', projectId: project.id, }) @@ -98,10 +120,11 @@ describe('ChatService', () => { }) it('should continue an existing chat session', async () => { - const { user, project } = await setupBasicData() + const { user, project, agent } = await setupBasicData() // Start const { sessionId } = await chatService.startOrContinueChat(user, { + agentId: agent.id, textPrompt: 'first message', projectId: project.id, }) @@ -110,6 +133,7 @@ describe('ChatService', () => { const { sessionId: nextSessionId, taskId: nextTaskId } = await chatService.startOrContinueChat( user, { + agentId: agent.id, textPrompt: 'second message', sessionId, }, @@ -140,7 +164,7 @@ describe('ChatService', () => { }) it('should inject context of referenced assets and attached files', async () => { - const { user, project, rootFolder } = await setupBasicData() + const { user, project, rootFolder, agent } = await setupBasicData() const childFolder = await prisma.asset.create({ data: { @@ -171,6 +195,7 @@ describe('ChatService', () => { }) const { taskId } = await chatService.startOrContinueChat(user, { + agentId: agent.id, textPrompt: 'process file', projectId: project.id, assetIds: [childFolder.id], @@ -193,14 +218,16 @@ describe('ChatService', () => { }) it('should list sessions of a user', async () => { - const { user, project } = await setupBasicData() + const { user, project, agent } = await setupBasicData() await chatService.startOrContinueChat(user, { + agentId: agent.id, textPrompt: 'chat 1', projectId: project.id, }) await chatService.startOrContinueChat(user, { + agentId: agent.id, textPrompt: 'chat 2', projectId: project.id, }) @@ -210,9 +237,10 @@ describe('ChatService', () => { }) it('should list messages mapped correctly', async () => { - const { user, project } = await setupBasicData() + const { user, project, agent } = await setupBasicData() const { sessionId } = await chatService.startOrContinueChat(user, { + agentId: agent.id, textPrompt: 'hello', projectId: project.id, }) @@ -224,9 +252,10 @@ describe('ChatService', () => { }) it('should delete session and cascade', async () => { - const { user, project } = await setupBasicData() + const { user, project, agent } = await setupBasicData() const { sessionId } = await chatService.startOrContinueChat(user, { + agentId: agent.id, textPrompt: 'to delete', projectId: project.id, }) diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 5690f1ad..71c0e1fd 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -84,6 +84,7 @@ export class ChatService { req: ChatRequest, ): Promise<{ sessionId: string; taskId: string }> { const { + agentId, textPrompt, attachedFiles = [], assetIds = [], @@ -218,31 +219,9 @@ export class ChatService { 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', - }, - }, - }) + const agent = await tx.agent.findUnique({ where: { id: agentId } }) + if (!agent) { + throw new Error(`Agent with ID "${agentId}" not found`) } let activeSessionId = passedSessionId diff --git a/packages/dtos/src/chat.ts b/packages/dtos/src/chat.ts index acb70df6..bcdf4c55 100644 --- a/packages/dtos/src/chat.ts +++ b/packages/dtos/src/chat.ts @@ -2,6 +2,7 @@ import { z } from 'zod' export const chatRequestSchema = z .object({ + agentId: z.string(), 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 From e4c1830e02bfe4310813f25525be8fbf996ad46e Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 11:42:40 +0800 Subject: [PATCH 05/12] feat(chatbot): delegate context prompt building to AgentChatPromptBuilder in workflow --- .../agent-chat-prompt-builder.test.ts | 11 +++ .../workflows/agent-chat-prompt-builder.ts | 26 +++++++ .../agent/src/workflows/agent-chat.test.ts | 68 +++++++++++++++++++ packages/agent/src/workflows/agent-chat.ts | 30 ++++++++ packages/core/src/chat/chat.test.ts | 9 +-- packages/core/src/chat/chat.ts | 35 +--------- packages/db/src/prisma-json-types.ts | 2 + 7 files changed, 143 insertions(+), 38 deletions(-) diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts index 87f9c039..2714ec40 100644 --- a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts @@ -73,4 +73,15 @@ describe('AgentChatPromptBuilder', () => { expect(result).toContain("call the 'screenshot' tool") expect(result).toContain('The user explicitly mentioned you') }) + + it('should build prompt with attached files and referenced assets', () => { + const builder = new AgentChatPromptBuilder('a1') + .withAttachedFiles(['- file1.txt', '- file2.png']) + .withReferencedAssets(['- folder1', '- file3.mp4']) + const result = builder.build() + + expect(result).toContain('[Context: Attached Files & Referenced Assets]') + expect(result).toContain('Attached Files:\n- file1.txt\n- file2.png') + expect(result).toContain('Referenced Workspace Assets:\n- folder1\n- file3.mp4') + }) }) diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.ts index b8c14243..aee76c26 100644 --- a/packages/agent/src/workflows/agent-chat-prompt-builder.ts +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.ts @@ -22,11 +22,27 @@ export class AgentChatPromptBuilder { private commentTimestamp?: number private pathContext?: string private explicitMention = false + private attachedFiles: string[] = [] + private referencedAssets: string[] = [] constructor(assetId: string) { this.assetId = assetId } + withAttachedFiles(files?: string[]): this { + if (files) { + this.attachedFiles = files + } + return this + } + + withReferencedAssets(assets?: string[]): this { + if (assets) { + this.referencedAssets = assets + } + return this + } + withPathContext(pathContext?: string): this { this.pathContext = pathContext return this @@ -70,6 +86,16 @@ export class AgentChatPromptBuilder { instruction += `\n\nAsset Path Context:\n${this.pathContext}` } + if (this.attachedFiles.length > 0 || this.referencedAssets.length > 0) { + instruction += `\n\n[Context: Attached Files & Referenced Assets]` + if (this.attachedFiles.length > 0) { + instruction += `\nAttached Files:\n${this.attachedFiles.join('\n')}` + } + if (this.referencedAssets.length > 0) { + instruction += `\nReferenced Workspace Assets:\n${this.referencedAssets.join('\n')}` + } + } + if (this.mediaType) { const type = getSimpleMediaType(this.mediaType) if (type === 'image') { diff --git a/packages/agent/src/workflows/agent-chat.test.ts b/packages/agent/src/workflows/agent-chat.test.ts index a82d0d6f..d5682e4b 100644 --- a/packages/agent/src/workflows/agent-chat.test.ts +++ b/packages/agent/src/workflows/agent-chat.test.ts @@ -397,4 +397,72 @@ describe('Agent Chat Workflow', () => { message: 'Sorry, I encountered an error while processing your request.', }) }) + + it('should execute direct-context chatbot flow resolving file metadata and skipping comment placeholder', async () => { + mockActivities.getAssetActivity.mockImplementation(async (id: string) => { + if (id === 'file-attachment-1') { + return { id: 'file-attachment-1', name: 'attachment.png', type: 'file', mediaType: 'image/png', projectId: 'p1' } + } + if (id === 'referenced-asset-1') { + return { id: 'referenced-asset-1', name: 'ref-folder', type: 'folder', mediaType: null, projectId: 'p1' } + } + return { id, name: 'test-file.png', type: 'file', mediaType: 'image/png', projectId: 'p1', project: { teamId: 't1' } } + }) + + mockActivities.getAssetPathContextActivity.mockImplementation(async (id: string) => { + if (id === 'file-attachment-1') return 'attachment.png' + if (id === 'referenced-asset-1') return 'ref-folder' + return 'folder/subfolder/file.png' + }) + + const task = await prisma.workflowTask.create({ + data: { + type: 'chat', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agent: { + agentId: 'b1', + sessionId: 'session-direct-123', + prompt: 'chatbot prompt', + attachedFiles: ['file-attachment-1'], + assetIds: ['referenced-asset-1'], + explicitMention: true, + }, + }, + }, + }) + + await agentChat(task) + + // Verify placeholder comment is NOT created + expect(mockActivities.createCommentActivity).not.toHaveBeenCalled() + expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled() + + // Verify prompt builder is populated and workflow runs agentChatActivity with context instruction + const expectedInstruction = new AgentChatPromptBuilder('a1') + .withPathContext('folder/subfolder/file.png') + .withAssetDetails('test-file.png', 'image/png', undefined) + .withCommentTimestamp(undefined) + .withExplicitMention(true) + .withAttachedFiles(['- Name: attachment.png (ID: file-attachment-1, Type: file, Media Type: image/png, Project ID: p1, Path: attachment.png)']) + .withReferencedAssets(['- Name: ref-folder (ID: referenced-asset-1, Type: folder, Media Type: unknown, Project ID: p1, Path: ref-folder)']) + .build() + + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith({ + teamId: 't1', + agentId: 'b1', + message: 'chatbot prompt', + imageUrls: [], + projectId: 'p1', + folderId: '', + agentsInstruction: expectedInstruction, + sessionId: 'session-direct-123', + userId: undefined, + userCommentId: undefined, + explicitMention: true, + context: { agent: { id: 'b1' } }, + }) + }) }) diff --git a/packages/agent/src/workflows/agent-chat.ts b/packages/agent/src/workflows/agent-chat.ts index 48e183a7..64d14925 100644 --- a/packages/agent/src/workflows/agent-chat.ts +++ b/packages/agent/src/workflows/agent-chat.ts @@ -122,11 +122,41 @@ export async function agentChat(task: WorkflowTask): Promise { const mediaInfo = asset.media as any const duration = mediaInfo?.duration + // Resolve Attached Files Details + const attachedFileDetailsList: string[] = [] + if (payload.agent?.attachedFiles) { + for (const fileId of payload.agent.attachedFiles) { + const file = await executeActivity(agentWorkerQueue, getAssetActivity, fileId) + if (file) { + const path = await executeActivity(agentWorkerQueue, getAssetPathContextActivity, fileId) + attachedFileDetailsList.push( + `- Name: ${file.name} (ID: ${file.id}, Type: ${file.type}, Media Type: ${file.mediaType || 'unknown'}, Project ID: ${file.projectId || 'unknown'}, Path: ${path})` + ) + } + } + } + + // Resolve Referenced Workspace Assets Details + const referencedAssetDetailsList: string[] = [] + if (payload.agent?.assetIds) { + for (const assetId of payload.agent.assetIds) { + const referencedAsset = await executeActivity(agentWorkerQueue, getAssetActivity, assetId) + if (referencedAsset) { + const path = await executeActivity(agentWorkerQueue, getAssetPathContextActivity, assetId) + referencedAssetDetailsList.push( + `- Name: ${referencedAsset.name} (ID: ${referencedAsset.id}, Type: ${referencedAsset.type}, Media Type: ${referencedAsset.mediaType || 'unknown'}, Project ID: ${referencedAsset.projectId || 'unknown'}, Path: ${path})` + ) + } + } + } + const instruction = new AgentChatPromptBuilder(asset.id) .withPathContext(pathContext) .withAssetDetails(asset.name, asset.mediaType, duration) .withCommentTimestamp(commentTimestamp) .withExplicitMention(payload.agent?.explicitMention) + .withAttachedFiles(attachedFileDetailsList) + .withReferencedAssets(referencedAssetDetailsList) .build() // 6. Call AI Chat diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index 101f452d..713dd0d2 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -208,12 +208,9 @@ describe('ChatService', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const taskPayload = task?.payload as any - expect(taskPayload?.agent?.prompt).toContain('[Context: Attached Files & Referenced Assets]') - expect(taskPayload?.agent?.prompt).toContain('doc.jpg') - expect(taskPayload?.agent?.prompt).toContain('child_folder') - expect(taskPayload?.agent?.prompt).toContain('image/jpeg') - expect(taskPayload?.agent?.prompt).toContain('child_folder/doc.jpg') - expect(taskPayload?.agent?.prompt).toContain('process file') + expect(taskPayload?.agent?.prompt).toBe('process file') + expect(taskPayload?.agent?.attachedFiles).toContain(textFile.id) + expect(taskPayload?.agent?.assetIds).toContain(childFolder.id) expect(taskPayload?.agent?.imageUrls).toContain('doc_s3_key') }) diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 71c0e1fd..1835f8bd 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -162,38 +162,7 @@ export class ChatService { } } - // 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 || ''}` + const finalPrompt = textPrompt || '' const resolvedImageUrls: string[] = [] for (const fileId of attachedFiles) { @@ -288,6 +257,8 @@ export class ChatService { agent: { prompt: finalPrompt, imageUrls: resolvedImageUrls, + attachedFiles, + assetIds, explicitMention: true, agentId, sessionId: activeSessionId, diff --git a/packages/db/src/prisma-json-types.ts b/packages/db/src/prisma-json-types.ts index 72b1d0a3..3fc60f5c 100644 --- a/packages/db/src/prisma-json-types.ts +++ b/packages/db/src/prisma-json-types.ts @@ -290,6 +290,8 @@ declare global { explicitMention?: boolean prompt?: string imageUrls?: string[] + attachedFiles?: string[] + assetIds?: string[] } // ---------------------------------------------------------------------- From 243a4ab2c52e609b05de6ee2aaf583851b05faaa Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 11:50:31 +0800 Subject: [PATCH 06/12] feat(chatbot): remove manual AgentSessionEntry creation from ChatService --- packages/core/src/chat/chat.test.ts | 35 +++++++++++++++++--------- packages/core/src/chat/chat.ts | 39 +++-------------------------- 2 files changed, 26 insertions(+), 48 deletions(-) diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index 713dd0d2..b0d05d22 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -98,14 +98,11 @@ describe('ChatService', () => { }) expect(comment).toBeNull() - // Verify session entry is created + // Verify no session entry is created yet (it is created automatically when the workflow runs) 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') + expect(entry).toBeNull() // Verify WorkflowTask is created with correct payload const task = await prisma.workflowTask.findUnique({ @@ -142,16 +139,11 @@ describe('ChatService', () => { expect(nextSessionId).toBe(sessionId) expect(nextTaskId).toBeDefined() - // Verify entries order + // Verify no entries are created yet (they are created automatically when the workflow runs) 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') + expect(entries).toHaveLength(0) // Verify WorkflowTask is created with correct payload const task = await prisma.workflowTask.findUnique({ @@ -242,6 +234,25 @@ describe('ChatService', () => { projectId: project.id, }) + // Manually insert a test entry representing user message + await prisma.agentSessionEntry.create({ + data: { + id: 'test-entry-id', + sessionId, + entry: { + type: 'message', + id: 'test-entry-id', + parentId: null, + timestamp: new Date().toISOString(), + message: { + role: 'user', + content: [{ type: 'text', text: 'hello' }], + timestamp: Date.now(), + }, + }, + }, + }) + const messages = await chatService.listMessages(user.id, sessionId) expect(messages).toHaveLength(1) expect(messages[0].role).toBe('user') diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 1835f8bd..bbe5b796 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -3,7 +3,6 @@ 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' type User = Prisma.UserGetPayload> @@ -194,13 +193,13 @@ export class ChatService { } let activeSessionId = passedSessionId - let existingSession = null if (activeSessionId) { - existingSession = await tx.agentSession.findUnique({ + const sessionExists = await tx.agentSession.findUnique({ where: { id: activeSessionId }, + select: { id: true }, }) - if (!existingSession) throw new Error('Session not found') + if (!sessionExists) throw new Error('Session not found') } else { const newSession = await tx.agentSession.create({ data: { @@ -212,38 +211,6 @@ export class ChatService { }) activeSessionId = newSession.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, - }, - }) - // Trigger chat workflow const task = await tx.workflowTask.create({ data: { From d326a4cab89d4c10c8f76ef871879e1619e9903d Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 12:04:08 +0800 Subject: [PATCH 07/12] refactor(chatbot): make mapEntryToMessage fully type-safe without any casts --- packages/core/src/chat/chat.ts | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index bbe5b796..59fdcb06 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -9,8 +9,17 @@ type User = Prisma.UserGetPayload> export function mapEntryToMessage( entryRecord: Prisma.AgentSessionEntryGetPayload>, ): ChatMessage { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const entry = entryRecord.entry as any + interface SimpleMessageEntry { + type: 'message' | 'thinking_level_change' + timestamp?: string + thinkingLevel?: string + message?: { + role?: string + content?: string | Array<{ type: string; text?: string; data?: string }> + } + } + + const entry = entryRecord.entry as unknown as SimpleMessageEntry const id = entryRecord.id const timestamp = entry.timestamp || new Date().toISOString() @@ -32,10 +41,8 @@ export function mapEntryToMessage( 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) + .filter((c) => c.type === 'text') + .map((c) => c.text || '') .join('\n') } else if (typeof entry.message?.content === 'string') { content = entry.message.content @@ -53,7 +60,7 @@ export function mapEntryToMessage( role, content, timestamp, - entry, + entry: entry as unknown as PrismaJson.PiSessionEntry, } } From b8eddcd85487521fe5f970a0e9d9bfe4af3bf201 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 12:25:32 +0800 Subject: [PATCH 08/12] feat(chatbot): return rich AgentMessage structure directly from listMessages API --- packages/core/src/chat/chat.test.ts | 73 +++++++++++- packages/core/src/chat/chat.ts | 169 +++++++++++++++++++--------- packages/dtos/src/chat.ts | 21 ++-- 3 files changed, 202 insertions(+), 61 deletions(-) diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index b0d05d22..eaca5071 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -1,6 +1,6 @@ import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' -import { chatService } from '@shumai/core/src/chat/chat' +import { chatService, buildSessionMessages } from './chat' import { describe, expect, it } from 'vitest' describe('ChatService', () => { @@ -256,7 +256,7 @@ describe('ChatService', () => { const messages = await chatService.listMessages(user.id, sessionId) expect(messages).toHaveLength(1) expect(messages[0].role).toBe('user') - expect(messages[0].content).toBe('hello') + expect(messages[0].content).toEqual([{ type: 'text', text: 'hello' }]) }) it('should delete session and cascade', async () => { @@ -280,4 +280,73 @@ describe('ChatService', () => { }) expect(entries).toHaveLength(0) }) + + it('should build session messages correctly handling compaction and custom messages', () => { + const pathEntries = [ + { + id: 'entry-1', + type: 'message', + timestamp: '2026-07-07T00:00:00.000Z', + message: { + role: 'user', + content: 'first message', + }, + }, + { + id: 'entry-compaction', + type: 'compaction', + timestamp: '2026-07-07T00:01:00.000Z', + summary: 'Compacted conversation history', + tokensBefore: 200, + firstKeptEntryId: 'entry-2', + }, + { + id: 'entry-2', + type: 'message', + timestamp: '2026-07-07T00:02:00.000Z', + message: { + role: 'assistant', + content: 'kept message', + }, + }, + { + id: 'entry-3', + type: 'thinking_level_change', + timestamp: '2026-07-07T00:03:00.000Z', + thinkingLevel: 'high', + }, + { + id: 'entry-4', + type: 'branch_summary', + timestamp: '2026-07-07T00:04:00.000Z', + summary: 'Branch summary details', + fromId: 'entry-old', + }, + ] + + const messages = buildSessionMessages(pathEntries) + + expect(messages).toHaveLength(4) + + // 1. Compaction summary message + expect(messages[0].role).toBe('custom') + expect(messages[0].customType).toBe('compaction-summary') + expect(messages[0].content).toBe('Compacted conversation history') + expect((messages[0].details as Record).tokensBefore).toBe(200) + + // 2. Kept entry (entry-2) + expect(messages[1].id).toBe('entry-2') + expect(messages[1].role).toBe('assistant') + expect(messages[1].content).toBe('kept message') + + // 3. Thinking level change (entry-3) + expect(messages[2].role).toBe('thinking_level_change') + expect(messages[2].content).toContain('Thinking level changed to high') + + // 4. Branch summary (entry-4) + expect(messages[3].role).toBe('custom') + expect(messages[3].customType).toBe('branch-summary') + expect(messages[3].content).toBe('Branch summary details') + expect((messages[3].details as Record).fromId).toBe('entry-old') + }) }) diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 59fdcb06..79a5b895 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -6,61 +6,120 @@ import type { ChatRequest, ChatSessionInfo, ChatMessage } from '@shumai/dtos' type User = Prisma.UserGetPayload> +interface SimpleMessageEntry { + type: string + id?: string + timestamp?: string + thinkingLevel?: string + customType?: string + content?: unknown + display?: string + details?: unknown + summary?: string + fromId?: string + tokensBefore?: number + firstKeptEntryId?: string + message?: { + role: string + content: unknown + timestamp?: number + [key: string]: unknown + } +} + +export function buildSessionMessages(pathEntries: SimpleMessageEntry[]): ChatMessage[] { + let compaction: SimpleMessageEntry | null = null + + for (const entry of pathEntries) { + if (entry.type === 'compaction') { + compaction = entry + } + } + + const messages: ChatMessage[] = [] + const appendMessage = (entry: SimpleMessageEntry) => { + const timestampMs = entry.timestamp ? new Date(entry.timestamp).getTime() : Date.now() + if (entry.type === 'message' && entry.message) { + messages.push({ + ...(entry.message as Record), + id: entry.id || 'unknown-id', + role: entry.message.role, + content: entry.message.content as string | unknown[], + timestamp: entry.message.timestamp || timestampMs, + }) + } else if (entry.type === 'custom_message') { + messages.push({ + id: entry.id || 'unknown-id', + role: 'custom', + customType: entry.customType || '', + content: (entry.content as string | unknown[]) || '', + display: entry.display, + details: entry.details, + timestamp: timestampMs, + }) + } else if (entry.type === 'branch_summary' && entry.summary) { + messages.push({ + id: entry.id || 'unknown-id', + role: 'custom', + customType: 'branch-summary', + content: entry.summary, + details: { fromId: entry.fromId }, + timestamp: timestampMs, + }) + } else if (entry.type === 'thinking_level_change' && entry.thinkingLevel) { + messages.push({ + id: entry.id || 'unknown-id', + role: 'thinking_level_change', + content: `Thinking level changed to ${entry.thinkingLevel}`, + timestamp: timestampMs, + }) + } + } + + if (compaction) { + const compactionTimestamp = compaction.timestamp ? new Date(compaction.timestamp).getTime() : Date.now() + messages.push({ + id: compaction.id || 'unknown-id', + role: 'custom', + customType: 'compaction-summary', + content: compaction.summary || '', + details: { tokensBefore: compaction.tokensBefore }, + timestamp: compactionTimestamp, + }) + const compactionIdx = pathEntries.findIndex( + (e) => e.type === 'compaction' && e.id === compaction?.id, + ) + let foundFirstKept = false + for (let i = 0; i < compactionIdx; i++) { + const entry = pathEntries[i] + if (entry.id === compaction.firstKeptEntryId) foundFirstKept = true + if (foundFirstKept) appendMessage(entry) + } + for (let i = compactionIdx + 1; i < pathEntries.length; i++) { + appendMessage(pathEntries[i]) + } + } else { + for (const entry of pathEntries) { + appendMessage(entry) + } + } + + return messages +} + export function mapEntryToMessage( entryRecord: Prisma.AgentSessionEntryGetPayload>, ): ChatMessage { - interface SimpleMessageEntry { - type: 'message' | 'thinking_level_change' - timestamp?: string - thinkingLevel?: string - message?: { - role?: string - content?: string | Array<{ type: string; text?: string; data?: string }> - } + const entryObj = entryRecord.entry as unknown as SimpleMessageEntry + const pathEntries = [{ ...entryObj, id: entryRecord.id }] + const messages = buildSessionMessages(pathEntries) + if (messages.length > 0) { + return messages[0] } - - const entry = entryRecord.entry as unknown as SimpleMessageEntry - 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 - .filter((c) => c.type === 'text') - .map((c) => 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: entry as unknown as PrismaJson.PiSessionEntry, + id: entryRecord.id, + role: 'unknown', + content: '', } } @@ -296,7 +355,15 @@ export class ChatService { orderBy: { id: 'asc' }, }) - return entries.map(mapEntryToMessage) + const pathEntries = entries.map((e) => { + const entryObj = e.entry as unknown as SimpleMessageEntry + return { + ...entryObj, + id: e.id, + } + }) + + return buildSessionMessages(pathEntries) } async deleteSession(userId: string, sessionId: string): Promise { diff --git a/packages/dtos/src/chat.ts b/packages/dtos/src/chat.ts index bcdf4c55..a40b06e3 100644 --- a/packages/dtos/src/chat.ts +++ b/packages/dtos/src/chat.ts @@ -37,12 +37,17 @@ export const chatSessionInfoSchema = z.object({ 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 const chatMessageSchema = z.intersection( + z.object({ + id: z.string(), + }), + z.record(z.string(), z.unknown()), +) -export type ChatMessage = z.infer +export type ChatMessage = { + id: string + role: string + content: string | unknown[] + timestamp?: number + [key: string]: unknown +} From 55026af22ec36faa6dfa2169847bb24d2febf2b8 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 12:30:41 +0800 Subject: [PATCH 09/12] refactor(chatbot): import AgentMessage type statically in DTO layer --- bun.lock | 27 ++++++++--------- packages/core/src/chat/chat.test.ts | 45 +++++++++++++++++++---------- packages/core/src/chat/chat.ts | 14 ++++----- packages/dtos/package.json | 1 + packages/dtos/src/chat.ts | 13 +++------ 5 files changed, 56 insertions(+), 44 deletions(-) diff --git a/bun.lock b/bun.lock index 364519f2..5db1316a 100644 --- a/bun.lock +++ b/bun.lock @@ -37,7 +37,7 @@ }, "apps/agent": { "name": "@shumai/agent-app", - "version": "0.1.5", + "version": "0.1.7", "bin": { "shumai-agent": "./src/index.ts", }, @@ -49,7 +49,7 @@ }, "apps/cli": { "name": "@shumai/cli", - "version": "0.1.5", + "version": "0.1.7", "bin": { "shumai-cli": "./src/index.ts", }, @@ -64,7 +64,7 @@ }, "apps/transcode": { "name": "@shumai/transcode-app", - "version": "0.1.5", + "version": "0.1.7", "bin": { "shumai-transcode": "./src/index.ts", }, @@ -76,7 +76,7 @@ }, "apps/web": { "name": "@shumai/web-app", - "version": "0.1.5", + "version": "0.1.7", "dependencies": { "@shumai/agent": "workspace:*", "@shumai/api": "workspace:*", @@ -91,7 +91,7 @@ }, "packages/agent": { "name": "@shumai/agent", - "version": "0.1.5", + "version": "0.1.7", "dependencies": { "@anthropic-ai/sandbox-runtime": "0.0.52", "@earendil-works/pi-agent-core": "0.78.0", @@ -115,7 +115,7 @@ }, "packages/api": { "name": "@shumai/api", - "version": "0.1.5", + "version": "0.1.7", "dependencies": { "@hono/zod-validator": "0.7.6", "@shumai/core": "workspace:*", @@ -129,7 +129,7 @@ }, "packages/core": { "name": "@shumai/core", - "version": "0.1.5", + "version": "0.1.7", "dependencies": { "@shumai/db": "workspace:*", "@shumai/dtos": "workspace:*", @@ -156,7 +156,7 @@ }, "packages/db": { "name": "@shumai/db", - "version": "0.1.5", + "version": "0.1.7", "dependencies": { "@earendil-works/pi-agent-core": "0.78.0", "@prisma/adapter-pg": "7.8.0", @@ -172,18 +172,19 @@ }, "packages/dtos": { "name": "@shumai/dtos", - "version": "0.1.5", + "version": "0.1.7", "dependencies": { + "@earendil-works/pi-agent-core": "0.78.0", "zod": "4.4.3", }, }, "packages/tableprinter": { "name": "@shumai/tableprinter", - "version": "0.1.5", + "version": "0.1.7", }, "packages/transcode": { "name": "@shumai/transcode", - "version": "0.1.5", + "version": "0.1.7", "dependencies": { "@shumai/core": "workspace:*", "@shumai/db": "workspace:*", @@ -197,7 +198,7 @@ }, "packages/webui": { "name": "@shumai/webui", - "version": "0.1.5", + "version": "0.1.7", "dependencies": { "@base-ui/react": "1.5.0", "@dnd-kit/abstract": "0.4.0", @@ -294,7 +295,7 @@ }, "packages/workflow-core": { "name": "@shumai/workflow-core", - "version": "0.1.5", + "version": "0.1.7", "dependencies": { "@shumai/core": "workspace:*", "@shumai/db": "workspace:*", diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index eaca5071..27f7b7b7 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -255,8 +255,11 @@ describe('ChatService', () => { const messages = await chatService.listMessages(user.id, sessionId) expect(messages).toHaveLength(1) - expect(messages[0].role).toBe('user') - expect(messages[0].content).toEqual([{ type: 'text', text: 'hello' }]) + // Casting to any to access properties of union in test assertions + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const msg = messages[0] as any + expect(msg.role).toBe('user') + expect(msg.content).toEqual([{ type: 'text', text: 'hello' }]) }) it('should delete session and cascade', async () => { @@ -329,24 +332,36 @@ describe('ChatService', () => { expect(messages).toHaveLength(4) // 1. Compaction summary message - expect(messages[0].role).toBe('custom') - expect(messages[0].customType).toBe('compaction-summary') - expect(messages[0].content).toBe('Compacted conversation history') - expect((messages[0].details as Record).tokensBefore).toBe(200) + // Casting to any to access properties of union in test assertions + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const msg0 = messages[0] as any + expect(msg0.role).toBe('custom') + expect(msg0.customType).toBe('compaction-summary') + expect(msg0.content).toBe('Compacted conversation history') + expect((msg0.details as Record).tokensBefore).toBe(200) // 2. Kept entry (entry-2) - expect(messages[1].id).toBe('entry-2') - expect(messages[1].role).toBe('assistant') - expect(messages[1].content).toBe('kept message') + // Casting to any to access properties of union in test assertions + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const msg1 = messages[1] as any + expect(msg1.id).toBe('entry-2') + expect(msg1.role).toBe('assistant') + expect(msg1.content).toBe('kept message') // 3. Thinking level change (entry-3) - expect(messages[2].role).toBe('thinking_level_change') - expect(messages[2].content).toContain('Thinking level changed to high') + // Casting to any to access properties of union in test assertions + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const msg2 = messages[2] as any + expect(msg2.role).toBe('thinking_level_change') + expect(msg2.content).toContain('Thinking level changed to high') // 4. Branch summary (entry-4) - expect(messages[3].role).toBe('custom') - expect(messages[3].customType).toBe('branch-summary') - expect(messages[3].content).toBe('Branch summary details') - expect((messages[3].details as Record).fromId).toBe('entry-old') + // Casting to any to access properties of union in test assertions + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const msg3 = messages[3] as any + expect(msg3.role).toBe('custom') + expect(msg3.customType).toBe('branch-summary') + expect(msg3.content).toBe('Branch summary details') + expect((msg3.details as Record).fromId).toBe('entry-old') }) }) diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 79a5b895..1857bada 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -46,7 +46,7 @@ export function buildSessionMessages(pathEntries: SimpleMessageEntry[]): ChatMes role: entry.message.role, content: entry.message.content as string | unknown[], timestamp: entry.message.timestamp || timestampMs, - }) + } as unknown as ChatMessage) } else if (entry.type === 'custom_message') { messages.push({ id: entry.id || 'unknown-id', @@ -56,7 +56,7 @@ export function buildSessionMessages(pathEntries: SimpleMessageEntry[]): ChatMes display: entry.display, details: entry.details, timestamp: timestampMs, - }) + } as unknown as ChatMessage) } else if (entry.type === 'branch_summary' && entry.summary) { messages.push({ id: entry.id || 'unknown-id', @@ -65,14 +65,14 @@ export function buildSessionMessages(pathEntries: SimpleMessageEntry[]): ChatMes content: entry.summary, details: { fromId: entry.fromId }, timestamp: timestampMs, - }) + } as unknown as ChatMessage) } else if (entry.type === 'thinking_level_change' && entry.thinkingLevel) { messages.push({ id: entry.id || 'unknown-id', role: 'thinking_level_change', content: `Thinking level changed to ${entry.thinkingLevel}`, timestamp: timestampMs, - }) + } as unknown as ChatMessage) } } @@ -85,7 +85,7 @@ export function buildSessionMessages(pathEntries: SimpleMessageEntry[]): ChatMes content: compaction.summary || '', details: { tokensBefore: compaction.tokensBefore }, timestamp: compactionTimestamp, - }) + } as unknown as ChatMessage) const compactionIdx = pathEntries.findIndex( (e) => e.type === 'compaction' && e.id === compaction?.id, ) @@ -118,9 +118,9 @@ export function mapEntryToMessage( } return { id: entryRecord.id, - role: 'unknown', + role: 'user', content: '', - } + } as unknown as ChatMessage } export class ChatService { diff --git a/packages/dtos/package.json b/packages/dtos/package.json index 66190881..6b9e94a9 100644 --- a/packages/dtos/package.json +++ b/packages/dtos/package.json @@ -6,6 +6,7 @@ "main": "./src/index.ts", "types": "./src/index.ts", "dependencies": { + "@earendil-works/pi-agent-core": "0.78.0", "zod": "4.4.3" } } diff --git a/packages/dtos/src/chat.ts b/packages/dtos/src/chat.ts index a40b06e3..9ad1b08a 100644 --- a/packages/dtos/src/chat.ts +++ b/packages/dtos/src/chat.ts @@ -1,4 +1,5 @@ import { z } from 'zod' +import type { AgentMessage } from '@earendil-works/pi-agent-core' export const chatRequestSchema = z .object({ @@ -41,13 +42,7 @@ export const chatMessageSchema = z.intersection( z.object({ id: z.string(), }), - z.record(z.string(), z.unknown()), -) + z.unknown(), +) as unknown as z.ZodType -export type ChatMessage = { - id: string - role: string - content: string | unknown[] - timestamp?: number - [key: string]: unknown -} +export type ChatMessage = AgentMessage & { id: string } From f04729b4bfac3d6745926250d80f6e687e88fd50 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 14:16:31 +0800 Subject: [PATCH 10/12] refactor(chatbot): use SessionTreeEntry type directly in ChatService, removing SimpleMessageEntry --- bun.lock | 1 + packages/core/package.json | 1 + packages/core/src/chat/chat.test.ts | 4 +- packages/core/src/chat/chat.ts | 66 ++++++++++------------------- 4 files changed, 27 insertions(+), 45 deletions(-) diff --git a/bun.lock b/bun.lock index 5db1316a..72d6d422 100644 --- a/bun.lock +++ b/bun.lock @@ -131,6 +131,7 @@ "name": "@shumai/core", "version": "0.1.7", "dependencies": { + "@earendil-works/pi-agent-core": "0.78.0", "@shumai/db": "workspace:*", "@shumai/dtos": "workspace:*", "@sinclair/typebox": "0.34.49", diff --git a/packages/core/package.json b/packages/core/package.json index 58641d57..b2ea3457 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -8,6 +8,7 @@ "dependencies": { "@shumai/db": "workspace:*", "@shumai/dtos": "workspace:*", + "@earendil-works/pi-agent-core": "0.78.0", "@sinclair/typebox": "0.34.49", "adm-zip": "0.5.17", "better-auth": "1.6.11", diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index 27f7b7b7..add00049 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -1,6 +1,6 @@ import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' -import { chatService, buildSessionMessages } from './chat' +import { chatService, buildSessionMessages, type PathEntry } from './chat' import { describe, expect, it } from 'vitest' describe('ChatService', () => { @@ -327,7 +327,7 @@ describe('ChatService', () => { }, ] - const messages = buildSessionMessages(pathEntries) + const messages = buildSessionMessages(pathEntries as unknown as PathEntry[]) expect(messages).toHaveLength(4) diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 1857bada..43543678 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -3,72 +3,52 @@ 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 type { SessionTreeEntry } from '@earendil-works/pi-agent-core' type User = Prisma.UserGetPayload> -interface SimpleMessageEntry { - type: string - id?: string - timestamp?: string - thinkingLevel?: string - customType?: string - content?: unknown - display?: string - details?: unknown - summary?: string - fromId?: string - tokensBefore?: number - firstKeptEntryId?: string - message?: { - role: string - content: unknown - timestamp?: number - [key: string]: unknown - } -} +export type PathEntry = SessionTreeEntry & { id: string } -export function buildSessionMessages(pathEntries: SimpleMessageEntry[]): ChatMessage[] { - let compaction: SimpleMessageEntry | null = null +export function buildSessionMessages(pathEntries: PathEntry[]): ChatMessage[] { + let compaction: (SessionTreeEntry & { type: 'compaction' } & { id: string }) | null = null for (const entry of pathEntries) { if (entry.type === 'compaction') { - compaction = entry + compaction = entry as SessionTreeEntry & { type: 'compaction' } & { id: string } } } const messages: ChatMessage[] = [] - const appendMessage = (entry: SimpleMessageEntry) => { - const timestampMs = entry.timestamp ? new Date(entry.timestamp).getTime() : Date.now() - if (entry.type === 'message' && entry.message) { + const appendMessage = (entry: PathEntry) => { + const timestampMs = new Date(entry.timestamp).getTime() + if (entry.type === 'message') { messages.push({ - ...(entry.message as Record), - id: entry.id || 'unknown-id', - role: entry.message.role, - content: entry.message.content as string | unknown[], + ...entry.message, + id: entry.id, timestamp: entry.message.timestamp || timestampMs, } as unknown as ChatMessage) } else if (entry.type === 'custom_message') { messages.push({ - id: entry.id || 'unknown-id', + id: entry.id, role: 'custom', - customType: entry.customType || '', - content: (entry.content as string | unknown[]) || '', + customType: entry.customType, + content: entry.content, display: entry.display, - details: entry.details, + details: entry.details as Record | undefined, timestamp: timestampMs, } as unknown as ChatMessage) - } else if (entry.type === 'branch_summary' && entry.summary) { + } else if (entry.type === 'branch_summary') { messages.push({ - id: entry.id || 'unknown-id', + id: entry.id, role: 'custom', customType: 'branch-summary', content: entry.summary, details: { fromId: entry.fromId }, timestamp: timestampMs, } as unknown as ChatMessage) - } else if (entry.type === 'thinking_level_change' && entry.thinkingLevel) { + } else if (entry.type === 'thinking_level_change') { messages.push({ - id: entry.id || 'unknown-id', + id: entry.id, role: 'thinking_level_change', content: `Thinking level changed to ${entry.thinkingLevel}`, timestamp: timestampMs, @@ -77,12 +57,12 @@ export function buildSessionMessages(pathEntries: SimpleMessageEntry[]): ChatMes } if (compaction) { - const compactionTimestamp = compaction.timestamp ? new Date(compaction.timestamp).getTime() : Date.now() + const compactionTimestamp = new Date(compaction.timestamp).getTime() messages.push({ - id: compaction.id || 'unknown-id', + id: compaction.id, role: 'custom', customType: 'compaction-summary', - content: compaction.summary || '', + content: compaction.summary, details: { tokensBefore: compaction.tokensBefore }, timestamp: compactionTimestamp, } as unknown as ChatMessage) @@ -110,7 +90,7 @@ export function buildSessionMessages(pathEntries: SimpleMessageEntry[]): ChatMes export function mapEntryToMessage( entryRecord: Prisma.AgentSessionEntryGetPayload>, ): ChatMessage { - const entryObj = entryRecord.entry as unknown as SimpleMessageEntry + const entryObj = entryRecord.entry as unknown as SessionTreeEntry const pathEntries = [{ ...entryObj, id: entryRecord.id }] const messages = buildSessionMessages(pathEntries) if (messages.length > 0) { @@ -356,7 +336,7 @@ export class ChatService { }) const pathEntries = entries.map((e) => { - const entryObj = e.entry as unknown as SimpleMessageEntry + const entryObj = e.entry as unknown as SessionTreeEntry return { ...entryObj, id: e.id, From 985bf0170cc7daa5d60382be87b3a3b60b928b9f Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 20:59:25 +0800 Subject: [PATCH 11/12] fix(api): prevent SSE connection resource leak by checking stream.aborted --- packages/api/src/chat.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/api/src/chat.ts b/packages/api/src/chat.ts index 580387b7..8f806bce 100644 --- a/packages/api/src/chat.ts +++ b/packages/api/src/chat.ts @@ -42,6 +42,9 @@ const route = new Hono<{ Variables: { user: User } }>() const startTime = Date.now() while (Date.now() - startTime < timeoutMs) { + if (stream.aborted) { + break + } // Query new entries from the DB const newEntries = await prisma.agentSessionEntry.findMany({ where: { From 10279d74bcf05a1b80a0e74a245f8f5812f65065 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 21:51:10 +0800 Subject: [PATCH 12/12] feat(chatbot): append turn-specific agentsInstruction as a custom message session entry --- packages/agent/src/activities/agent.ts | 18 +++++++++++--- .../agent-chat-prompt-builder.test.ts | 19 +++++++++++++++ .../workflows/agent-chat-prompt-builder.ts | 24 +++++++++++++++++++ .../agent/src/workflows/agent-chat.test.ts | 2 ++ packages/agent/src/workflows/agent-chat.ts | 3 +++ 5 files changed, 63 insertions(+), 3 deletions(-) diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index 57048a2f..54d6b1b3 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -88,9 +88,8 @@ If you need to create files in the local filesystem (for example, a temporary fi systemPrompt = `${systemPrompt}\n\nAgent Personality and Core Instructions:\n${agent.soul}` } - if (params.agentsInstruction) { - systemPrompt = `${systemPrompt}\n\nContext and Instructions:\n${params.agentsInstruction}` - } + // Note: params.agentsInstruction is no longer appended to systemPrompt here. + // Instead, it is persisted as a custom message session entry in the conversation history below. const modelConfig = agent.modelRef?.config if (modelConfig?.input) { @@ -145,6 +144,19 @@ If you need to create files in the local filesystem (for example, a temporary fi } try { + if (params.agentsInstruction && params.agentsInstruction.trim()) { + const storage = session.getStorage() + const parentId = await storage.getLeafId() + await storage.appendEntry({ + id: ulid(), + type: 'custom_message', + parentId, + timestamp: new Date().toISOString(), + customType: 'context', + content: params.agentsInstruction.trim(), + } as unknown as SessionTreeEntry) + } + const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass }) const sessionEntries = await session.getEntries() diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts index 2714ec40..aba32e64 100644 --- a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts @@ -84,4 +84,23 @@ describe('AgentChatPromptBuilder', () => { expect(result).toContain('Attached Files:\n- file1.txt\n- file2.png') expect(result).toContain('Referenced Workspace Assets:\n- folder1\n- file3.mp4') }) + + it('should build prompt for continuation mode returning only turn-specific modifications', () => { + const builder = new AgentChatPromptBuilder('a1') + .withContinuation(true) + .withAssetDetails('movie.mp4', 'video/mp4', 12.34) + .withPathContext('src/main.ts') + .withCommentTimestamp(8.2) + .withAttachedFiles(['- file1.txt']) + .withReferencedAssets(['- folder1']) + const result = builder.build() + + expect(result).not.toContain('The user is discussing an asset with ID:') + expect(result).not.toContain('File Name: movie.mp4') + expect(result).not.toContain('Asset Path Context:') + expect(result).toContain('Comment Timestamp: 8.20 seconds') + expect(result).toContain('[Context: New Attached Files & Referenced Assets]') + expect(result).toContain('Attached Files:\n- file1.txt') + expect(result).toContain('Referenced Workspace Assets:\n- folder1') + }) }) diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.ts index aee76c26..9b4f654c 100644 --- a/packages/agent/src/workflows/agent-chat-prompt-builder.ts +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.ts @@ -25,10 +25,17 @@ export class AgentChatPromptBuilder { private attachedFiles: string[] = [] private referencedAssets: string[] = [] + private isContinuation = false + constructor(assetId: string) { this.assetId = assetId } + withContinuation(isContinuation: boolean): this { + this.isContinuation = isContinuation + return this + } + withAttachedFiles(files?: string[]): this { if (files) { this.attachedFiles = files @@ -68,6 +75,23 @@ export class AgentChatPromptBuilder { } build(): string { + if (this.isContinuation) { + let instruction = '' + if (this.commentTimestamp !== undefined) { + instruction += `Comment Timestamp: ${this.commentTimestamp.toFixed(2)} seconds` + } + if (this.attachedFiles.length > 0 || this.referencedAssets.length > 0) { + instruction += `\n\n[Context: New Attached Files & Referenced Assets]` + if (this.attachedFiles.length > 0) { + instruction += `\nAttached Files:\n${this.attachedFiles.join('\n')}` + } + if (this.referencedAssets.length > 0) { + instruction += `\nReferenced Workspace Assets:\n${this.referencedAssets.join('\n')}` + } + } + return instruction.trim() + } + let instruction = `The user is discussing an asset with ID: ${this.assetId}.` if (this.assetName) { instruction += `\nFile Name: ${this.assetName}` diff --git a/packages/agent/src/workflows/agent-chat.test.ts b/packages/agent/src/workflows/agent-chat.test.ts index d5682e4b..8141a66f 100644 --- a/packages/agent/src/workflows/agent-chat.test.ts +++ b/packages/agent/src/workflows/agent-chat.test.ts @@ -185,6 +185,7 @@ describe('Agent Chat Workflow', () => { expect(mockActivities.initializeAgentSessionActivity).not.toHaveBeenCalled() const expectedInstruction2 = new AgentChatPromptBuilder('a1') + .withContinuation(true) .withPathContext('Path: folder/subfolder/file.png') .withAssetDetails('test-file.png', 'image/png', undefined) .withCommentTimestamp(null) @@ -442,6 +443,7 @@ describe('Agent Chat Workflow', () => { // Verify prompt builder is populated and workflow runs agentChatActivity with context instruction const expectedInstruction = new AgentChatPromptBuilder('a1') + .withContinuation(true) .withPathContext('folder/subfolder/file.png') .withAssetDetails('test-file.png', 'image/png', undefined) .withCommentTimestamp(undefined) diff --git a/packages/agent/src/workflows/agent-chat.ts b/packages/agent/src/workflows/agent-chat.ts index 64d14925..c0893b21 100644 --- a/packages/agent/src/workflows/agent-chat.ts +++ b/packages/agent/src/workflows/agent-chat.ts @@ -91,6 +91,7 @@ export async function agentChat(task: WorkflowTask): Promise { const teamId = asset.project.teamId // 4. Initialize Session if missing + let isNewChat = !payload.agent?.sessionId if (!sessionId) { if (!userCommentId) { throw ApplicationFailure.create({ @@ -104,6 +105,7 @@ export async function agentChat(task: WorkflowTask): Promise { userCommentId, userId: payload.agent?.userId, }) + isNewChat = true } // 4b. Fetch Agent Context @@ -151,6 +153,7 @@ export async function agentChat(task: WorkflowTask): Promise { } const instruction = new AgentChatPromptBuilder(asset.id) + .withContinuation(!isNewChat) .withPathContext(pathContext) .withAssetDetails(asset.name, asset.mediaType, duration) .withCommentTimestamp(commentTimestamp)