From 61c49b4d7f7e4d261ae8670284fce3f545f85c48 Mon Sep 17 00:00:00 2001 From: yiling Date: Mon, 13 Jul 2026 10:08:00 +0800 Subject: [PATCH] feat(chat): allow user to choose chatbot in sidebar - Remove chatbotAgentId from team settings and schema definition - Make agentId a required parameter in ChatRequest DTO and chatService - Fetch chatbot agents on chatbot sidebar mount and default to first enabled chat agent - Render an agent selector dropdown inside the message input area - Update existing chat sessions to follow the selected agent when continuing a conversation --- packages/core/src/chat/chat.test.ts | 9 ++ packages/core/src/chat/chat.ts | 32 +++-- packages/db/src/prisma-json-types.ts | 1 - packages/dtos/src/chat.ts | 1 + packages/dtos/src/team.ts | 6 +- packages/webui/components/breadcrumb-nav.tsx | 16 +-- packages/webui/components/chatbot-sidebar.tsx | 112 +++++++++++++++--- .../components/settings/AgentsSettings.tsx | 86 +------------- packages/webui/messages/en.json | 3 +- packages/webui/messages/zh.json | 3 +- packages/webui/paraglide/messages/_index.d.ts | 1 + packages/webui/paraglide/messages/_index.js | 3 +- .../paraglide/messages/select_agent.d.ts | 16 +++ .../webui/paraglide/messages/select_agent.js | 29 +++++ packages/webui/stores/chatbot.test.ts | 1 + packages/webui/stores/chatbot.ts | 16 +++ 16 files changed, 194 insertions(+), 141 deletions(-) create mode 100644 packages/webui/paraglide/messages/select_agent.d.ts create mode 100644 packages/webui/paraglide/messages/select_agent.js diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index d797f131..5310b450 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -76,6 +76,7 @@ describe('ChatService', () => { const { user, project, rootFolder } = await setupBasicData() const { sessionId, taskId } = await chatService.startOrContinueChat(user, { + agentId: 'test-agent-id', textPrompt: 'hello world', projectId: project.id, }) @@ -120,6 +121,7 @@ describe('ChatService', () => { // Start const { sessionId } = await chatService.startOrContinueChat(user, { + agentId: 'test-agent-id', textPrompt: 'first message', projectId: project.id, }) @@ -128,6 +130,7 @@ describe('ChatService', () => { const { sessionId: nextSessionId, taskId: nextTaskId } = await chatService.startOrContinueChat( user, { + agentId: 'test-agent-id', textPrompt: 'second message', sessionId, }, @@ -184,6 +187,7 @@ describe('ChatService', () => { }) const { taskId } = await chatService.startOrContinueChat(user, { + agentId: 'test-agent-id', textPrompt: 'process file', projectId: project.id, assetIds: [childFolder.id], @@ -206,11 +210,13 @@ describe('ChatService', () => { const { user, project } = await setupBasicData() await chatService.startOrContinueChat(user, { + agentId: 'test-agent-id', textPrompt: 'chat 1', projectId: project.id, }) await chatService.startOrContinueChat(user, { + agentId: 'test-agent-id', textPrompt: 'chat 2', projectId: project.id, }) @@ -234,6 +240,7 @@ describe('ChatService', () => { const { user, project } = await setupBasicData() const { sessionId } = await chatService.startOrContinueChat(user, { + agentId: 'test-agent-id', textPrompt: 'hello', projectId: project.id, }) @@ -270,6 +277,7 @@ describe('ChatService', () => { const { user, project } = await setupBasicData() const { sessionId } = await chatService.startOrContinueChat(user, { + agentId: 'test-agent-id', textPrompt: 'hello', projectId: project.id, }) @@ -369,6 +377,7 @@ describe('ChatService', () => { const { user, project } = await setupBasicData() const { sessionId } = await chatService.startOrContinueChat(user, { + agentId: 'test-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 30ec8ec7..311f376f 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -144,6 +144,7 @@ export class ChatService { req: ChatRequest, ): Promise<{ sessionId: string; taskId: string }> { const { + agentId, textPrompt, attachedFiles = [], assetIds = [], @@ -246,32 +247,27 @@ export class ChatService { const teamId = asset.project.teamId const projectId = asset.project.id - let agentId: string let activeSessionId = passedSessionId - if (activeSessionId) { - const sessionExists = await tx.agentSession.findUnique({ - where: { id: activeSessionId }, - select: { id: true, agentId: true }, - }) - if (!sessionExists) throw new Error('Session not found') - agentId = sessionExists.agentId - } else { - const teamSettings = (asset.project.team.settings || {}) as Record - const settingsAgentId = teamSettings.chatbotAgentId as string | undefined - if (!settingsAgentId) { - throw new Error('No chatbot agent configured for the team') - } - agentId = settingsAgentId - } - // Ensure AI agent configuration exists const agent = await tx.agent.findUnique({ where: { id: agentId } }) if (!agent) { throw new Error(`Agent with ID "${agentId}" not found`) } - if (!activeSessionId) { + if (activeSessionId) { + const sessionExists = await tx.agentSession.findUnique({ + where: { id: activeSessionId }, + select: { id: true }, + }) + if (!sessionExists) throw new Error('Session not found') + + // Update the session's agentId to match the selected agent + await tx.agentSession.update({ + where: { id: activeSessionId }, + data: { agentId }, + }) + } else { const newSession = await tx.agentSession.create({ data: { agentId, diff --git a/packages/db/src/prisma-json-types.ts b/packages/db/src/prisma-json-types.ts index d1b9ee02..5ca65aa5 100644 --- a/packages/db/src/prisma-json-types.ts +++ b/packages/db/src/prisma-json-types.ts @@ -59,7 +59,6 @@ declare global { export interface Settings { transcode: TranscodeSettings - chatbotAgentId?: string | null } // ---------------------------------------------------------------------- diff --git a/packages/dtos/src/chat.ts b/packages/dtos/src/chat.ts index 89ba09c6..c8f627a1 100644 --- a/packages/dtos/src/chat.ts +++ b/packages/dtos/src/chat.ts @@ -3,6 +3,7 @@ import type { AgentMessage } from '@earendil-works/pi-agent-core' 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 diff --git a/packages/dtos/src/team.ts b/packages/dtos/src/team.ts index 0c164800..f8c1630c 100644 --- a/packages/dtos/src/team.ts +++ b/packages/dtos/src/team.ts @@ -71,15 +71,11 @@ export const VideoTranscodeStrategy = { export type VideoTranscodeStrategy = (typeof VideoTranscodeStrategy)[keyof typeof VideoTranscodeStrategy] -export const updateTeamSettingsRequestSchema = z.discriminatedUnion('key', [ +export const updateTeamSettingsRequestSchema = z.union([ z.object({ key: z.literal('transcode.videoStrategy'), value: z.nativeEnum(VideoTranscodeStrategy), }), - z.object({ - key: z.literal('chatbotAgentId'), - value: z.string().nullable(), - }), ]) export type UpdateTeamSettingsRequest = z.infer diff --git a/packages/webui/components/breadcrumb-nav.tsx b/packages/webui/components/breadcrumb-nav.tsx index 0bb35539..04049de9 100644 --- a/packages/webui/components/breadcrumb-nav.tsx +++ b/packages/webui/components/breadcrumb-nav.tsx @@ -29,7 +29,6 @@ import { usePermissions } from '@/ui/hooks/use-permissions' import { cn } from '@/ui/lib/utils' import { m } from '@/ui/paraglide/messages.js' import type { AncestorFolder } from '@shumai/dtos' -import { useQuery } from '@tanstack/react-query' import { Link, useNavigate } from '@tanstack/react-router' import { Bot, @@ -115,20 +114,7 @@ export function BreadcrumbNav({ const navigate = useNavigate() const { canEdit } = usePermissions(projectId) - const { data: teamSettings } = useQuery({ - queryKey: ['teams', teamId, 'settings'], - queryFn: async () => { - const res = await client.api.teams[':teamId'].settings.$get({ - param: { teamId }, - }) - if (!res.ok) throw new Error('failed to fetch settings') - return res.json() - }, - enabled: !!teamId && !isPublic, - }) - - const isChatbotDisabled = - !isPublic && !(teamSettings as { chatbotAgentId?: string | null })?.chatbotAgentId + const isChatbotDisabled = false const handleVersionClick = (versionId: string) => { if (!fileId) return diff --git a/packages/webui/components/chatbot-sidebar.tsx b/packages/webui/components/chatbot-sidebar.tsx index 8b000c9f..7177accb 100644 --- a/packages/webui/components/chatbot-sidebar.tsx +++ b/packages/webui/components/chatbot-sidebar.tsx @@ -1,20 +1,30 @@ +import { client } from '@/ui/api/client' import { ScrollArea } from '@/ui/components/ui/scroll-area' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/ui/components/ui/select' import { cn } from '@/ui/lib/utils' import { m } from '@/ui/paraglide/messages.js' import { useChatbotStore } from '@/ui/stores/chatbot' +import { useTeamContextStore } from '@/ui/stores/team-context' 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' @@ -40,8 +50,42 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp deleteSession, startNewSession, sendMessage, + selectedAgentId, + setSelectedAgentId, } = useChatbotStore() + const { teamId, ensureTeamIdForProject } = useTeamContextStore() + + useEffect(() => { + if (projectId) { + ensureTeamIdForProject(projectId) + } + }, [projectId, ensureTeamIdForProject]) + + const { data: agents = [] } = useQuery({ + queryKey: ['agents', teamId], + queryFn: async () => { + if (!teamId) return [] + const res = await client.api.teams[':teamId'].agents.$get({ + param: { teamId }, + }) + if (!res.ok) throw new Error('failed to fetch agents') + return res.json() + }, + enabled: !!teamId, + }) + + const chatAgents = agents.filter((a) => a.type === 'chat' && a.enabled) + + useEffect(() => { + if (chatAgents.length > 0) { + const exists = chatAgents.some((a) => a.id === selectedAgentId) + if (!exists) { + setSelectedAgentId(chatAgents[0].id) + } + } + }, [chatAgents, selectedAgentId, setSelectedAgentId]) + const [inputText, setInputText] = useState('') const messagesEndRef = useRef(null) @@ -488,14 +532,54 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp disabled={isStreaming} /> - {/* Bottom row inside the border containing the send button */} -
+ {/* Bottom row inside the border containing the agent selector and send button */} +
+ {/* Agent selector */} +
+ {chatAgents.length > 0 ? ( + + ) : ( +
+ + + {m.no_chat_agents_warning ? m.no_chat_agents_warning() : 'No agents'} + +
+ )} +
+
)} - {/* Global Chatbot Agent Configuration Card */} - - -
-
-

- - {m.global_chatbot()} -

-

- {m.global_chatbot_description()} -

-
-
- {agents.filter((a) => a.type === 'chat' && a.enabled).length === 0 ? ( -
- {m.no_chat_agents_warning()} -
- ) : ( - - )} -
-
-
-
{AGENT_TYPES.map((section) => { const typeAgents = agents.filter((a) => a.type === section.type) const Icon = section.icon diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index 90ea93b8..94957c8e 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -840,5 +840,6 @@ "global_chatbot_description": "Select the agent that handles conversation inside the global chatbot sidebar.", "select_chatbot_agent": "Select chatbot agent", "no_chat_agents_warning": "No chat agents found. Please create a Chat Agent below first.", - "settings_saved": "Settings saved successfully" + "settings_saved": "Settings saved successfully", + "select_agent": "Select Agent" } diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index d757ca53..95a2817f 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -840,5 +840,6 @@ "global_chatbot_description": "选择在全局聊天机器人边栏中进行对话的智能体。", "select_chatbot_agent": "选择聊天机器人智能体", "no_chat_agents_warning": "未找到聊天智能体。请先在下方创建聊天智能体。", - "settings_saved": "设置保存成功" + "settings_saved": "设置保存成功", + "select_agent": "选择智能体" } diff --git a/packages/webui/paraglide/messages/_index.d.ts b/packages/webui/paraglide/messages/_index.d.ts index a495cf33..d01cd3ae 100644 --- a/packages/webui/paraglide/messages/_index.d.ts +++ b/packages/webui/paraglide/messages/_index.d.ts @@ -787,4 +787,5 @@ export * from "./global_chatbot_description.js"; export * from "./select_chatbot_agent.js"; export * from "./no_chat_agents_warning.js"; export * from "./settings_saved.js"; +export * from "./select_agent.js"; export type LocalizedString = import("../runtime.js").LocalizedString; diff --git a/packages/webui/paraglide/messages/_index.js b/packages/webui/paraglide/messages/_index.js index 1a6b2f8e..2926fc15 100644 --- a/packages/webui/paraglide/messages/_index.js +++ b/packages/webui/paraglide/messages/_index.js @@ -788,4 +788,5 @@ export * from './global_chatbot.js' export * from './global_chatbot_description.js' export * from './select_chatbot_agent.js' export * from './no_chat_agents_warning.js' -export * from './settings_saved.js' \ No newline at end of file +export * from './settings_saved.js' +export * from './select_agent.js' \ No newline at end of file diff --git a/packages/webui/paraglide/messages/select_agent.d.ts b/packages/webui/paraglide/messages/select_agent.d.ts new file mode 100644 index 00000000..692e9461 --- /dev/null +++ b/packages/webui/paraglide/messages/select_agent.d.ts @@ -0,0 +1,16 @@ +/** +* | output | +* | --- | +* | "Select Agent" | +* +* @param {Select_AgentInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const select_agent: ((inputs?: Select_AgentInputs, options?: { + locale?: "en" | "zh"; +}) => LocalizedString) & import("../runtime.js").MessageMetadata; +export type LocalizedString = import("../runtime.js").LocalizedString; +export type Select_AgentInputs = {}; diff --git a/packages/webui/paraglide/messages/select_agent.js b/packages/webui/paraglide/messages/select_agent.js new file mode 100644 index 00000000..a05c492c --- /dev/null +++ b/packages/webui/paraglide/messages/select_agent.js @@ -0,0 +1,29 @@ +/* eslint-disable */ +import { getLocale, experimentalStaticLocale } from '../runtime.js'; + +/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */ + +/** @typedef {{}} Select_AgentInputs */ + +const en_select_agent = /** @type {(inputs: Select_AgentInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`Select Agent`) +}; + +const zh_select_agent = /** @type {(inputs: Select_AgentInputs) => LocalizedString} */ () => { + return /** @type {LocalizedString} */ (`选择智能体`) +}; + +/** +* | output | +* | --- | +* | "Select Agent" | +* +* @param {Select_AgentInputs} inputs +* @param {{ locale?: "en" | "zh" }} options +* @returns {LocalizedString} +*/ +export const select_agent = /** @type {((inputs?: Select_AgentInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata} */ ((inputs = {}, options = {}) => { + const locale = experimentalStaticLocale ?? options.locale ?? getLocale() + if (locale === "en") return en_select_agent(inputs) + return zh_select_agent(inputs) +}); \ No newline at end of file diff --git a/packages/webui/stores/chatbot.test.ts b/packages/webui/stores/chatbot.test.ts index 53d026bb..cbab22e4 100644 --- a/packages/webui/stores/chatbot.test.ts +++ b/packages/webui/stores/chatbot.test.ts @@ -33,6 +33,7 @@ describe('useChatbotStore', () => { messages: [], historySessions: [], isStreaming: false, + selectedAgentId: 'agent-1', }) }) diff --git a/packages/webui/stores/chatbot.ts b/packages/webui/stores/chatbot.ts index 2175f0b6..ea45db17 100644 --- a/packages/webui/stores/chatbot.ts +++ b/packages/webui/stores/chatbot.ts @@ -26,6 +26,8 @@ interface ChatbotState { setHistorySessions: (sessions: ChatSessionInfo[]) => void isStreaming: boolean setIsStreaming: (streaming: boolean) => void + selectedAgentId: string | null + setSelectedAgentId: (id: string | null) => void fetchHistorySessions: () => Promise loadSession: (sessionId: string) => Promise @@ -59,6 +61,8 @@ export const useChatbotStore = create((set) => ({ setHistorySessions: (sessions) => set({ historySessions: sessions }), isStreaming: false, setIsStreaming: (streaming) => set({ isStreaming: streaming }), + selectedAgentId: null, + setSelectedAgentId: (id) => set({ selectedAgentId: id }), fetchHistorySessions: async () => { try { @@ -81,10 +85,15 @@ export const useChatbotStore = create((set) => ({ }) if (res.ok) { const messages = await res.json() + const sessionInfo = useChatbotStore + .getState() + .historySessions.find((s) => s.id === sessionId) + const agentId = sessionInfo?.agentId || null set({ currentSessionId: sessionId, messages: messages as ChatMessage[], isHistoryMode: false, + ...(agentId ? { selectedAgentId: agentId } : {}), }) } else { throw new Error('Failed to load session messages') @@ -164,9 +173,16 @@ export const useChatbotStore = create((set) => ({ const assetIds = state.chatAssets.map((a) => a.id) + const agentId = state.selectedAgentId + if (!agentId) { + toast.error('No agent selected') + return + } + try { const res = await client.api.chat.$post({ json: { + agentId, textPrompt: text, assetIds, sessionId: state.currentSessionId || undefined,