refactor(api/chat): remove direct Prisma query from API layer

API layer routes in packages/api/src/chat.ts accessed the database directly via prisma, violating communication layer boundaries.

This refactoring migrates these queries to packages/core/src/chat/chat.ts:
- Added getNewSessionMessages to fetch mapped SSE entries.
- Added getChatWorkflowStatus to check task completions.
- Added abortSession to handle workflow cancellation and task updates in core.
- Updated both core and API tests to match refactored signatures and mock boundaries.
This commit is contained in:
yiling
2026-07-14 16:40:55 +08:00
parent b53b76bc6e
commit 6643d63e81
6 changed files with 330 additions and 147 deletions
+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