Merge pull request #187 from shumaiOne/fix/chat-api-db-queries

refactor(api/chat): remove direct Prisma query from API layer
This commit is contained in:
Yiling-J
2026-07-14 16:47:44 +08:00
committed by GitHub
6 changed files with 330 additions and 147 deletions
+4 -1
View File
@@ -195,7 +195,10 @@ describe('Agent Activities', () => {
} as unknown as AgentExecutionContext
const addEventListenerSpy = vi.spyOn(mockTemporalContext.cancellationSignal, 'addEventListener')
const removeEventListenerSpy = vi.spyOn(mockTemporalContext.cancellationSignal, 'removeEventListener')
const removeEventListenerSpy = vi.spyOn(
mockTemporalContext.cancellationSignal,
'removeEventListener',
)
const executionPromise = agentChatActivity({
teamId: 't1',
+31 -75
View File
@@ -3,12 +3,7 @@ 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/workflow-core', () => ({
workflowService: {
cancel: vi.fn(),
},
}))
import type { ChatMessage } from '@shumai/dtos'
vi.mock('@shumai/core/src/chat/chat', async (importOriginal) => {
const original = await importOriginal<typeof import('@shumai/core/src/chat/chat')>()
@@ -19,24 +14,13 @@ vi.mock('@shumai/core/src/chat/chat', async (importOriginal) => {
listMessages: vi.fn(),
deleteSession: vi.fn(),
startOrContinueChat: vi.fn(),
getNewSessionMessages: vi.fn(),
getChatWorkflowStatus: vi.fn(),
abortSession: vi.fn(),
},
}
})
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/db', () => ({
prisma: {
agentSessionEntry: {
findMany: vi.fn(),
},
workflowTask: {
findUnique: vi.fn(),
findFirst: vi.fn(),
update: vi.fn(),
},
},
}))
import { prisma, type WorkflowTask } from '@shumai/db'
describe('Chat API', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
@@ -121,29 +105,26 @@ describe('Chat API', () => {
taskId: 'task1',
})
const mockEntries = [
{
id: 'entry1',
sessionId: 'session1',
entry: {
type: 'message',
message: {
vi.mocked(chatService.getNewSessionMessages)
.mockResolvedValueOnce({
messages: [
{
id: 'entry1',
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)
content: 'hi',
} as unknown as ChatMessage,
],
lastEntryId: 'entry1',
})
.mockResolvedValue({
messages: [],
lastEntryId: 'entry1',
})
const mockTask = {
id: 'task1',
vi.mocked(chatService.getChatWorkflowStatus).mockResolvedValue({
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('/teams/team1/chat', {
method: 'POST',
@@ -173,19 +154,15 @@ describe('Chat API', () => {
taskId: 'task1',
})
// No new entries initially
// Mock returns a simple array instead of full PrismaPromise, so we bypass type safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.agentSessionEntry.findMany).mockResolvedValue([] as any)
vi.mocked(chatService.getNewSessionMessages).mockResolvedValue({
messages: [],
lastEntryId: null,
})
const mockTask = {
id: 'task1',
vi.mocked(chatService.getChatWorkflowStatus).mockResolvedValue({
status: 'completed',
output: {},
}
// Mock returns a simple task object instead of PrismaPromise, so we bypass type safety.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.workflowTask.findUnique).mockResolvedValue(mockTask as any)
})
const res = await app.request('/teams/team1/chat', {
method: 'POST',
@@ -207,23 +184,7 @@ describe('Chat API', () => {
describe('POST /teams/:teamId/chat/sessions/:sessionId/abort', () => {
it('aborts an active chat session and updates task status', async () => {
const mockActiveTask = {
id: 'task1',
status: 'processing',
type: 'chat',
sessionId: 'session1',
payload: {
agent: {
sessionId: 'session1',
},
},
}
vi.mocked(prisma.workflowTask.findFirst).mockResolvedValue(
mockActiveTask as unknown as WorkflowTask,
)
vi.mocked(prisma.workflowTask.update).mockResolvedValue({} as unknown as WorkflowTask)
const { workflowService } = await import('@shumai/workflow-core')
vi.mocked(chatService.abortSession).mockResolvedValue(undefined)
const res = await app.request('/teams/team1/chat/sessions/session1/abort', {
method: 'POST',
@@ -233,18 +194,13 @@ describe('Chat API', () => {
const data = await res.json()
expect(data).toEqual({ success: true })
expect(workflowService.cancel).toHaveBeenCalledWith('task1')
expect(prisma.workflowTask.update).toHaveBeenCalledWith({
where: { id: 'task1' },
data: {
status: 'failed',
output: { error: 'aborted' },
},
})
expect(chatService.abortSession).toHaveBeenCalledWith('user1', 'session1')
})
it('returns 404 if no active task is found for the session', async () => {
vi.mocked(prisma.workflowTask.findFirst).mockResolvedValue(null)
vi.mocked(chatService.abortSession).mockRejectedValue(
new Error('No active execution found for this session'),
)
const res = await app.request('/teams/team1/chat/sessions/session1/abort', {
method: 'POST',
+33 -54
View File
@@ -1,12 +1,10 @@
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 { chatService } from '@shumai/core/src/chat/chat'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { chatRequestSchema, paginationParamsSchema } from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { workflowService } from '@shumai/workflow-core'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -89,19 +87,14 @@ const route = new Hono<{ Variables: { user: User } }>()
if (stream.aborted) {
break
}
// Query new entries from the DB
const newEntries = await prisma.agentSessionEntry.findMany({
where: {
sessionId,
...(lastEntryId ? { id: { gt: lastEntryId } } : {}),
},
orderBy: { id: 'asc' },
})
// Query new entries from the DB via chatService
const { messages, lastEntryId: newLastId } = await chatService.getNewSessionMessages(
sessionId,
lastEntryId || undefined,
)
if (newEntries.length > 0) {
for (const record of newEntries) {
const message = mapEntryToMessage(record)
if (!message) continue
if (messages.length > 0) {
for (const message of messages) {
await stream.writeSSE({
data: JSON.stringify({
type: 'entry',
@@ -109,7 +102,6 @@ const route = new Hono<{ Variables: { user: User } }>()
}),
})
}
lastEntryId = newEntries[newEntries.length - 1].id
} else {
await stream.writeSSE({
data: JSON.stringify({
@@ -118,24 +110,20 @@ const route = new Hono<{ Variables: { user: User } }>()
})
}
// Check if workflow has finished
const task = await prisma.workflowTask.findUnique({
where: { id: taskId },
select: { status: true, output: true },
})
if (newLastId) {
lastEntryId = newLastId
}
// Check if workflow has finished via chatService
const task = await chatService.getChatWorkflowStatus(taskId)
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)
if (!message) continue
const { messages: finalMessages } = await chatService.getNewSessionMessages(
sessionId,
lastEntryId || undefined,
)
for (const message of finalMessages) {
await stream.writeSSE({
data: JSON.stringify({
type: 'entry',
@@ -145,7 +133,7 @@ const route = new Hono<{ Variables: { user: User } }>()
}
// Send done status
const output = task.output as Record<string, unknown> | null
const output = task.output
await stream.writeSSE({
data: JSON.stringify({
type: 'done',
@@ -186,29 +174,20 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId,
})
const taskToAbort = await prisma.workflowTask.findFirst({
where: {
status: { in: ['pending', 'processing'] },
type: 'chat',
sessionId,
},
})
if (!taskToAbort) {
return c.json({ error: 'No active execution found for this session' }, 404)
try {
await chatService.abortSession(user.id, sessionId)
return c.json({ success: true }, 200)
} catch (error: unknown) {
const err = error as Error
if (
err.message === 'Session not found' ||
err.message === 'Unauthorized session access' ||
err.message === 'No active execution found for this session'
) {
return c.json({ error: err.message }, 404)
}
throw error
}
await workflowService.cancel(taskToAbort.id)
await prisma.workflowTask.update({
where: { id: taskToAbort.id },
data: {
status: 'failed',
output: { error: 'aborted' },
},
})
return c.json({ success: true }, 200)
})
export default route
+168 -2
View File
@@ -1,7 +1,8 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { chatService, buildSessionMessages, mapEntryToMessage, type PathEntry } from './chat'
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { workflowService } from '@shumai/workflow-core'
describe('ChatService', () => {
setupTestDbHooks()
@@ -110,7 +111,7 @@ describe('ChatService', () => {
})
expect(task).toBeDefined()
expect(task?.type).toBe('chat')
expect(task?.status).toBe('pending')
expect(['pending', 'processing']).toContain(task?.status)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const taskPayload = task?.payload as any
expect(taskPayload?.agent?.prompt).toBe('hello world')
@@ -476,4 +477,169 @@ describe('ChatService', () => {
expect(msg3.content).toBe('Branch summary details')
expect((msg3.details as Record<string, unknown>).fromId).toBe('entry-old')
})
describe('getNewSessionMessages', () => {
it('returns new messages and lastEntryId', async () => {
const { user, team, project } = await setupBasicData()
const { sessionId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello',
projectId: project.id,
})
// Insert two entries
const entry1 = await prisma.agentSessionEntry.create({
data: {
id: 'entry-id-1',
sessionId,
entry: {
type: 'message',
id: 'entry-id-1',
parentId: null,
timestamp: new Date().toISOString(),
message: {
role: 'user',
content: [{ type: 'text', text: 'msg 1' }],
},
} as unknown as PrismaJson.PiSessionEntry,
},
})
const entry2 = await prisma.agentSessionEntry.create({
data: {
id: 'entry-id-2',
sessionId,
entry: {
type: 'message',
id: 'entry-id-2',
parentId: 'entry-id-1',
timestamp: new Date().toISOString(),
message: {
role: 'assistant',
content: [{ type: 'text', text: 'msg 2' }],
},
} as unknown as PrismaJson.PiSessionEntry,
},
})
// 1. Get all messages
const res1 = await chatService.getNewSessionMessages(sessionId)
expect(res1.messages).toHaveLength(2)
expect(res1.lastEntryId).toBe(entry2.id)
expect(res1.messages[0].id).toBe(entry1.id)
// 2. Get with lastEntryId
const res2 = await chatService.getNewSessionMessages(sessionId, entry1.id)
expect(res2.messages).toHaveLength(1)
expect(res2.lastEntryId).toBe(entry2.id)
expect(res2.messages[0].id).toBe(entry2.id)
// 3. Get with latest lastEntryId
const res3 = await chatService.getNewSessionMessages(sessionId, entry2.id)
expect(res3.messages).toHaveLength(0)
expect(res3.lastEntryId).toBe(entry2.id)
})
})
describe('getChatWorkflowStatus', () => {
it('returns task status and output', async () => {
const { team, project } = await setupBasicData()
const rootFolder = await prisma.asset.findFirst({
where: { projectId: project.id, type: 'root' },
})
const task = await prisma.workflowTask.create({
data: {
assetId: rootFolder!.id,
type: 'chat',
status: 'completed',
teamId: team.id,
projectId: project.id,
payload: { projectId: project.id },
output: { success: true },
},
})
const statusRes = await chatService.getChatWorkflowStatus(task.id)
expect(statusRes).not.toBeNull()
expect(statusRes?.status).toBe('completed')
expect(statusRes?.output).toEqual({ success: true })
})
it('returns null if task not found', async () => {
const statusRes = await chatService.getChatWorkflowStatus('non-existent-task')
expect(statusRes).toBeNull()
})
})
describe('abortSession', () => {
it('cancels active task and marks failed/aborted', async () => {
const { user, team, project } = await setupBasicData()
const { sessionId, taskId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'long execution',
projectId: project.id,
})
// Mark the task as processing
await prisma.workflowTask.update({
where: { id: taskId },
data: { status: 'processing' },
})
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
await chatService.abortSession(user.id, sessionId)
expect(cancelSpy).toHaveBeenCalledWith(taskId)
const updatedTask = await prisma.workflowTask.findUnique({
where: { id: taskId },
})
expect(updatedTask?.status).toBe('failed')
expect(updatedTask?.output).toEqual({ error: 'aborted' })
cancelSpy.mockRestore()
})
it('throws error if session not found', async () => {
await expect(chatService.abortSession('user-1', 'non-existent-session')).rejects.toThrow(
'Session not found',
)
})
it('throws error if unauthorized', async () => {
const { team, project } = await setupBasicData()
const otherUser = await prisma.user.create({
data: { name: 'Other User', email: `other-${Date.now()}@example.com`, password: 'pw' },
})
const { sessionId } = await chatService.startOrContinueChat(otherUser, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello',
projectId: project.id,
})
await expect(chatService.abortSession('different-user-id', sessionId)).rejects.toThrow(
'Unauthorized session access',
)
})
it('throws error if no active task', async () => {
const { user, team, project } = await setupBasicData()
const { sessionId, taskId } = await chatService.startOrContinueChat(user, team.id, {
agentId: 'test-agent-id',
textPrompt: 'hello',
projectId: project.id,
})
// Complete the task
await prisma.workflowTask.update({
where: { id: taskId },
data: { status: 'completed' },
})
await expect(chatService.abortSession(user.id, sessionId)).rejects.toThrow(
'No active execution found for this session',
)
})
})
})
+79
View File
@@ -4,6 +4,7 @@ import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/a
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'
import { workflowService } from '@shumai/workflow-core'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -395,6 +396,84 @@ export class ChatService {
where: { id: sessionId },
})
}
async getNewSessionMessages(
sessionId: string,
lastEntryId?: string,
): Promise<{ messages: ChatMessage[]; lastEntryId: string | null }> {
const entries = await this.prismaClient.agentSessionEntry.findMany({
where: {
sessionId,
...(lastEntryId ? { id: { gt: lastEntryId } } : {}),
},
orderBy: { id: 'asc' },
})
if (entries.length === 0) {
return { messages: [], lastEntryId: lastEntryId ?? null }
}
const messages: ChatMessage[] = []
for (const entry of entries) {
const message = mapEntryToMessage(entry)
if (message) {
messages.push(message)
}
}
return {
messages,
lastEntryId: entries[entries.length - 1].id,
}
}
async getChatWorkflowStatus(
taskId: string,
): Promise<{ status: string | null; output: Record<string, unknown> | null } | null> {
const task = await this.prismaClient.workflowTask.findUnique({
where: { id: taskId },
select: { status: true, output: true },
})
if (!task) return null
return {
status: task.status,
output: task.output as Record<string, unknown> | null,
}
}
async abortSession(userId: string, sessionId: string): Promise<void> {
const session = await this.prismaClient.agentSession.findUnique({
where: { id: sessionId },
})
if (!session) {
throw new Error('Session not found')
}
if (session.userId !== userId) {
throw new Error('Unauthorized session access')
}
const taskToAbort = await this.prismaClient.workflowTask.findFirst({
where: {
status: { in: ['pending', 'processing'] },
type: 'chat',
sessionId,
},
})
if (!taskToAbort) {
throw new Error('No active execution found for this session')
}
await workflowService.cancel(taskToAbort.id)
await this.prismaClient.workflowTask.update({
where: { id: taskToAbort.id },
data: {
status: 'failed',
output: { error: 'aborted' },
},
})
}
}
export const chatService = new ChatService()
+15 -15
View File
@@ -1,11 +1,11 @@
import { client } from '@/ui/api/client'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
@@ -15,16 +15,16 @@ import { useDroppable } from '@dnd-kit/react'
import type { ChatMessage } from '@shumai/dtos'
import { useQuery } from '@tanstack/react-query'
import {
ArrowLeft,
ArrowUp,
Bot,
Brain,
ChevronDown,
History,
Loader2,
Plus,
Trash2,
Wrench,
ArrowLeft,
ArrowUp,
Bot,
Brain,
ChevronDown,
History,
Loader2,
Plus,
Trash2,
Wrench,
} from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import Markdown from 'react-markdown'