diff --git a/packages/api/src/chat.test.ts b/packages/api/src/chat.test.ts index a1dad133..823d4c65 100644 --- a/packages/api/src/chat.test.ts +++ b/packages/api/src/chat.test.ts @@ -43,7 +43,7 @@ describe('Chat API', () => { vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) }) - describe('GET /chat/sessions', () => { + describe('GET /teams/:teamId/chat/sessions', () => { it('returns list of sessions', async () => { const mockSessions = { data: [ @@ -62,15 +62,16 @@ describe('Chat API', () => { // 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') + const res = await app.request('/teams/team1/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') + expect(chatService.listSessions).toHaveBeenCalledWith('user1', 'team1', expect.any(Object)) }) }) - describe('GET /chat/sessions/:sessionId/messages', () => { + describe('GET /teams/:teamId/chat/sessions/:sessionId/messages', () => { it('returns list of messages', async () => { const mockMessages = [ { @@ -84,27 +85,28 @@ describe('Chat API', () => { // 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') + const res = await app.request('/teams/team1/chat/sessions/session1/messages') expect(res.status).toBe(200) const data = await res.json() expect(data).toHaveLength(1) expect(data[0].content).toBe('hello') + expect(chatService.listMessages).toHaveBeenCalledWith('user1', 'team1', 'session1') }) }) - describe('DELETE /chat/sessions/:sessionId', () => { + describe('DELETE /teams/:teamId/chat/sessions/:sessionId', () => { it('deletes a session', async () => { vi.mocked(chatService.deleteSession).mockResolvedValue(undefined) - const res = await app.request('/chat/sessions/session1', { + const res = await app.request('/teams/team1/chat/sessions/session1', { method: 'DELETE', }) expect(res.status).toBe(204) - expect(chatService.deleteSession).toHaveBeenCalledWith('user1', 'session1') + expect(chatService.deleteSession).toHaveBeenCalledWith('user1', 'team1', 'session1') }) }) - describe('POST /chat', () => { + describe('POST /teams/:teamId/chat', () => { it('starts or continues chat and returns stream', async () => { vi.mocked(chatService.startOrContinueChat).mockResolvedValue({ sessionId: 'session1', @@ -135,7 +137,7 @@ describe('Chat API', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any vi.mocked(prisma.workflowTask.findUnique).mockResolvedValue(mockTask as any) - const res = await app.request('/chat', { + const res = await app.request('/teams/team1/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ @@ -150,6 +152,11 @@ describe('Chat API', () => { const text = await res.text() expect(text).toContain('data:') expect(text).toContain('entry1') + expect(chatService.startOrContinueChat).toHaveBeenCalledWith( + expect.objectContaining({ id: 'user1' }), + 'team1', + expect.any(Object), + ) }) }) }) diff --git a/packages/api/src/chat.ts b/packages/api/src/chat.ts index d8510dad..b517817b 100644 --- a/packages/api/src/chat.ts +++ b/packages/api/src/chat.ts @@ -3,38 +3,71 @@ 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 { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' 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) => { + .get('/teams/:teamId/chat/sessions', zValidator('query', paginationParamsSchema), async (c) => { const user = c.get('user') + const teamId = c.req.param('teamId') const query = c.req.valid('query') - const res = await chatService.listSessions(user.id, query) + await authzService.hasPermission({ + user, + permission: Permission.Read, + type: ResourceType.Team, + id: teamId, + }) + + const res = await chatService.listSessions(user.id, teamId, query) return c.json(res, 200) }) - .get('/chat/sessions/:sessionId/messages', async (c) => { + .get('/teams/:teamId/chat/sessions/:sessionId/messages', async (c) => { const user = c.get('user') + const teamId = c.req.param('teamId') const sessionId = c.req.param('sessionId') - const res = await chatService.listMessages(user.id, sessionId) + await authzService.hasPermission({ + user, + permission: Permission.Read, + type: ResourceType.Team, + id: teamId, + }) + + const res = await chatService.listMessages(user.id, teamId, sessionId) return c.json(res, 200) }) - .delete('/chat/sessions/:sessionId', async (c) => { + .delete('/teams/:teamId/chat/sessions/:sessionId', async (c) => { const user = c.get('user') + const teamId = c.req.param('teamId') const sessionId = c.req.param('sessionId') - await chatService.deleteSession(user.id, sessionId) + await authzService.hasPermission({ + user, + permission: Permission.Read, + type: ResourceType.Team, + id: teamId, + }) + + await chatService.deleteSession(user.id, teamId, sessionId) return new Response(null, { status: 204 }) }) - .post('/chat', zValidator('json', chatRequestSchema), async (c) => { + .post('/teams/:teamId/chat', zValidator('json', chatRequestSchema), async (c) => { const user = c.get('user') + const teamId = c.req.param('teamId') const req = c.req.valid('json') - const { sessionId, taskId } = await chatService.startOrContinueChat(user, req) + await authzService.hasPermission({ + user, + permission: Permission.Read, + type: ResourceType.Team, + id: teamId, + }) + + const { sessionId, taskId } = await chatService.startOrContinueChat(user, teamId, req) c.header('x-session-id', sessionId) diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index 5310b450..280dfcb4 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -73,9 +73,9 @@ describe('ChatService', () => { } it('should start a new chat session and trigger workflow', async () => { - const { user, project, rootFolder } = await setupBasicData() + const { user, team, project, rootFolder } = await setupBasicData() - const { sessionId, taskId } = await chatService.startOrContinueChat(user, { + const { sessionId, taskId } = await chatService.startOrContinueChat(user, team.id, { agentId: 'test-agent-id', textPrompt: 'hello world', projectId: project.id, @@ -117,10 +117,10 @@ describe('ChatService', () => { }) it('should continue an existing chat session', async () => { - const { user, project } = await setupBasicData() + const { user, team, project } = await setupBasicData() // Start - const { sessionId } = await chatService.startOrContinueChat(user, { + const { sessionId } = await chatService.startOrContinueChat(user, team.id, { agentId: 'test-agent-id', textPrompt: 'first message', projectId: project.id, @@ -129,6 +129,7 @@ describe('ChatService', () => { // Continue const { sessionId: nextSessionId, taskId: nextTaskId } = await chatService.startOrContinueChat( user, + team.id, { agentId: 'test-agent-id', textPrompt: 'second message', @@ -156,7 +157,7 @@ describe('ChatService', () => { }) it('should inject context of referenced assets and attached files', async () => { - const { user, project, rootFolder } = await setupBasicData() + const { user, team, project, rootFolder } = await setupBasicData() const childFolder = await prisma.asset.create({ data: { @@ -186,7 +187,7 @@ describe('ChatService', () => { }, }) - const { taskId } = await chatService.startOrContinueChat(user, { + const { taskId } = await chatService.startOrContinueChat(user, team.id, { agentId: 'test-agent-id', textPrompt: 'process file', projectId: project.id, @@ -207,15 +208,15 @@ describe('ChatService', () => { }) it('should list sessions of a user and only return chat type sessions', async () => { - const { user, project } = await setupBasicData() + const { user, team, project } = await setupBasicData() - await chatService.startOrContinueChat(user, { + await chatService.startOrContinueChat(user, team.id, { agentId: 'test-agent-id', textPrompt: 'chat 1', projectId: project.id, }) - await chatService.startOrContinueChat(user, { + await chatService.startOrContinueChat(user, team.id, { agentId: 'test-agent-id', textPrompt: 'chat 2', projectId: project.id, @@ -232,14 +233,14 @@ describe('ChatService', () => { }, }) - const list = await chatService.listSessions(user.id, { first: 10 }) + const list = await chatService.listSessions(user.id, team.id, { first: 10 }) expect(list.data).toHaveLength(2) }) it('should list messages mapped correctly', async () => { - const { user, project } = await setupBasicData() + const { user, team, project } = await setupBasicData() - const { sessionId } = await chatService.startOrContinueChat(user, { + const { sessionId } = await chatService.startOrContinueChat(user, team.id, { agentId: 'test-agent-id', textPrompt: 'hello', projectId: project.id, @@ -264,7 +265,7 @@ describe('ChatService', () => { }, }) - const messages = await chatService.listMessages(user.id, sessionId) + const messages = await chatService.listMessages(user.id, team.id, sessionId) expect(messages).toHaveLength(1) // Casting to any to access properties of union in test assertions // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -274,9 +275,9 @@ describe('ChatService', () => { }) it('should hide customType context messages', async () => { - const { user, project } = await setupBasicData() + const { user, team, project } = await setupBasicData() - const { sessionId } = await chatService.startOrContinueChat(user, { + const { sessionId } = await chatService.startOrContinueChat(user, team.id, { agentId: 'test-agent-id', textPrompt: 'hello', projectId: project.id, @@ -352,7 +353,7 @@ describe('ChatService', () => { }) // Verify listMessages returns only the user, thinking level change and custom display entry message - const messages = await chatService.listMessages(user.id, sessionId) + const messages = await chatService.listMessages(user.id, team.id, sessionId) expect(messages).toHaveLength(3) expect(messages[0].id).toBe('test-entry-1-user') expect(messages[1].id).toBe('test-entry-3-thinking') @@ -374,15 +375,15 @@ describe('ChatService', () => { }) it('should delete session and cascade', async () => { - const { user, project } = await setupBasicData() + const { user, team, project } = await setupBasicData() - const { sessionId } = await chatService.startOrContinueChat(user, { + const { sessionId } = await chatService.startOrContinueChat(user, team.id, { agentId: 'test-agent-id', textPrompt: 'to delete', projectId: project.id, }) - await chatService.deleteSession(user.id, sessionId) + await chatService.deleteSession(user.id, team.id, sessionId) const session = await prisma.agentSession.findUnique({ where: { id: sessionId }, diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 311f376f..7eea143c 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -141,6 +141,7 @@ export class ChatService { async startOrContinueChat( user: User, + teamId: string, req: ChatRequest, ): Promise<{ sessionId: string; taskId: string }> { const { @@ -254,13 +255,17 @@ export class ChatService { if (!agent) { throw new Error(`Agent with ID "${agentId}" not found`) } + if (agent.teamId !== teamId) { + throw new Error(`Agent does not belong to the specified team`) + } if (activeSessionId) { const sessionExists = await tx.agentSession.findUnique({ where: { id: activeSessionId }, - select: { id: true }, + select: { id: true, userId: true }, }) if (!sessionExists) throw new Error('Session not found') + if (sessionExists.userId !== user.id) throw new Error('Unauthorized session access') // Update the session's agentId to match the selected agent await tx.agentSession.update({ @@ -313,11 +318,15 @@ export class ChatService { async listSessions( userId: string, + teamId: string, params: { first?: number; after?: string }, ): Promise> { const where: Prisma.AgentSessionWhereInput = { userId, type: 'chat', + agent: { + teamId, + }, } return await paginateQuery( @@ -344,7 +353,7 @@ export class ChatService { ) } - async listMessages(userId: string, sessionId: string): Promise { + async listMessages(userId: string, teamId: string, sessionId: string): Promise { const session = await this.prismaClient.agentSession.findUnique({ where: { id: sessionId }, }) @@ -371,7 +380,7 @@ export class ChatService { return buildSessionMessages(pathEntries) } - async deleteSession(userId: string, sessionId: string): Promise { + async deleteSession(userId: string, teamId: string, sessionId: string): Promise { const session = await this.prismaClient.agentSession.findUnique({ where: { id: sessionId }, }) diff --git a/packages/webui/components/chatbot-sidebar.tsx b/packages/webui/components/chatbot-sidebar.tsx index 7177accb..b1aca99b 100644 --- a/packages/webui/components/chatbot-sidebar.tsx +++ b/packages/webui/components/chatbot-sidebar.tsx @@ -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' @@ -105,14 +105,14 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp // Fetch history when entering history mode useEffect(() => { - if (isHistoryMode) { - fetchHistorySessions() + if (isHistoryMode && teamId) { + fetchHistorySessions(teamId) } - }, [isHistoryMode, fetchHistorySessions]) + }, [isHistoryMode, fetchHistorySessions, teamId]) const handleSend = () => { - if (!inputText.trim() || isStreaming) return - sendMessage(inputText, projectId, contextAssetId) + if (!inputText.trim() || isStreaming || !teamId) return + sendMessage(teamId, inputText, projectId, contextAssetId) setInputText('') } @@ -441,7 +441,10 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp isActive ? 'border-primary' : 'border-border hover:bg-accent/30', )} > -
loadSession(sess.id)} className="flex-1 min-w-0 pr-6"> +
teamId && loadSession(teamId, sess.id)} + className="flex-1 min-w-0 pr-6" + >
{sess.name || m.new_chat()}
@@ -452,8 +455,8 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp