mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-22 12:07:17 +00:00
feat(chatbot): implement chatbot sidebar, message view, history mode and sse stream
This commit is contained in:
@@ -36,7 +36,17 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
const { sessionId, taskId } = await chatService.startOrContinueChat(user, req)
|
||||
|
||||
c.header('x-session-id', sessionId)
|
||||
|
||||
return streamSSE(c, async (stream) => {
|
||||
// Send session ID as the first event
|
||||
await stream.writeSSE({
|
||||
data: JSON.stringify({
|
||||
type: 'session',
|
||||
sessionId,
|
||||
}),
|
||||
})
|
||||
|
||||
let lastEntryId = ''
|
||||
const timeoutMs = 5 * 60 * 1000 // 5 minutes timeout
|
||||
const startTime = Date.now()
|
||||
|
||||
@@ -1,11 +1,37 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useDroppable } from '@dnd-kit/react'
|
||||
import { useChatbotStore } from '@/ui/stores/chatbot'
|
||||
import { File, Folder, X, MessageSquare } from 'lucide-react'
|
||||
import { Bot, Send, History, Plus, Trash2, Loader2, ArrowLeft } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import Markdown from 'react-markdown'
|
||||
import type { ChatMessage } from '@shumai/dtos'
|
||||
|
||||
export function ChatbotSidebar() {
|
||||
const { chatAssets, removeAsset, clearAssets } = useChatbotStore()
|
||||
interface ChatbotSidebarProps {
|
||||
projectId: string
|
||||
contextAssetId?: string
|
||||
}
|
||||
|
||||
export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProps) {
|
||||
const {
|
||||
isHistoryMode,
|
||||
setIsHistoryMode,
|
||||
currentSessionId,
|
||||
chatAssets,
|
||||
removeAsset,
|
||||
messages,
|
||||
historySessions,
|
||||
isStreaming,
|
||||
fetchHistorySessions,
|
||||
loadSession,
|
||||
deleteSession,
|
||||
startNewSession,
|
||||
sendMessage,
|
||||
} = useChatbotStore()
|
||||
|
||||
const [inputText, setInputText] = useState('')
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
|
||||
id: 'chatbot-sidebar',
|
||||
@@ -14,70 +40,282 @@ export function ChatbotSidebar() {
|
||||
},
|
||||
})
|
||||
|
||||
// Auto-scroll messages list to bottom
|
||||
useEffect(() => {
|
||||
if (!isHistoryMode) {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
|
||||
}
|
||||
}, [messages, isStreaming, isHistoryMode])
|
||||
|
||||
// Fetch history when entering history mode
|
||||
useEffect(() => {
|
||||
if (isHistoryMode) {
|
||||
fetchHistorySessions()
|
||||
}
|
||||
}, [isHistoryMode, fetchHistorySessions])
|
||||
|
||||
const handleSend = () => {
|
||||
if (!inputText.trim() || isStreaming) return
|
||||
sendMessage(inputText, projectId, contextAssetId)
|
||||
setInputText('')
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
handleSend()
|
||||
}
|
||||
}
|
||||
|
||||
const getMessageText = (content: unknown): string => {
|
||||
if (typeof content === 'string') return content
|
||||
if (Array.isArray(content)) {
|
||||
return content
|
||||
.map((c) => {
|
||||
if (typeof c === 'string') return c
|
||||
if (c && typeof c === 'object' && 'type' in c && c.type === 'text' && 'text' in c) {
|
||||
return String((c as { text: unknown }).text)
|
||||
}
|
||||
return ''
|
||||
})
|
||||
.join('')
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
const preprocessMarkdown = (text: string): string => {
|
||||
return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:')
|
||||
}
|
||||
|
||||
const renderMessage = (msg: ChatMessage) => {
|
||||
const isUser = msg.role === 'user'
|
||||
const isAssistant = msg.role === 'assistant'
|
||||
const isTool = msg.role === 'toolResult'
|
||||
const isSystem = (msg.role as string) === 'thinking_level_change' || msg.role === 'custom'
|
||||
|
||||
if (isUser) {
|
||||
return (
|
||||
<div key={msg.id} className="flex justify-end w-full">
|
||||
<div className="bg-primary text-primary-foreground rounded-lg px-3 py-2 max-w-[85%] text-sm whitespace-pre-wrap shadow-xs break-words">
|
||||
{getMessageText(msg.content)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isAssistant) {
|
||||
return (
|
||||
<div key={msg.id} className="flex flex-col w-full space-y-1">
|
||||
<div className="text-sm leading-[1.8] prose prose-sm dark:prose-invert max-w-none break-words">
|
||||
<Markdown>{preprocessMarkdown(getMessageText(msg.content))}</Markdown>
|
||||
</div>
|
||||
<div className="text-[10px] text-muted-foreground self-start italic">
|
||||
{m.created_by_agent()}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isTool) {
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
className="flex items-center gap-2 text-xs text-muted-foreground bg-muted/40 p-2 rounded-md border border-border/50"
|
||||
>
|
||||
<span className="font-semibold">
|
||||
{m.tool_result_with_name({ name: (msg as { toolName?: string }).toolName || 'tool' })}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isSystem) {
|
||||
const systemContent = 'content' in msg ? msg.content : ''
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
className="text-center text-xs text-muted-foreground italic bg-muted/20 py-1.5 rounded"
|
||||
>
|
||||
{getMessageText(systemContent)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setDroppableRef}
|
||||
className={cn(
|
||||
'flex flex-col h-full bg-background transition-colors duration-200 min-h-0',
|
||||
'flex flex-col h-full bg-background transition-colors duration-200 min-h-0 border-l border-border',
|
||||
isOver && 'bg-accent/50 ring-2 ring-primary ring-inset',
|
||||
)}
|
||||
>
|
||||
{/* Header section */}
|
||||
<div className="flex items-center justify-between p-4 border-b border-border flex-shrink-0">
|
||||
<div className="flex items-center gap-2 font-semibold">
|
||||
<MessageSquare className="h-5 w-5 text-primary" />
|
||||
<span>{m.chatbot_context()}</span>
|
||||
</div>
|
||||
{chatAssets.length > 0 && (
|
||||
<button
|
||||
onClick={clearAssets}
|
||||
className="text-xs text-muted-foreground hover:text-foreground underline transition-colors"
|
||||
>
|
||||
{m.clear()}
|
||||
</button>
|
||||
{isHistoryMode ? (
|
||||
<>
|
||||
<div className="flex items-center gap-2 font-semibold">
|
||||
<History className="h-5 w-5 text-primary" />
|
||||
<span>{m.history()}</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setIsHistoryMode(false)}
|
||||
className="p-1.5 hover:bg-accent rounded-md text-muted-foreground hover:text-foreground transition-colors"
|
||||
title="Close History"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-2 font-semibold">
|
||||
<Bot className="h-5 w-5 text-primary" />
|
||||
<span>{m.shumai_agent()}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={startNewSession}
|
||||
className="p-1.5 hover:bg-accent rounded-md text-muted-foreground hover:text-foreground transition-colors"
|
||||
title={m.new_chat()}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setIsHistoryMode(true)}
|
||||
className="p-1.5 hover:bg-accent rounded-md text-muted-foreground hover:text-foreground transition-colors"
|
||||
title={m.history()}
|
||||
>
|
||||
<History className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 p-4 overflow-y-auto min-h-0 space-y-4">
|
||||
{chatAssets.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-48 border-2 border-dashed border-border rounded-lg text-muted-foreground p-4 text-center">
|
||||
<MessageSquare className="h-8 w-8 mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-sm">{m.chatbot_drag_drop_hint()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
|
||||
{m.context_assets_count({ count: chatAssets.length })}
|
||||
</h3>
|
||||
<div className="divide-y divide-border border border-border rounded-md bg-muted/10 max-h-[400px] overflow-y-auto">
|
||||
{chatAssets.map((asset) => (
|
||||
<div
|
||||
key={asset.id}
|
||||
className="flex items-center justify-between p-2.5 text-sm group"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{asset.type === 'folder' ? (
|
||||
<Folder className="h-4 w-4 text-blue-500 flex-shrink-0" />
|
||||
) : (
|
||||
<File className="h-4 w-4 text-muted-foreground flex-shrink-0" />
|
||||
{/* Main body view */}
|
||||
{isHistoryMode ? (
|
||||
<ScrollArea className="flex-1 p-4 min-h-0">
|
||||
{historySessions.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-48 text-muted-foreground p-4 text-center">
|
||||
<History className="h-8 w-8 mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-sm">{m.no_history_sessions()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 pb-4">
|
||||
{historySessions.map((sess) => {
|
||||
const isActive = sess.id === currentSessionId
|
||||
return (
|
||||
<div
|
||||
key={sess.id}
|
||||
className={cn(
|
||||
'group relative flex items-center justify-between p-3 border rounded-lg transition-all cursor-pointer bg-card',
|
||||
isActive
|
||||
? 'border-primary ring-1 ring-primary'
|
||||
: 'border-border hover:bg-accent/30',
|
||||
)}
|
||||
<span className="truncate font-medium text-foreground">{asset.name}</span>
|
||||
<span className="text-[10px] bg-muted text-muted-foreground px-1.5 py-0.5 rounded-full capitalize">
|
||||
{asset.type}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => removeAsset(asset.id)}
|
||||
className="text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity p-0.5"
|
||||
title={m.remove_from_context()}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<div onClick={() => loadSession(sess.id)} className="flex-1 min-w-0 pr-6">
|
||||
<div className="text-sm font-semibold text-foreground truncate">
|
||||
{m.shumai_agent()}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-0.5">
|
||||
{new Date(sess.createdAt).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (confirm(m.delete_session_confirm())) {
|
||||
deleteSession(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"
|
||||
title="Delete Session"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
) : (
|
||||
<>
|
||||
{/* Active Chat view */}
|
||||
<ScrollArea className="flex-1 p-4 min-h-0">
|
||||
{messages.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-48 border-2 border-dashed border-border rounded-lg text-muted-foreground p-4 text-center">
|
||||
<Bot className="h-8 w-8 mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-sm">{m.chatbot_drag_drop_hint()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4 pb-4">
|
||||
{messages.map(renderMessage)}
|
||||
{isStreaming &&
|
||||
messages.length > 0 &&
|
||||
messages[messages.length - 1].role === 'user' && (
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted-foreground italic">
|
||||
<Loader2 className="h-3 w-3 animate-spin text-primary" />
|
||||
<span>Thinking...</span>
|
||||
</div>
|
||||
)}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
|
||||
{/* Context assets above input area */}
|
||||
<div className="p-4 border-t border-border flex-shrink-0 bg-background flex flex-col gap-2 min-h-0">
|
||||
{chatAssets.length > 0 && (
|
||||
<div className="flex flex-col gap-1.5 min-h-0 max-h-[160px] overflow-y-auto border border-border rounded-md bg-muted/10 p-2 divide-y divide-border/50">
|
||||
{chatAssets.map((asset) => (
|
||||
<div
|
||||
key={asset.id}
|
||||
className="flex items-center justify-between py-1.5 text-xs group"
|
||||
>
|
||||
<div className="flex items-baseline gap-1.5 min-w-0 pr-2">
|
||||
<span className="truncate font-medium text-foreground">{asset.name}</span>
|
||||
<span className="text-[9px] text-muted-foreground uppercase flex-shrink-0">
|
||||
{asset.type}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => removeAsset(asset.id)}
|
||||
className="text-muted-foreground hover:text-destructive transition-colors p-0.5"
|
||||
title={m.remove_from_context()}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Input area */}
|
||||
<div className="flex items-end gap-2">
|
||||
<textarea
|
||||
value={inputText}
|
||||
onChange={(e) => setInputText(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Type a message..."
|
||||
rows={2}
|
||||
className="flex-1 min-h-[44px] max-h-[120px] rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-none"
|
||||
disabled={isStreaming}
|
||||
/>
|
||||
<button
|
||||
onClick={handleSend}
|
||||
disabled={isStreaming || !inputText.trim()}
|
||||
className="h-9 w-9 flex items-center justify-center rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0 shadow-sm"
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -514,7 +514,7 @@ export default function FileSystemManager({
|
||||
className="bg-background border-l border-border flex flex-col flex-shrink-0"
|
||||
>
|
||||
{isChatbotOpen ? (
|
||||
<ChatbotSidebar />
|
||||
<ChatbotSidebar projectId={projectId} contextAssetId={assetId} />
|
||||
) : singleSelectedFile ? (
|
||||
<FileViewerRightSidebar
|
||||
teamId={teamId}
|
||||
|
||||
@@ -826,5 +826,12 @@
|
||||
"context_assets_count": "Context Assets ({count})",
|
||||
"remove_from_context": "Remove from context",
|
||||
"hide_chatbot": "Hide Chatbot",
|
||||
"show_chatbot": "Show Chatbot"
|
||||
"show_chatbot": "Show Chatbot",
|
||||
"created_by_agent": "Created by Agent",
|
||||
"new_chat": "New Chat",
|
||||
"shumai_agent": "Shumai Agent",
|
||||
"history": "History",
|
||||
"send": "Send",
|
||||
"no_history_sessions": "No chat history found.",
|
||||
"delete_session_confirm": "Are you sure you want to delete this chat session?"
|
||||
}
|
||||
|
||||
@@ -826,5 +826,12 @@
|
||||
"context_assets_count": "上下文资源 ({count})",
|
||||
"remove_from_context": "从上下文中移除",
|
||||
"hide_chatbot": "隐藏聊天机器人",
|
||||
"show_chatbot": "显示聊天机器人"
|
||||
"show_chatbot": "显示聊天机器人",
|
||||
"created_by_agent": "由智能体创建",
|
||||
"new_chat": "开启新会话",
|
||||
"shumai_agent": "数脉智能体",
|
||||
"history": "历史记录",
|
||||
"send": "发送",
|
||||
"no_history_sessions": "暂无历史会话记录",
|
||||
"delete_session_confirm": "您确定要删除此会话记录吗?"
|
||||
}
|
||||
|
||||
+6
@@ -774,4 +774,10 @@ export * from "./context_assets_count.js";
|
||||
export * from "./remove_from_context.js";
|
||||
export * from "./hide_chatbot.js";
|
||||
export * from "./show_chatbot.js";
|
||||
export * from "./new_chat.js";
|
||||
export * from "./shumai_agent.js";
|
||||
export * from "./history.js";
|
||||
export * from "./send.js";
|
||||
export * from "./no_history_sessions.js";
|
||||
export * from "./delete_session_confirm.js";
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
|
||||
+7
-1
@@ -775,4 +775,10 @@ export * from './chatbot_drag_drop_hint.js'
|
||||
export * from './context_assets_count.js'
|
||||
export * from './remove_from_context.js'
|
||||
export * from './hide_chatbot.js'
|
||||
export * from './show_chatbot.js'
|
||||
export * from './show_chatbot.js'
|
||||
export * from './new_chat.js'
|
||||
export * from './shumai_agent.js'
|
||||
export * from './history.js'
|
||||
export * from './send.js'
|
||||
export * from './no_history_sessions.js'
|
||||
export * from './delete_session_confirm.js'
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Are you sure you want to delete this chat session?" |
|
||||
*
|
||||
* @param {Delete_Session_ConfirmInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const delete_session_confirm: ((inputs?: Delete_Session_ConfirmInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Delete_Session_ConfirmInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Delete_Session_ConfirmInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Delete_Session_ConfirmInputs */
|
||||
|
||||
const en_delete_session_confirm = /** @type {(inputs: Delete_Session_ConfirmInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Are you sure you want to delete this chat session?`)
|
||||
};
|
||||
|
||||
const zh_delete_session_confirm = /** @type {(inputs: Delete_Session_ConfirmInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`您确定要删除此会话记录吗?`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Are you sure you want to delete this chat session?" |
|
||||
*
|
||||
* @param {Delete_Session_ConfirmInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const delete_session_confirm = /** @type {((inputs?: Delete_Session_ConfirmInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Delete_Session_ConfirmInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_delete_session_confirm(inputs)
|
||||
return zh_delete_session_confirm(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "History" |
|
||||
*
|
||||
* @param {HistoryInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const history: ((inputs?: HistoryInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<HistoryInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type HistoryInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} HistoryInputs */
|
||||
|
||||
const en_history = /** @type {(inputs: HistoryInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`History`)
|
||||
};
|
||||
|
||||
const zh_history = /** @type {(inputs: HistoryInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`历史记录`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "History" |
|
||||
*
|
||||
* @param {HistoryInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const history = /** @type {((inputs?: HistoryInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<HistoryInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_history(inputs)
|
||||
return zh_history(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "New Chat" |
|
||||
*
|
||||
* @param {New_ChatInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const new_chat: ((inputs?: New_ChatInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<New_ChatInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type New_ChatInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} New_ChatInputs */
|
||||
|
||||
const en_new_chat = /** @type {(inputs: New_ChatInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`New Chat`)
|
||||
};
|
||||
|
||||
const zh_new_chat = /** @type {(inputs: New_ChatInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`开启新会话`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "New Chat" |
|
||||
*
|
||||
* @param {New_ChatInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const new_chat = /** @type {((inputs?: New_ChatInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<New_ChatInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_new_chat(inputs)
|
||||
return zh_new_chat(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "No chat history found." |
|
||||
*
|
||||
* @param {No_History_SessionsInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const no_history_sessions: ((inputs?: No_History_SessionsInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<No_History_SessionsInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type No_History_SessionsInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} No_History_SessionsInputs */
|
||||
|
||||
const en_no_history_sessions = /** @type {(inputs: No_History_SessionsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`No chat history found.`)
|
||||
};
|
||||
|
||||
const zh_no_history_sessions = /** @type {(inputs: No_History_SessionsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`暂无历史会话记录`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "No chat history found." |
|
||||
*
|
||||
* @param {No_History_SessionsInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const no_history_sessions = /** @type {((inputs?: No_History_SessionsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<No_History_SessionsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_no_history_sessions(inputs)
|
||||
return zh_no_history_sessions(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Send" |
|
||||
*
|
||||
* @param {SendInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const send: ((inputs?: SendInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<SendInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type SendInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} SendInputs */
|
||||
|
||||
const en_send = /** @type {(inputs: SendInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Send`)
|
||||
};
|
||||
|
||||
const zh_send = /** @type {(inputs: SendInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`发送`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Send" |
|
||||
*
|
||||
* @param {SendInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const send = /** @type {((inputs?: SendInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<SendInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_send(inputs)
|
||||
return zh_send(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Shumai Agent" |
|
||||
*
|
||||
* @param {Shumai_AgentInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const shumai_agent: ((inputs?: Shumai_AgentInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Shumai_AgentInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Shumai_AgentInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Shumai_AgentInputs */
|
||||
|
||||
const en_shumai_agent = /** @type {(inputs: Shumai_AgentInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Shumai Agent`)
|
||||
};
|
||||
|
||||
const zh_shumai_agent = /** @type {(inputs: Shumai_AgentInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`数脉智能体`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Shumai Agent" |
|
||||
*
|
||||
* @param {Shumai_AgentInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const shumai_agent = /** @type {((inputs?: Shumai_AgentInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Shumai_AgentInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_shumai_agent(inputs)
|
||||
return zh_shumai_agent(inputs)
|
||||
});
|
||||
@@ -449,7 +449,7 @@ function FileViewPage() {
|
||||
className="flex-shrink-0 bg-background border-l border-border flex flex-col"
|
||||
>
|
||||
{isChatbotOpen ? (
|
||||
<ChatbotSidebar />
|
||||
<ChatbotSidebar projectId={projectId} contextAssetId={activeFileId} />
|
||||
) : (
|
||||
<FileViewerRightSidebar
|
||||
teamId={teamId}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { create } from 'zustand'
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { ChatMessage, ChatSessionInfo } from '@shumai/dtos'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
export interface ChatAsset {
|
||||
id: string
|
||||
@@ -9,15 +12,35 @@ export interface ChatAsset {
|
||||
interface ChatbotState {
|
||||
isChatbotOpen: boolean
|
||||
setIsChatbotOpen: (open: boolean) => void
|
||||
isHistoryMode: boolean
|
||||
setIsHistoryMode: (history: boolean) => void
|
||||
currentSessionId: string | null
|
||||
setCurrentSessionId: (id: string | null) => void
|
||||
chatAssets: ChatAsset[]
|
||||
addAssets: (assets: ChatAsset[]) => void
|
||||
removeAsset: (id: string) => void
|
||||
clearAssets: () => void
|
||||
messages: ChatMessage[]
|
||||
setMessages: (messages: ChatMessage[]) => void
|
||||
historySessions: ChatSessionInfo[]
|
||||
setHistorySessions: (sessions: ChatSessionInfo[]) => void
|
||||
isStreaming: boolean
|
||||
setIsStreaming: (streaming: boolean) => void
|
||||
|
||||
fetchHistorySessions: () => Promise<void>
|
||||
loadSession: (sessionId: string) => Promise<void>
|
||||
deleteSession: (sessionId: string) => Promise<void>
|
||||
startNewSession: () => void
|
||||
sendMessage: (text: string, projectId: string, contextAssetId?: string) => Promise<void>
|
||||
}
|
||||
|
||||
export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
isChatbotOpen: false,
|
||||
setIsChatbotOpen: (open) => set({ isChatbotOpen: open }),
|
||||
isHistoryMode: false,
|
||||
setIsHistoryMode: (history) => set({ isHistoryMode: history }),
|
||||
currentSessionId: null,
|
||||
setCurrentSessionId: (id) => set({ currentSessionId: id }),
|
||||
chatAssets: [],
|
||||
addAssets: (assets) =>
|
||||
set((state) => {
|
||||
@@ -30,4 +53,189 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
chatAssets: state.chatAssets.filter((a) => a.id !== id),
|
||||
})),
|
||||
clearAssets: () => set({ chatAssets: [] }),
|
||||
messages: [],
|
||||
setMessages: (messages) => set({ messages }),
|
||||
historySessions: [],
|
||||
setHistorySessions: (sessions) => set({ historySessions: sessions }),
|
||||
isStreaming: false,
|
||||
setIsStreaming: (streaming) => set({ isStreaming: streaming }),
|
||||
|
||||
fetchHistorySessions: async () => {
|
||||
try {
|
||||
const res = await client.api.chat.sessions.$get({
|
||||
query: { first: '50' },
|
||||
})
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
set({ historySessions: data.data || [] })
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch history sessions:', err)
|
||||
}
|
||||
},
|
||||
|
||||
loadSession: async (sessionId) => {
|
||||
try {
|
||||
const res = await client.api.chat.sessions[':sessionId'].messages.$get({
|
||||
param: { sessionId },
|
||||
})
|
||||
if (res.ok) {
|
||||
const messages = await res.json()
|
||||
set({
|
||||
currentSessionId: sessionId,
|
||||
messages: messages as ChatMessage[],
|
||||
isHistoryMode: false,
|
||||
})
|
||||
} else {
|
||||
throw new Error('Failed to load session messages')
|
||||
}
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : 'Failed to load session'
|
||||
toast.error(errMsg)
|
||||
}
|
||||
},
|
||||
|
||||
deleteSession: async (sessionId) => {
|
||||
try {
|
||||
const res = await client.api.chat.sessions[':sessionId'].$delete({
|
||||
param: { sessionId },
|
||||
})
|
||||
if (res.ok) {
|
||||
toast.success('Session deleted successfully')
|
||||
set((s) => ({
|
||||
historySessions: s.historySessions.filter((sess) => sess.id !== sessionId),
|
||||
currentSessionId: s.currentSessionId === sessionId ? null : s.currentSessionId,
|
||||
messages: s.currentSessionId === sessionId ? [] : s.messages,
|
||||
}))
|
||||
} else {
|
||||
throw new Error('Failed to delete session')
|
||||
}
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : 'Failed to delete session'
|
||||
toast.error(errMsg)
|
||||
}
|
||||
},
|
||||
|
||||
startNewSession: () => {
|
||||
set({
|
||||
currentSessionId: null,
|
||||
messages: [],
|
||||
chatAssets: [],
|
||||
})
|
||||
},
|
||||
|
||||
sendMessage: async (text, projectId, contextAssetId) => {
|
||||
const state = useChatbotStore.getState()
|
||||
if (state.isStreaming) return
|
||||
|
||||
const tempId = `temp-${Date.now()}`
|
||||
const optimisticMsg = {
|
||||
id: tempId,
|
||||
role: 'user' as const,
|
||||
content: [{ type: 'text', text }],
|
||||
timestamp: Date.now(),
|
||||
} as unknown as ChatMessage
|
||||
|
||||
set({
|
||||
messages: [...state.messages, optimisticMsg],
|
||||
isStreaming: true,
|
||||
})
|
||||
|
||||
const assetIds = state.chatAssets.map((a) => a.id)
|
||||
|
||||
try {
|
||||
const res = await client.api.chat.$post({
|
||||
json: {
|
||||
agentId: 'default',
|
||||
textPrompt: text,
|
||||
assetIds,
|
||||
sessionId: state.currentSessionId || undefined,
|
||||
contextAssetId,
|
||||
projectId,
|
||||
},
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error('Failed to start chat')
|
||||
}
|
||||
|
||||
// Try reading custom header first
|
||||
const headerSessionId = res.headers.get('x-session-id')
|
||||
if (headerSessionId && !state.currentSessionId) {
|
||||
set({ currentSessionId: headerSessionId })
|
||||
}
|
||||
|
||||
const reader = res.body?.getReader()
|
||||
if (!reader) {
|
||||
throw new Error('No stream body')
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() || ''
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed) continue
|
||||
|
||||
if (trimmed.startsWith('data: ')) {
|
||||
const dataStr = trimmed.slice(6)
|
||||
try {
|
||||
const data = JSON.parse(dataStr)
|
||||
if (data.type === 'session') {
|
||||
if (!useChatbotStore.getState().currentSessionId) {
|
||||
set({ currentSessionId: data.sessionId })
|
||||
}
|
||||
} else if (data.type === 'entry') {
|
||||
const entry = data.entry as ChatMessage
|
||||
set((s) => {
|
||||
// Replace temp/optimistic message when the real user message streams back
|
||||
const filtered = s.messages.filter(
|
||||
(m) =>
|
||||
m.id !== entry.id && !(entry.role === 'user' && m.id.startsWith('temp-')),
|
||||
)
|
||||
|
||||
// Prevent duplicates by ID
|
||||
const existingIdx = filtered.findIndex((m) => m.id === entry.id)
|
||||
if (existingIdx !== -1) {
|
||||
const copy = [...filtered]
|
||||
copy[existingIdx] = entry
|
||||
return { messages: copy }
|
||||
} else {
|
||||
return { messages: [...filtered, entry] }
|
||||
}
|
||||
})
|
||||
} else if (data.type === 'done') {
|
||||
if (data.status === 'failed') {
|
||||
toast.error(data.error || 'Workflow failed')
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error parsing SSE line:', err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we finished successfully, trigger a history list refresh
|
||||
const finalState = useChatbotStore.getState()
|
||||
finalState.fetchHistorySessions()
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : 'Failed to send message'
|
||||
toast.error(errMsg)
|
||||
// Remove optimistic message on failure
|
||||
set((s) => ({
|
||||
messages: s.messages.filter((m) => m.id !== tempId),
|
||||
}))
|
||||
} finally {
|
||||
set({ isStreaming: false })
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
Reference in New Issue
Block a user