mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 02:18:21 +00:00
feat(chat): enforce team-scoped authorization and session creator check
- Update chat API routes and service methods to include and verify teamId context - Validate that the requesting user is the creator of the chat session during continuation - Update frontend chatbot store and components to pass teamId parameter - Update backend API/core and frontend store tests to verify team scoping and creator checks
This commit is contained in:
@@ -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),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<Record<string, never>>
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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<PaginatedData<ChatSessionInfo[]>> {
|
||||
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<ChatMessage[]> {
|
||||
async listMessages(userId: string, teamId: string, sessionId: string): Promise<ChatMessage[]> {
|
||||
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<void> {
|
||||
async deleteSession(userId: string, teamId: string, sessionId: string): Promise<void> {
|
||||
const session = await this.prismaClient.agentSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
})
|
||||
|
||||
@@ -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',
|
||||
)}
|
||||
>
|
||||
<div onClick={() => loadSession(sess.id)} className="flex-1 min-w-0 pr-6">
|
||||
<div
|
||||
onClick={() => teamId && loadSession(teamId, sess.id)}
|
||||
className="flex-1 min-w-0 pr-6"
|
||||
>
|
||||
<div className="text-sm font-semibold text-foreground truncate">
|
||||
{sess.name || m.new_chat()}
|
||||
</div>
|
||||
@@ -452,8 +455,8 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (confirm(m.delete_session_confirm())) {
|
||||
deleteSession(sess.id)
|
||||
if (teamId && confirm(m.delete_session_confirm())) {
|
||||
deleteSession(teamId, sess.id)
|
||||
}
|
||||
}}
|
||||
className="absolute right-3 opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity text-muted-foreground hover:text-destructive p-1 rounded hover:bg-muted"
|
||||
|
||||
@@ -4,17 +4,22 @@ import { client } from '@/ui/api/client'
|
||||
import type { ChatMessage } from '@shumai/dtos'
|
||||
|
||||
vi.mock('@/ui/api/client', () => {
|
||||
const chatMock = {
|
||||
$post: vi.fn(),
|
||||
sessions: {
|
||||
$get: vi.fn(() => Promise.resolve({ ok: true, json: async () => ({ data: [] }) } as any)),
|
||||
$delete: vi.fn(),
|
||||
messages: {
|
||||
$get: vi.fn(),
|
||||
},
|
||||
},
|
||||
}
|
||||
return {
|
||||
client: {
|
||||
api: {
|
||||
chat: {
|
||||
$post: vi.fn(),
|
||||
sessions: {
|
||||
$get: vi.fn(),
|
||||
$delete: vi.fn(),
|
||||
messages: {
|
||||
$get: vi.fn(),
|
||||
},
|
||||
teams: {
|
||||
':teamId': {
|
||||
chat: chatMock,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -99,9 +104,9 @@ describe('useChatbotStore', () => {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(client.api.chat.$post).mockResolvedValue(mockResponse as any)
|
||||
vi.mocked(client.api.teams[':teamId'].chat.$post).mockResolvedValue(mockResponse as any)
|
||||
|
||||
const sendPromise = useChatbotStore.getState().sendMessage('hello', 'proj-123')
|
||||
const sendPromise = useChatbotStore.getState().sendMessage('team-123', 'hello', 'proj-123')
|
||||
|
||||
// Optimistic message should be present immediately
|
||||
const stateWithOptimistic = useChatbotStore.getState()
|
||||
@@ -166,9 +171,11 @@ describe('useChatbotStore', () => {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(client.api.chat.$post).mockResolvedValue(mockResponse as any)
|
||||
vi.mocked(client.api.teams[':teamId'].chat.$post).mockResolvedValue(mockResponse as any)
|
||||
|
||||
const sendPromise = useChatbotStore.getState().sendMessage('new message', 'proj-123')
|
||||
const sendPromise = useChatbotStore
|
||||
.getState()
|
||||
.sendMessage('team-123', 'new message', 'proj-123')
|
||||
|
||||
// Optimistic message should be appended immediately
|
||||
const stateWithOptimistic = useChatbotStore.getState()
|
||||
@@ -221,9 +228,9 @@ describe('useChatbotStore', () => {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(client.api.chat.$post).mockResolvedValue(mockResponse as any)
|
||||
vi.mocked(client.api.teams[':teamId'].chat.$post).mockResolvedValue(mockResponse as any)
|
||||
|
||||
const sendPromise = useChatbotStore.getState().sendMessage('hello', 'proj-123')
|
||||
const sendPromise = useChatbotStore.getState().sendMessage('team-123', 'hello', 'proj-123')
|
||||
|
||||
// 3. Verify that both the optimistic context message and user message are present immediately
|
||||
const stateWithOptimistic = useChatbotStore.getState()
|
||||
|
||||
@@ -29,11 +29,16 @@ interface ChatbotState {
|
||||
selectedAgentId: string | null
|
||||
setSelectedAgentId: (id: string | null) => void
|
||||
|
||||
fetchHistorySessions: () => Promise<void>
|
||||
loadSession: (sessionId: string) => Promise<void>
|
||||
deleteSession: (sessionId: string) => Promise<void>
|
||||
fetchHistorySessions: (teamId: string) => Promise<void>
|
||||
loadSession: (teamId: string, sessionId: string) => Promise<void>
|
||||
deleteSession: (teamId: string, sessionId: string) => Promise<void>
|
||||
startNewSession: () => void
|
||||
sendMessage: (text: string, projectId: string, contextAssetId?: string) => Promise<void>
|
||||
sendMessage: (
|
||||
teamId: string,
|
||||
text: string,
|
||||
projectId: string,
|
||||
contextAssetId?: string,
|
||||
) => Promise<void>
|
||||
}
|
||||
|
||||
export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
@@ -64,9 +69,10 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
selectedAgentId: null,
|
||||
setSelectedAgentId: (id) => set({ selectedAgentId: id }),
|
||||
|
||||
fetchHistorySessions: async () => {
|
||||
fetchHistorySessions: async (teamId) => {
|
||||
try {
|
||||
const res = await client.api.chat.sessions.$get({
|
||||
const res = await client.api.teams[':teamId'].chat.sessions.$get({
|
||||
param: { teamId },
|
||||
query: { first: '50' },
|
||||
})
|
||||
if (res.ok) {
|
||||
@@ -78,10 +84,10 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
}
|
||||
},
|
||||
|
||||
loadSession: async (sessionId) => {
|
||||
loadSession: async (teamId, sessionId) => {
|
||||
try {
|
||||
const res = await client.api.chat.sessions[':sessionId'].messages.$get({
|
||||
param: { sessionId },
|
||||
const res = await client.api.teams[':teamId'].chat.sessions[':sessionId'].messages.$get({
|
||||
param: { teamId, sessionId },
|
||||
})
|
||||
if (res.ok) {
|
||||
const messages = await res.json()
|
||||
@@ -104,10 +110,10 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
}
|
||||
},
|
||||
|
||||
deleteSession: async (sessionId) => {
|
||||
deleteSession: async (teamId, sessionId) => {
|
||||
try {
|
||||
const res = await client.api.chat.sessions[':sessionId'].$delete({
|
||||
param: { sessionId },
|
||||
const res = await client.api.teams[':teamId'].chat.sessions[':sessionId'].$delete({
|
||||
param: { teamId, sessionId },
|
||||
})
|
||||
if (res.ok) {
|
||||
toast.success('Session deleted successfully')
|
||||
@@ -133,7 +139,7 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
})
|
||||
},
|
||||
|
||||
sendMessage: async (text, projectId, contextAssetId) => {
|
||||
sendMessage: async (teamId, text, projectId, contextAssetId) => {
|
||||
const state = useChatbotStore.getState()
|
||||
if (state.isStreaming) return
|
||||
|
||||
@@ -180,7 +186,8 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await client.api.chat.$post({
|
||||
const res = await client.api.teams[':teamId'].chat.$post({
|
||||
param: { teamId },
|
||||
json: {
|
||||
agentId,
|
||||
textPrompt: text,
|
||||
@@ -272,7 +279,7 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
|
||||
// If we finished successfully, trigger a history list refresh
|
||||
const finalState = useChatbotStore.getState()
|
||||
finalState.fetchHistorySessions()
|
||||
finalState.fetchHistorySessions(teamId)
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : 'Failed to send message'
|
||||
toast.error(errMsg)
|
||||
|
||||
Reference in New Issue
Block a user