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
This commit is contained in:
yiling
2026-07-13 10:10:56 +08:00
parent bad93466ae
commit 61c49b4d7f
16 changed files with 194 additions and 141 deletions
+9
View File
@@ -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,
})
+14 -18
View File
@@ -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<string, unknown>
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,
-1
View File
@@ -59,7 +59,6 @@ declare global {
export interface Settings {
transcode: TranscodeSettings
chatbotAgentId?: string | null
}
// ----------------------------------------------------------------------
+1
View File
@@ -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
+1 -5
View File
@@ -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<typeof updateTeamSettingsRequestSchema>
+1 -15
View File
@@ -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
+98 -14
View File
@@ -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<HTMLDivElement>(null)
@@ -488,14 +532,54 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
disabled={isStreaming}
/>
{/* Bottom row inside the border containing the send button */}
<div className="flex justify-end items-center px-3 pb-2 pt-1">
{/* Bottom row inside the border containing the agent selector and send button */}
<div className="flex justify-between items-center px-3 pb-2 pt-1">
{/* Agent selector */}
<div className="flex items-center gap-1.5 min-w-0 max-w-[70%]">
{chatAgents.length > 0 ? (
<Select
value={selectedAgentId || ''}
onValueChange={(val) => setSelectedAgentId(val)}
disabled={isStreaming}
>
<SelectTrigger className="h-8 border-none bg-transparent hover:bg-muted text-muted-foreground hover:text-foreground focus:ring-0 focus:ring-offset-0 px-2 py-0 gap-1.5 text-xs shrink-0 select-none shadow-none max-w-full">
<SelectValue placeholder={m.select_agent()} />
</SelectTrigger>
<SelectContent>
{chatAgents.map((agent) => (
<SelectItem key={agent.id} value={agent.id}>
<div className="flex items-center gap-2">
{agent.avatar ? (
<img
src={agent.avatar}
alt={agent.name}
className="w-4 h-4 rounded-full object-cover"
/>
) : (
<Bot className="w-4 h-4 text-muted-foreground" />
)}
<span className="text-xs">{agent.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<div className="flex items-center gap-1.5 px-2 py-1 text-[11px] text-muted-foreground/60 italic select-none">
<Bot className="h-3.5 w-3.5" />
<span>
{m.no_chat_agents_warning ? m.no_chat_agents_warning() : 'No agents'}
</span>
</div>
)}
</div>
<button
onClick={handleSend}
disabled={isStreaming || !inputText.trim()}
disabled={isStreaming || !inputText.trim() || !selectedAgentId}
className={cn(
'p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm',
inputText.trim() && !isStreaming
inputText.trim() && !isStreaming && selectedAgentId
? 'bg-primary text-primary-foreground hover:bg-primary/95 transform hover:-translate-y-0.5'
: 'bg-muted text-muted-foreground cursor-not-allowed opacity-50',
)}
@@ -2,13 +2,6 @@ import { client } from '@/ui/api/client'
import { Card, CardContent } from '@/ui/components/ui/card'
import { Button } from '@/ui/components/ui/button'
import { Badge } from '@/ui/components/ui/badge'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
Loader2,
@@ -23,7 +16,7 @@ import {
} from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import { AgentInfo, AgentType, ThinkingLevel, UpdateTeamSettingsRequest } from '@shumai/dtos'
import { AgentInfo, AgentType, ThinkingLevel } from '@shumai/dtos'
import { AgentFormDialog } from './AgentFormDialog'
import {
DropdownMenu,
@@ -150,35 +143,6 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
},
})
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 team settings')
return res.json()
},
})
const updateSettingsMutation = useMutation({
mutationFn: async (params: UpdateTeamSettingsRequest) => {
const res = await client.api.teams[':teamId'].settings.$patch({
param: { teamId },
json: params,
})
if (!res.ok) throw new Error('failed to update settings')
return res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'settings'] })
toast.success(m.settings_saved())
},
onError: (err) => {
toast.error(err.message)
},
})
const toggleSection = (type: string) => {
setExpandedSections((prev) => ({
...prev,
@@ -250,54 +214,6 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
</div>
)}
{/* Global Chatbot Agent Configuration Card */}
<Card className="border-border shadow-xs">
<CardContent className="p-6">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="space-y-1">
<h4 className="font-semibold text-foreground flex items-center gap-2 text-sm md:text-base">
<Bot className="w-5 h-5 text-primary" />
{m.global_chatbot()}
</h4>
<p className="text-xs md:text-sm text-muted-foreground">
{m.global_chatbot_description()}
</p>
</div>
<div className="w-full md:w-72 shrink-0">
{agents.filter((a) => a.type === 'chat' && a.enabled).length === 0 ? (
<div className="text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/20 dark:text-amber-400 p-2.5 rounded-lg border border-amber-200 dark:border-amber-900/30">
{m.no_chat_agents_warning()}
</div>
) : (
<Select
value={
(teamSettings as { chatbotAgentId?: string | null })?.chatbotAgentId || ''
}
onValueChange={(val) => {
updateSettingsMutation.mutate({
key: 'chatbotAgentId',
value: val || null,
})
}}
>
<SelectTrigger className="w-full">
<SelectValue placeholder={m.select_chatbot_agent()} />
</SelectTrigger>
<SelectContent>
{agents
.filter((a) => a.type === 'chat' && a.enabled)
.map((agent) => (
<SelectItem key={agent.id} value={agent.id}>
{agent.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
</div>
</CardContent>
</Card>
{AGENT_TYPES.map((section) => {
const typeAgents = agents.filter((a) => a.type === section.type)
const Icon = section.icon
+2 -1
View File
@@ -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"
}
+2 -1
View File
@@ -840,5 +840,6 @@
"global_chatbot_description": "选择在全局聊天机器人边栏中进行对话的智能体。",
"select_chatbot_agent": "选择聊天机器人智能体",
"no_chat_agents_warning": "未找到聊天智能体。请先在下方创建聊天智能体。",
"settings_saved": "设置保存成功"
"settings_saved": "设置保存成功",
"select_agent": "选择智能体"
}
+1
View File
@@ -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;
+2 -1
View File
@@ -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'
export * from './settings_saved.js'
export * from './select_agent.js'
+16
View File
@@ -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<Select_AgentInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Select_AgentInputs = {};
+29
View File
@@ -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<Select_AgentInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_select_agent(inputs)
return zh_select_agent(inputs)
});
+1
View File
@@ -33,6 +33,7 @@ describe('useChatbotStore', () => {
messages: [],
historySessions: [],
isStreaming: false,
selectedAgentId: 'agent-1',
})
})
+16
View File
@@ -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<void>
loadSession: (sessionId: string) => Promise<void>
@@ -59,6 +61,8 @@ export const useChatbotStore = create<ChatbotState>((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<ChatbotState>((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<ChatbotState>((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,