fix: propagate real message IDs via SSE and fix regenerate model parameter
- Add message_id and user_message_id to SSE done events so frontend can replace temp IDs with real DB IDs, fixing "消息不存在" on regenerate - Replace Body(default=None) with RegenerateRequest Pydantic model for proper JSON body parsing, fixing 422 Unprocessable Content - Frontend always sends model in regenerate request body - Pass selected model through message-item → regenerateMessage chain - Various UI refinements to chat sidebar, quick questions, and layout Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -8,12 +8,15 @@ import ChatInterface from "@/components/chat/chat-interface";
|
||||
import Sidebar from "@/components/chat/sidebar";
|
||||
import MobileNav from "@/components/layout/mobile-nav";
|
||||
import LoadingSpinner from "@/components/ui/loading-spinner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PanelLeftClose, PanelLeftOpen } from "lucide-react";
|
||||
|
||||
export default function ChatPage() {
|
||||
const router = useRouter();
|
||||
const { isAuthenticated, user, isLoading: authLoading } = useAuthStore();
|
||||
const { loadSessions, isLoading: chatLoading } = useChatStore();
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
const [sidebarOpen, setSidebarOpen] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authLoading && !isAuthenticated) {
|
||||
@@ -22,7 +25,6 @@ export default function ChatPage() {
|
||||
}
|
||||
|
||||
if (isAuthenticated && !isInitialized) {
|
||||
// 加载聊天会话
|
||||
loadSessions();
|
||||
setIsInitialized(true);
|
||||
}
|
||||
@@ -41,18 +43,45 @@ export default function ChatPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-[calc(100vh-4rem)] bg-background flex">
|
||||
{/* 侧边栏 */}
|
||||
<div className="w-80 border-r bg-card/50 flex-shrink-0">
|
||||
<Sidebar />
|
||||
</div>
|
||||
|
||||
{/* 主聊天区域 */}
|
||||
<div className="flex-1 flex flex-col min-w-0">
|
||||
<ChatInterface />
|
||||
<div className="h-[calc(100vh-4rem)] bg-background">
|
||||
<div className="h-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex gap-4 py-4">
|
||||
{/* Mobile overlay */}
|
||||
{sidebarOpen && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/30 z-30 md:hidden"
|
||||
onClick={() => setSidebarOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Sidebar — persistent on desktop, overlay on mobile */}
|
||||
<div className={`
|
||||
shrink-0 z-40
|
||||
w-[260px] rounded-xl border border-border/40 bg-card shadow-sm
|
||||
transition-all duration-200 ease-in-out overflow-hidden
|
||||
fixed md:relative md:top-auto md:left-auto md:bottom-auto
|
||||
${sidebarOpen ? 'translate-x-0' : '-translate-x-full md:hidden'}
|
||||
`}>
|
||||
<Sidebar onClose={() => setSidebarOpen(false)} />
|
||||
</div>
|
||||
|
||||
{/* Main chat area */}
|
||||
<div className="flex-1 flex flex-col min-w-0 relative rounded-xl border border-border/40 bg-card shadow-sm overflow-hidden">
|
||||
{/* Toggle button */}
|
||||
{!sidebarOpen && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setSidebarOpen(true)}
|
||||
className="absolute top-3 left-3 z-10 h-9 w-9 text-muted-foreground hover:text-foreground hover:bg-muted/50"
|
||||
>
|
||||
<PanelLeftOpen className="w-5 h-5" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<ChatInterface />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 移动端导航 */}
|
||||
<MobileNav />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -69,13 +69,6 @@ export default function CourseContentPage() {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const structure = await courseContentAPI.getCourseContent();
|
||||
console.log("加载的书籍结构:", structure);
|
||||
console.log("章节数量:", structure?.chapters?.length || 0);
|
||||
if (structure?.chapters) {
|
||||
structure.chapters.forEach((chapter, index) => {
|
||||
console.log(`章节 ${index + 1}:`, chapter.title, "节数:", chapter.sections?.length || 0);
|
||||
});
|
||||
}
|
||||
setBookStructure(structure);
|
||||
} catch (err) {
|
||||
console.error("加载课程内容失败:", err);
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useState, useRef, useEffect } from "react";
|
||||
import { useChatStore } from "@/store/chat";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Send, Loader2, Bot, User, StopCircle, ArrowDown, Paperclip } from "lucide-react";
|
||||
import { Send, Square, Bot, ChevronDown, Settings2 } from "lucide-react";
|
||||
import MessageList from "./message-list";
|
||||
import QuickQuestions from "./quick-questions";
|
||||
import ModeSelector, { ChatMode } from "./mode-selector";
|
||||
@@ -21,9 +21,12 @@ export default function ChatInterface() {
|
||||
const [selectedKnowledgeBases, setSelectedKnowledgeBases] = useState<string[]>([]);
|
||||
const [systemKnowledgeBases, setSystemKnowledgeBases] = useState<KnowledgeBase[]>([]);
|
||||
const [userKnowledgeBases, setUserKnowledgeBases] = useState<KnowledgeBase[]>([]);
|
||||
const [showScrollDown, setShowScrollDown] = useState(false);
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const {
|
||||
currentSession,
|
||||
messages,
|
||||
@@ -36,91 +39,44 @@ export default function ChatInterface() {
|
||||
selectSession,
|
||||
} = useChatStore();
|
||||
|
||||
// 调试日志
|
||||
useEffect(() => {
|
||||
console.log("[DEBUG-CHAT-INTERFACE] 组件状态:", {
|
||||
currentSession: currentSession?.id,
|
||||
messagesCount: messages.length,
|
||||
isLoading,
|
||||
isStreaming,
|
||||
messages: messages.map(m => ({ id: m.id, role: m.role, contentLength: m.content.length }))
|
||||
});
|
||||
}, [currentSession, messages, isLoading, isStreaming]);
|
||||
|
||||
// 自动滚动到底部
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({
|
||||
behavior: isStreaming ? "auto" : "smooth"
|
||||
});
|
||||
}, [messages, isStreaming]);
|
||||
|
||||
// 加载知识库(区分系统知识库和用户知识库)
|
||||
useEffect(() => {
|
||||
const loadKnowledgeBases = async () => {
|
||||
try {
|
||||
const bases = await knowledgeBaseAPI.getKnowledgeBases();
|
||||
|
||||
console.log("[DEBUG] 加载的知识库:", bases.map(kb => ({
|
||||
id: kb.id,
|
||||
name: kb.name,
|
||||
is_system: kb.is_system
|
||||
})));
|
||||
|
||||
// 转换为KnowledgeSelector需要的格式
|
||||
const formattedBases: KnowledgeBase[] = bases.map(kb => ({
|
||||
id: kb.id.toString(),
|
||||
name: kb.name,
|
||||
description: kb.description || "",
|
||||
documentCount: kb.document_count,
|
||||
enabled: true, // 默认启用
|
||||
isSystem: kb.is_system === true, // 明确检查是否为 true
|
||||
enabled: true,
|
||||
isSystem: kb.is_system === true,
|
||||
}));
|
||||
|
||||
// 分离系统知识库和用户知识库
|
||||
const systemBases = formattedBases.filter(kb => kb.isSystem === true);
|
||||
const userBases = formattedBases.filter(kb => kb.isSystem !== true);
|
||||
|
||||
console.log("[DEBUG] 系统知识库:", systemBases.map(kb => ({ id: kb.id, name: kb.name })));
|
||||
console.log("[DEBUG] 用户知识库:", userBases.map(kb => ({ id: kb.id, name: kb.name })));
|
||||
|
||||
setSystemKnowledgeBases(systemBases);
|
||||
setUserKnowledgeBases(userBases);
|
||||
setSystemKnowledgeBases(formattedBases.filter(kb => kb.isSystem));
|
||||
setUserKnowledgeBases(formattedBases.filter(kb => !kb.isSystem));
|
||||
} catch (error) {
|
||||
console.error("加载知识库失败:", error);
|
||||
}
|
||||
};
|
||||
|
||||
loadKnowledgeBases();
|
||||
}, []);
|
||||
|
||||
const handleSendMessage = async () => {
|
||||
if (!inputMessage.trim() || isLoading || isStreaming) return;
|
||||
|
||||
const message = inputMessage.trim();
|
||||
setInputMessage("");
|
||||
setShowSettings(false);
|
||||
|
||||
console.log("[DEBUG-CHAT] 发送消息:", {
|
||||
message: message,
|
||||
chatMode: chatMode,
|
||||
selectedKnowledgeBases: selectedKnowledgeBases,
|
||||
selectedModel: selectedModel,
|
||||
currentSession: currentSession?.id
|
||||
});
|
||||
|
||||
// 如果没有当前会话,先创建一个新会话
|
||||
if (!currentSession) {
|
||||
const newSession = await createSession("新对话");
|
||||
if (newSession) {
|
||||
await selectSession(newSession.id);
|
||||
}
|
||||
}
|
||||
|
||||
// 使用流式发送,传递聊天模式、选中的知识库ID和模型ID
|
||||
await streamMessage(message, chatMode, selectedKnowledgeBases, selectedModel);
|
||||
};
|
||||
|
||||
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
if (e.key === "Enter" && !e.shiftKey && !isComposing) {
|
||||
e.preventDefault();
|
||||
handleSendMessage();
|
||||
}
|
||||
@@ -128,295 +84,164 @@ export default function ChatInterface() {
|
||||
|
||||
const handleQuickQuestion = async (question: string) => {
|
||||
setInputMessage(question);
|
||||
|
||||
// 聚焦到输入框
|
||||
setTimeout(() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, 100);
|
||||
setTimeout(() => inputRef.current?.focus(), 100);
|
||||
};
|
||||
|
||||
// Debug logging
|
||||
console.log("[CHAT-INTERFACE] Current state:", {
|
||||
hasSession: !!currentSession,
|
||||
sessionId: currentSession?.id,
|
||||
messagesCount: messages.length
|
||||
});
|
||||
const scrollToBottom = () => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
};
|
||||
|
||||
const handleScroll = () => {
|
||||
if (!scrollContainerRef.current) return;
|
||||
const { scrollTop, scrollHeight, clientHeight } = scrollContainerRef.current;
|
||||
setShowScrollDown(scrollHeight - scrollTop - clientHeight > 120);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (isStreaming) {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "auto" });
|
||||
}
|
||||
}, [messages, isStreaming]);
|
||||
|
||||
const renderWelcome = (size: "lg" | "sm") => (
|
||||
<div className="text-center max-w-lg mx-auto px-4">
|
||||
<div className="w-12 h-12 bg-primary/10 rounded-2xl flex items-center justify-center mx-auto mb-4">
|
||||
<Bot className="w-6 h-6 text-primary" />
|
||||
</div>
|
||||
<h1 className={cn("font-semibold text-foreground mb-1.5", size === "lg" ? "text-xl" : "text-lg")}>
|
||||
国土空间规划课程智能体
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mb-6 max-w-sm mx-auto">
|
||||
基于大模型的智能问答系统,为您提供专业的国土空间规划知识服务
|
||||
</p>
|
||||
<QuickQuestions onSelect={handleQuickQuestion} />
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderInputArea = () => (
|
||||
<div className="border-t border-border/40 bg-card/80 backdrop-blur-sm flex-shrink-0">
|
||||
<div className="max-w-3xl mx-auto px-4 py-3">
|
||||
{/* Settings panel — collapsible */}
|
||||
{showSettings && (
|
||||
<div className="flex items-center gap-2 mb-3 pb-3 border-b border-border/30">
|
||||
<ModeSelector mode={chatMode} onModeChange={setChatMode} />
|
||||
<ModelSelector
|
||||
selectedModel={selectedModel}
|
||||
onModelChange={setSelectedModel}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
<KnowledgeSelector
|
||||
selectedBases={selectedKnowledgeBases}
|
||||
onBasesChange={setSelectedKnowledgeBases}
|
||||
systemKnowledgeBases={systemKnowledgeBases}
|
||||
userKnowledgeBases={userKnowledgeBases}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Input row */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn(
|
||||
"h-9 w-9 shrink-0 rounded-lg text-muted-foreground",
|
||||
showSettings && "bg-muted text-foreground"
|
||||
)}
|
||||
onClick={() => setShowSettings(!showSettings)}
|
||||
title="设置"
|
||||
>
|
||||
<Settings2 className="w-4 h-4" />
|
||||
</Button>
|
||||
|
||||
<div className="flex-1 relative">
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={inputMessage}
|
||||
onChange={(e) => setInputMessage(e.target.value)}
|
||||
onKeyDown={handleKeyPress}
|
||||
onCompositionStart={() => setIsComposing(true)}
|
||||
onCompositionEnd={() => setIsComposing(false)}
|
||||
placeholder="输入您的问题…"
|
||||
disabled={isLoading || isStreaming}
|
||||
className={cn(
|
||||
"w-full h-10 px-4 rounded-xl text-sm",
|
||||
"bg-muted/40 border border-border/30",
|
||||
"placeholder:text-muted-foreground/60",
|
||||
"focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary/30",
|
||||
"transition-all duration-150"
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={isStreaming ? stopGeneration : handleSendMessage}
|
||||
disabled={!isStreaming && (!inputMessage.trim() || isLoading)}
|
||||
className={cn(
|
||||
"h-9 w-9 shrink-0 rounded-lg inline-flex items-center justify-center",
|
||||
"transition-all duration-150",
|
||||
isStreaming
|
||||
? "bg-destructive hover:bg-destructive/90 text-white"
|
||||
: "bg-[#2563eb] hover:bg-[#1d4ed8] text-white disabled:bg-[#2563eb]/40 disabled:cursor-not-allowed"
|
||||
)}
|
||||
>
|
||||
{isStreaming ? (
|
||||
<Square className="w-4 h-4 fill-current" />
|
||||
) : (
|
||||
<Send className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Empty state — no session selected
|
||||
if (!currentSession) {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col bg-background h-full">
|
||||
{/* 上部:欢迎内容区域 - 使用 flex-1 + 可滚动 */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="h-full flex items-center justify-center p-6">
|
||||
<div className="text-center max-w-2xl px-4">
|
||||
<div className="w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg">
|
||||
<Bot className="w-8 h-8 text-white" />
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-foreground mb-2">
|
||||
欢迎使用国土空间规划课程智能体
|
||||
</h3>
|
||||
<p className="text-muted-foreground mb-6">
|
||||
基于大模型的智能问答系统,为您提供专业的国土空间规划知识服务
|
||||
</p>
|
||||
<QuickQuestions onSelect={handleQuickQuestion} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部:输入区域 - 不使用 sticky,直接作为 flex 子元素 */}
|
||||
<div className="border-t border-border bg-card p-4 lg:p-6 flex-shrink-0">
|
||||
{/* 功能选择器 */}
|
||||
<div className="mb-4 space-y-3">
|
||||
<div className="flex items-center space-x-2">
|
||||
<ModeSelector mode={chatMode} onModeChange={setChatMode} />
|
||||
<ModelSelector
|
||||
selectedModel={selectedModel}
|
||||
onModelChange={setSelectedModel}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
<KnowledgeSelector
|
||||
selectedBases={selectedKnowledgeBases}
|
||||
onBasesChange={setSelectedKnowledgeBases}
|
||||
systemKnowledgeBases={systemKnowledgeBases}
|
||||
userKnowledgeBases={userKnowledgeBases}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9 px-3 flex-shrink-0"
|
||||
title="上传附件"
|
||||
>
|
||||
<Paperclip className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 输入框和发送按钮 */}
|
||||
<div className="flex items-end space-x-3">
|
||||
<div className="flex-1">
|
||||
<div className="relative">
|
||||
<Input
|
||||
ref={inputRef}
|
||||
value={inputMessage}
|
||||
onChange={(e) => setInputMessage(e.target.value)}
|
||||
onKeyPress={handleKeyPress}
|
||||
onCompositionStart={() => setIsComposing(true)}
|
||||
onCompositionEnd={() => setIsComposing(false)}
|
||||
placeholder="输入您的问题..."
|
||||
disabled={isLoading || isStreaming}
|
||||
className={cn(
|
||||
"min-h-[48px] resize-none touch-manipulation pr-12 rounded-xl",
|
||||
"border-border/50 bg-background/80 backdrop-blur-sm",
|
||||
"focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500/50",
|
||||
"transition-all duration-200"
|
||||
)}
|
||||
/>
|
||||
{isStreaming && (
|
||||
<div className="absolute right-3 top-1/2 -translate-y-1/2">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" />
|
||||
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }} />
|
||||
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleSendMessage}
|
||||
disabled={!inputMessage.trim() || isLoading || isStreaming}
|
||||
size="icon"
|
||||
className={cn(
|
||||
"h-12 w-12 flex-shrink-0 touch-manipulation rounded-xl",
|
||||
"bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700",
|
||||
"shadow-lg hover:shadow-xl transition-all duration-200",
|
||||
"disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
)}
|
||||
>
|
||||
{isLoading || isStreaming ? (
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
) : (
|
||||
<Send className="w-5 h-5" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 输入提示 */}
|
||||
<div className="mt-3 flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span className="hidden sm:block">按 Enter 发送,Shift + Enter 换行</span>
|
||||
<span className="sm:hidden">点击发送按钮发送消息</span>
|
||||
{isStreaming && (
|
||||
<span className="flex items-center gap-1 text-blue-600">
|
||||
<div className="w-1.5 h-1.5 bg-blue-500 rounded-full animate-pulse" />
|
||||
正在生成回复...
|
||||
</span>
|
||||
)}
|
||||
{renderWelcome("lg")}
|
||||
</div>
|
||||
</div>
|
||||
{renderInputArea()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col bg-background h-full">
|
||||
{/* 聊天头部 - 不需要 sticky,作为 flex 子元素自然在顶部 */}
|
||||
<div className="border-b border-border bg-card p-4 lg:p-6 flex-shrink-0">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="w-8 h-8 bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg flex items-center justify-center flex-shrink-0 shadow-sm">
|
||||
<Bot className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h2 className="text-lg font-semibold text-foreground truncate">
|
||||
{currentSession.title}
|
||||
</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="flex items-center gap-2">
|
||||
{isStreaming && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={stopGeneration}
|
||||
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||
>
|
||||
<StopCircle className="w-4 h-4 mr-2" />
|
||||
停止生成
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })}
|
||||
className="opacity-60 hover:opacity-100"
|
||||
>
|
||||
<ArrowDown className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 flex flex-col bg-background h-full relative">
|
||||
{/* Scroll-to-bottom */}
|
||||
{showScrollDown && (
|
||||
<button
|
||||
onClick={scrollToBottom}
|
||||
className="absolute bottom-20 left-1/2 -translate-x-1/2 z-10 w-8 h-8 rounded-full bg-card border border-border/50 shadow-sm flex items-center justify-center hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<ChevronDown className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* 消息列表 - 使用 flex-1 占据剩余空间 + 可滚动 */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{/* Messages */}
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
className="flex-1 overflow-y-auto"
|
||||
onScroll={handleScroll}
|
||||
>
|
||||
{messages.length === 0 ? (
|
||||
<div className="h-full flex items-center justify-center p-6">
|
||||
<div className="text-center max-w-2xl">
|
||||
<div className="w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg">
|
||||
<Bot className="w-8 h-8 text-white" />
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-foreground mb-2">
|
||||
开始对话
|
||||
</h3>
|
||||
<p className="text-muted-foreground mb-6 max-w-lg mx-auto">
|
||||
输入您的问题,我将为您提供专业的国土空间规划知识解答
|
||||
</p>
|
||||
<QuickQuestions onSelect={handleQuickQuestion} />
|
||||
</div>
|
||||
{renderWelcome("sm")}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<MessageList messages={messages} />
|
||||
<MessageList messages={messages} selectedModel={selectedModel} />
|
||||
<div ref={messagesEndRef} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 输入区域 - 不需要 sticky,作为 flex 子元素自然在底部 */}
|
||||
<div className="border-t border-border bg-card p-4 lg:p-6 flex-shrink-0">
|
||||
{/* 功能选择器 */}
|
||||
<div className="mb-4 space-y-3">
|
||||
<div className="flex items-center space-x-2">
|
||||
<ModeSelector mode={chatMode} onModeChange={setChatMode} />
|
||||
<ModelSelector
|
||||
selectedModel={selectedModel}
|
||||
onModelChange={setSelectedModel}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
<KnowledgeSelector
|
||||
selectedBases={selectedKnowledgeBases}
|
||||
onBasesChange={setSelectedKnowledgeBases}
|
||||
systemKnowledgeBases={systemKnowledgeBases}
|
||||
userKnowledgeBases={userKnowledgeBases}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9 px-3 flex-shrink-0"
|
||||
title="上传附件"
|
||||
>
|
||||
<Paperclip className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 输入框和发送按钮 */}
|
||||
<div className="flex items-end space-x-3">
|
||||
<div className="flex-1">
|
||||
<div className="relative">
|
||||
<Input
|
||||
ref={inputRef}
|
||||
value={inputMessage}
|
||||
onChange={(e) => setInputMessage(e.target.value)}
|
||||
onKeyPress={handleKeyPress}
|
||||
onCompositionStart={() => setIsComposing(true)}
|
||||
onCompositionEnd={() => setIsComposing(false)}
|
||||
placeholder="输入您的问题..."
|
||||
disabled={isLoading || isStreaming}
|
||||
className={cn(
|
||||
"min-h-[48px] resize-none touch-manipulation pr-12 rounded-xl",
|
||||
"border-border/50 bg-background/80 backdrop-blur-sm",
|
||||
"focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500/50",
|
||||
"transition-all duration-200"
|
||||
)}
|
||||
/>
|
||||
{isStreaming && (
|
||||
<div className="absolute right-3 top-1/2 -translate-y-1/2">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" />
|
||||
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }} />
|
||||
<div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleSendMessage}
|
||||
disabled={!inputMessage.trim() || isLoading || isStreaming}
|
||||
size="icon"
|
||||
className={cn(
|
||||
"h-12 w-12 flex-shrink-0 touch-manipulation rounded-xl",
|
||||
"bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700",
|
||||
"shadow-lg hover:shadow-xl transition-all duration-200",
|
||||
"disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
)}
|
||||
>
|
||||
{isLoading || isStreaming ? (
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
) : (
|
||||
<Send className="w-5 h-5" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 输入提示 */}
|
||||
<div className="mt-3 flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span className="hidden sm:block">按 Enter 发送,Shift + Enter 换行</span>
|
||||
<span className="sm:hidden">点击发送按钮发送消息</span>
|
||||
{isStreaming && (
|
||||
<span className="flex items-center gap-1 text-blue-600">
|
||||
<div className="w-1.5 h-1.5 bg-blue-500 rounded-full animate-pulse" />
|
||||
正在生成回复...
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{renderInputArea()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { ChatMessage, ThinkingStep } from "@/types";
|
||||
import { User, Bot, MoreVertical, ThumbsUp, ThumbsDown, Copy, Edit, RotateCcw, Trash2, Loader2, CheckCircle2, FileSearch, Brain, Sparkles } from "lucide-react";
|
||||
import { User, Bot, Copy, Edit, RotateCcw, ThumbsUp, ThumbsDown, Loader2, CheckCircle2, FileSearch, Brain, Sparkles } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
|
||||
@@ -9,12 +10,6 @@ import { tomorrow } from "react-syntax-highlighter/dist/esm/styles/prism";
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
import { zhCN } from "date-fns/locale";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { useChatStore } from "@/store/chat";
|
||||
import SourceReferences from "./source-references";
|
||||
import { useState } from "react";
|
||||
@@ -22,84 +17,64 @@ import { toast } from "sonner";
|
||||
|
||||
interface MessageItemProps {
|
||||
message: ChatMessage;
|
||||
selectedModel?: string;
|
||||
}
|
||||
|
||||
// 思考过程组件
|
||||
const ThinkingProcess = ({ thinking }: { thinking: ThinkingStep[] }) => {
|
||||
if (!thinking || thinking.length === 0) return null;
|
||||
|
||||
|
||||
const getStageIcon = (stage: string) => {
|
||||
switch (stage) {
|
||||
case 'understanding': return <Brain className="h-4 w-4" />;
|
||||
case 'retrieving': return <FileSearch className="h-4 w-4 animate-spin" />;
|
||||
case 'retrieved': return <CheckCircle2 className="h-4 w-4 text-green-500" />;
|
||||
case 'generating': return <Sparkles className="h-4 w-4 animate-pulse" />;
|
||||
default: return <Loader2 className="h-4 w-4" />;
|
||||
case 'understanding': return <Brain className="h-3.5 w-3.5" />;
|
||||
case 'retrieving': return <FileSearch className="h-3.5 w-3.5 animate-spin" />;
|
||||
case 'retrieved': return <CheckCircle2 className="h-3.5 w-3.5 text-green-500" />;
|
||||
case 'generating': return <Sparkles className="h-3.5 w-3.5 animate-pulse" />;
|
||||
default: return <Loader2 className="h-3.5 w-3.5" />;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<div className="mb-3 space-y-2 text-sm text-muted-foreground bg-muted/50 rounded-lg p-3">
|
||||
<div className="mb-2.5 space-y-1.5 text-xs text-muted-foreground bg-muted/30 rounded-lg p-2.5">
|
||||
{thinking.map((step, index) => (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
{getStageIcon(step.stage)}
|
||||
<span>{step.message}</span>
|
||||
{step.time && (
|
||||
<span className="text-xs">({step.time}s)</span>
|
||||
)}
|
||||
{step.time && <span className="opacity-60">({step.time}s)</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default function MessageItem({ message }: MessageItemProps) {
|
||||
export default function MessageItem({ message, selectedModel }: MessageItemProps) {
|
||||
const isUser = message.role === "user";
|
||||
const isAssistant = message.role === "assistant";
|
||||
const { editMessage, regenerateMessage, feedbackMessage, isStreaming } = useChatStore();
|
||||
const { editMessage, regenerateMessage, feedbackMessage } = useChatStore();
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [editContent, setEditContent] = useState(message.content);
|
||||
|
||||
// 添加调试信息
|
||||
console.log(`[DEBUG-MESSAGE] 渲染消息 ${message.id}:`, {
|
||||
role: message.role,
|
||||
contentLength: message.content.length,
|
||||
contentPreview: message.content.substring(0, 50) + "..."
|
||||
});
|
||||
|
||||
const handleCopy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(message.content);
|
||||
toast.success("已复制到剪贴板");
|
||||
} catch (error) {
|
||||
toast.success("已复制");
|
||||
} catch {
|
||||
toast.error("复制失败");
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = () => {
|
||||
setIsEditing(true);
|
||||
};
|
||||
|
||||
const handleSaveEdit = async () => {
|
||||
try {
|
||||
await editMessage(message.id, editContent);
|
||||
setIsEditing(false);
|
||||
toast.success("消息已更新");
|
||||
} catch (error) {
|
||||
} catch {
|
||||
toast.error("编辑失败");
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelEdit = () => {
|
||||
setEditContent(message.content);
|
||||
setIsEditing(false);
|
||||
};
|
||||
|
||||
const handleRegenerate = async () => {
|
||||
try {
|
||||
await regenerateMessage(message.id);
|
||||
toast.success("正在重新生成回复");
|
||||
} catch (error) {
|
||||
await regenerateMessage(message.id, selectedModel);
|
||||
} catch {
|
||||
toast.error("重新生成失败");
|
||||
}
|
||||
};
|
||||
@@ -107,50 +82,62 @@ export default function MessageItem({ message }: MessageItemProps) {
|
||||
const handleFeedback = async (feedback: "like" | "dislike") => {
|
||||
try {
|
||||
await feedbackMessage(message.id, feedback);
|
||||
toast.success("感谢您的反馈");
|
||||
} catch (error) {
|
||||
toast.error("反馈提交失败");
|
||||
} catch {
|
||||
toast.error("反馈失败");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`flex gap-3 p-4 ${isAssistant ? 'justify-start' : 'justify-end'}`}>
|
||||
{isAssistant && (
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-8 h-8 bg-gradient-to-r from-blue-600 to-blue-800 rounded-lg flex items-center justify-center shadow-sm">
|
||||
<Bot className="w-4 h-4 text-white" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={`flex-1 max-w-[80%] ${isAssistant ? '' : 'flex justify-end'}`}>
|
||||
<div className={`mit-card ${isAssistant ? 'bg-card' : 'bg-primary text-primary-foreground'}`}>
|
||||
{isEditing ? (
|
||||
<div className="space-y-2">
|
||||
<textarea
|
||||
value={editContent}
|
||||
onChange={(e) => setEditContent(e.target.value)}
|
||||
className="w-full p-2 border rounded resize-none"
|
||||
rows={3}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={handleSaveEdit}>
|
||||
保存
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={handleCancelEdit}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className={cn(
|
||||
"flex gap-3 py-4 group",
|
||||
isUser ? "flex-row-reverse" : "flex-row"
|
||||
)}>
|
||||
{/* Avatar */}
|
||||
<div className="flex-shrink-0 pt-0.5">
|
||||
<div className={cn(
|
||||
"w-7 h-7 rounded-full flex items-center justify-center",
|
||||
isAssistant ? "bg-primary/10" : "bg-muted"
|
||||
)}>
|
||||
{isAssistant ? (
|
||||
<Bot className="w-3.5 h-3.5 text-primary" />
|
||||
) : (
|
||||
<>
|
||||
{/* 思考过程组件 */}
|
||||
<User className="w-3.5 h-3.5 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className={cn("min-w-0 max-w-[75%]", isUser && "flex flex-col items-end")}>
|
||||
{isEditing ? (
|
||||
<div className="space-y-2 w-full">
|
||||
<textarea
|
||||
value={editContent}
|
||||
onChange={(e) => setEditContent(e.target.value)}
|
||||
className="w-full p-2.5 border rounded-lg resize-none text-sm bg-card"
|
||||
rows={3}
|
||||
/>
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button size="sm" variant="ghost" onClick={() => { setEditContent(message.content); setIsEditing(false); }}>取消</Button>
|
||||
<Button size="sm" onClick={handleSaveEdit}>保存</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Bubble */}
|
||||
<div className={cn(
|
||||
"px-3.5 py-2.5 text-sm leading-relaxed",
|
||||
isUser
|
||||
? "bg-primary text-primary-foreground rounded-2xl rounded-tr-sm"
|
||||
: "rounded-2xl rounded-tl-sm"
|
||||
)}>
|
||||
{isAssistant && message.thinking && (
|
||||
<ThinkingProcess thinking={message.thinking} />
|
||||
)}
|
||||
|
||||
{/* 消息内容 */}
|
||||
<div className="prose prose-sm max-w-none dark:prose-invert">
|
||||
|
||||
<div className={cn(
|
||||
"prose prose-sm max-w-none",
|
||||
isUser ? "prose-invert" : "dark:prose-invert"
|
||||
)}>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
components={{
|
||||
@@ -161,138 +148,75 @@ export default function MessageItem({ message }: MessageItemProps) {
|
||||
style={tomorrow}
|
||||
language={match[1]}
|
||||
PreTag="div"
|
||||
className="rounded-md"
|
||||
className="rounded-md !text-xs"
|
||||
{...props}
|
||||
>
|
||||
{String(children).replace(/\n$/, "")}
|
||||
</SyntaxHighlighter>
|
||||
) : (
|
||||
<code className={className} {...props}>
|
||||
{children}
|
||||
</code>
|
||||
<code className={cn("px-1 py-0.5 rounded text-xs", isUser ? "bg-primary-foreground/20" : "bg-muted")} {...props}>{children}</code>
|
||||
);
|
||||
},
|
||||
table: ({ children }) => (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full border-collapse border border-border">
|
||||
{children}
|
||||
</table>
|
||||
<div className="overflow-x-auto -mx-1">
|
||||
<table className="min-w-full border-collapse border border-border text-xs">{children}</table>
|
||||
</div>
|
||||
),
|
||||
th: ({ children }) => (
|
||||
<th className="border border-border bg-muted px-3 py-2 text-left font-medium">
|
||||
{children}
|
||||
</th>
|
||||
<th className="border border-border bg-muted px-2 py-1.5 text-left font-medium">{children}</th>
|
||||
),
|
||||
td: ({ children }) => (
|
||||
<td className="border border-border px-3 py-2">
|
||||
{children}
|
||||
</td>
|
||||
<td className="border border-border px-2 py-1.5">{children}</td>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{message.content}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
|
||||
{/* 知识来源 */}
|
||||
|
||||
{isAssistant && message.metadata?.sources && message.metadata.sources.length > 0 && (
|
||||
<div className="mt-4 pt-4 border-t border-border">
|
||||
<SourceReferences sources={message.metadata.sources} maxSources={5} />
|
||||
<div className="mt-2.5 pt-2.5 border-t border-border/30">
|
||||
<SourceReferences sources={message.metadata.sources} maxSources={3} />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className={`flex items-center gap-1 mt-2 opacity-0 group-hover:opacity-100 transition-opacity ${
|
||||
isAssistant ? "flex-row" : "flex-row-reverse"
|
||||
}`}>
|
||||
{/* 复制按钮 */}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleCopy}
|
||||
className="h-7 w-7 p-0 hover:bg-muted/50"
|
||||
>
|
||||
<Copy className="h-3 w-3" />
|
||||
</Button>
|
||||
|
||||
{/* 用户消息操作 */}
|
||||
{isUser && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleEdit}
|
||||
className="h-7 w-7 p-0 hover:bg-muted/50"
|
||||
>
|
||||
<Edit className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* 助手消息操作 */}
|
||||
{isAssistant && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleRegenerate}
|
||||
className="h-7 w-7 p-0 hover:bg-muted/50"
|
||||
>
|
||||
<RotateCcw className="h-3 w-3" />
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className={cn(
|
||||
"flex items-center gap-0.5 mt-1",
|
||||
isUser ? "flex-row-reverse" : "flex-row"
|
||||
)}>
|
||||
<Button size="sm" variant="ghost" onClick={handleCopy} className="h-6 w-6 p-0 text-muted-foreground hover:text-foreground">
|
||||
<Copy className="h-3 w-3" />
|
||||
</Button>
|
||||
|
||||
{/* 反馈按钮 */}
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleFeedback("like")}
|
||||
className={`h-7 w-7 p-0 hover:bg-muted/50 ${
|
||||
message.feedback === "like" ? "text-green-600" : ""
|
||||
}`}
|
||||
>
|
||||
<ThumbsUp className="h-3 w-3" />
|
||||
{isUser && (
|
||||
<Button size="sm" variant="ghost" onClick={() => setIsEditing(true)} className="h-6 w-6 p-0 text-muted-foreground hover:text-foreground">
|
||||
<Edit className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleFeedback("dislike")}
|
||||
className={`h-7 w-7 p-0 hover:bg-muted/50 ${
|
||||
message.feedback === "dislike" ? "text-red-600" : ""
|
||||
}`}
|
||||
>
|
||||
<ThumbsDown className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 时间戳和编辑标记 */}
|
||||
<div className={`text-xs text-muted-foreground mt-1 ${
|
||||
isUser ? "text-right" : "text-left"
|
||||
}`}>
|
||||
{message.created_at ? formatDistanceToNow(
|
||||
new Date(new Date(message.created_at).getTime() + 8 * 60 * 60 * 1000),
|
||||
{
|
||||
addSuffix: true,
|
||||
locale: zhCN
|
||||
}) : '未知时间'}
|
||||
{message.edited && (
|
||||
<span className="ml-1 text-muted-foreground">(已编辑)</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{isAssistant && (
|
||||
<>
|
||||
<Button size="sm" variant="ghost" onClick={handleRegenerate} className="h-6 w-6 p-0 text-muted-foreground hover:text-foreground">
|
||||
<RotateCcw className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => handleFeedback("like")} className={cn("h-6 w-6 p-0", message.feedback === "like" ? "text-green-600" : "text-muted-foreground hover:text-foreground")}>
|
||||
<ThumbsUp className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => handleFeedback("dislike")} className={cn("h-6 w-6 p-0", message.feedback === "dislike" ? "text-red-500" : "text-muted-foreground hover:text-foreground")}>
|
||||
<ThumbsDown className="h-3 w-3" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<span className="text-[10px] text-muted-foreground/50 mx-1">
|
||||
{message.created_at ? formatDistanceToNow(
|
||||
new Date(new Date(message.created_at).getTime() + 8 * 60 * 60 * 1000),
|
||||
{ addSuffix: true, locale: zhCN }
|
||||
) : ""}
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isAssistant && (
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-8 h-8 bg-gradient-to-r from-gray-600 to-gray-800 rounded-lg flex items-center justify-center shadow-sm">
|
||||
<User className="w-4 h-4 text-white" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,13 +5,14 @@ import MessageItem from "./message-item";
|
||||
|
||||
interface MessageListProps {
|
||||
messages: ChatMessage[];
|
||||
selectedModel?: string;
|
||||
}
|
||||
|
||||
export default function MessageList({ messages }: MessageListProps) {
|
||||
export default function MessageList({ messages, selectedModel }: MessageListProps) {
|
||||
return (
|
||||
<div className="space-y-4 p-4">
|
||||
<div className="max-w-3xl mx-auto px-4">
|
||||
{messages.map((message) => (
|
||||
<MessageItem key={message.id} message={message} />
|
||||
<MessageItem key={message.id} message={message} selectedModel={selectedModel} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -9,39 +9,23 @@ interface QuickQuestionsProps {
|
||||
|
||||
const quickQuestions = [
|
||||
"什么是国土空间规划?",
|
||||
"国土空间规划的主要原则是什么?",
|
||||
"如何进行国土空间规划编制?",
|
||||
"国土空间规划的三区三线是什么?",
|
||||
"国土空间规划与城市规划的区别?",
|
||||
"国土空间规划中的三区三线是什么?",
|
||||
"如何评价国土空间规划的合理性?",
|
||||
"如何进行国土空间规划编制?",
|
||||
];
|
||||
|
||||
export default function QuickQuestions({ onSelect }: QuickQuestionsProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="text-sm text-muted-foreground text-center">
|
||||
快速开始,选择一个问题:
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 max-w-4xl mx-auto">
|
||||
{quickQuestions.map((question, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="justify-start text-left h-auto p-4 hover:bg-muted/50 transition-colors"
|
||||
onClick={() => onSelect(question)}
|
||||
>
|
||||
<MessageSquare className="w-4 h-4 mr-3 flex-shrink-0" />
|
||||
<span className="text-sm leading-relaxed">{question}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-w-lg mx-auto">
|
||||
{quickQuestions.map((question, index) => (
|
||||
<button
|
||||
key={index}
|
||||
onClick={() => onSelect(question)}
|
||||
className="text-left px-3.5 py-2.5 rounded-xl border border-border/40 bg-card/50 hover:bg-muted/50 hover:border-border/70 transition-colors text-sm text-foreground/80 leading-relaxed"
|
||||
>
|
||||
{question}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+155
-238
@@ -1,34 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import { useChatStore } from "@/store/chat";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import {
|
||||
Plus,
|
||||
MessageSquare,
|
||||
Menu,
|
||||
X,
|
||||
import {
|
||||
Plus,
|
||||
MessageSquare,
|
||||
Edit2,
|
||||
Trash2,
|
||||
Download,
|
||||
MoreVertical,
|
||||
Search,
|
||||
Calendar,
|
||||
Clock,
|
||||
ChevronRight
|
||||
} from "lucide-react";
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
import { zhCN } from "date-fns/locale";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -40,27 +24,48 @@ import {
|
||||
import { toast } from "sonner";
|
||||
import ExportDialog from "./export-dialog";
|
||||
|
||||
export default function Sidebar() {
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
||||
interface SidebarProps {
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
function groupSessionsByDate(sessions: any[]) {
|
||||
const now = new Date();
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const yesterday = new Date(today.getTime() - 86400000);
|
||||
const lastWeek = new Date(today.getTime() - 7 * 86400000);
|
||||
const lastMonth = new Date(today.getTime() - 30 * 86400000);
|
||||
|
||||
const groups: { label: string; sessions: any[] }[] = [
|
||||
{ label: "今天", sessions: [] },
|
||||
{ label: "昨天", sessions: [] },
|
||||
{ label: "过去 7 天", sessions: [] },
|
||||
{ label: "过去 30 天", sessions: [] },
|
||||
{ label: "更早", sessions: [] },
|
||||
];
|
||||
|
||||
sessions.forEach(session => {
|
||||
const date = new Date(session.created_at);
|
||||
if (date >= today) groups[0].sessions.push(session);
|
||||
else if (date >= yesterday) groups[1].sessions.push(session);
|
||||
else if (date >= lastWeek) groups[2].sessions.push(session);
|
||||
else if (date >= lastMonth) groups[3].sessions.push(session);
|
||||
else groups[4].sessions.push(session);
|
||||
});
|
||||
|
||||
return groups.filter(g => g.sessions.length > 0);
|
||||
}
|
||||
|
||||
export default function Sidebar({ onClose }: SidebarProps) {
|
||||
const [editingSession, setEditingSession] = useState<number | null>(null);
|
||||
const [editTitle, setEditTitle] = useState("");
|
||||
const [deleteSessionId, setDeleteSessionId] = useState<number | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [openDropdownId, setOpenDropdownId] = useState<number | null>(null);
|
||||
const router = useRouter();
|
||||
const { sessions, currentSession, selectSession, createSession, renameSession, deleteSession } = useChatStore();
|
||||
|
||||
// 过滤会话(按创建时间排序)
|
||||
const filteredSessions = () => {
|
||||
if (!searchQuery) {
|
||||
return sessions.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
|
||||
}
|
||||
|
||||
return sessions
|
||||
.filter(session =>
|
||||
session.title.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
)
|
||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
|
||||
const sorted = [...sessions].sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
|
||||
if (!searchQuery) return sorted;
|
||||
return sorted.filter(s => s.title.toLowerCase().includes(searchQuery.toLowerCase()));
|
||||
};
|
||||
|
||||
const handleNewChat = async () => {
|
||||
@@ -68,16 +73,12 @@ export default function Sidebar() {
|
||||
if (newSession) {
|
||||
selectSession(newSession.id);
|
||||
}
|
||||
onClose?.();
|
||||
};
|
||||
|
||||
const handleSelectSession = async (sessionId: number) => {
|
||||
await selectSession(sessionId);
|
||||
setIsMobileMenuOpen(false);
|
||||
};
|
||||
|
||||
const handleRenameSession = (sessionId: number, currentTitle: string) => {
|
||||
setEditingSession(sessionId);
|
||||
setEditTitle(currentTitle);
|
||||
onClose?.();
|
||||
};
|
||||
|
||||
const handleSaveRename = async () => {
|
||||
@@ -86,246 +87,162 @@ export default function Sidebar() {
|
||||
await renameSession(editingSession, editTitle.trim());
|
||||
setEditingSession(null);
|
||||
setEditTitle("");
|
||||
toast.success("会话重命名成功");
|
||||
} catch (error) {
|
||||
toast.success("重命名成功");
|
||||
} catch {
|
||||
toast.error("重命名失败");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelRename = () => {
|
||||
setEditingSession(null);
|
||||
setEditTitle("");
|
||||
};
|
||||
|
||||
const handleDeleteSession = (sessionId: number) => {
|
||||
setDeleteSessionId(sessionId);
|
||||
};
|
||||
|
||||
const handleConfirmDelete = async () => {
|
||||
if (deleteSessionId) {
|
||||
try {
|
||||
await deleteSession(deleteSessionId);
|
||||
setDeleteSessionId(null);
|
||||
toast.success("会话已删除");
|
||||
} catch (error) {
|
||||
toast.success("已删除");
|
||||
} catch {
|
||||
toast.error("删除失败");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelDelete = () => {
|
||||
setDeleteSessionId(null);
|
||||
};
|
||||
|
||||
const renderSessionItem = (session: any) => {
|
||||
return (
|
||||
<div
|
||||
key={session.id}
|
||||
className={`group relative flex items-center gap-3 px-3 py-2 rounded-lg cursor-pointer transition-all hover:bg-muted/50 ${
|
||||
currentSession?.id === session.id ? 'bg-muted border border-border' : ''
|
||||
}`}
|
||||
onClick={() => handleSelectSession(session.id)}
|
||||
>
|
||||
<MessageSquare className="w-4 h-4 text-muted-foreground flex-shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-foreground truncate">
|
||||
{session.title}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{session.created_at ? (() => {
|
||||
const rawDate = new Date(session.created_at);
|
||||
const date = new Date(rawDate.getTime() + 8 * 60 * 60 * 1000);
|
||||
const now = new Date();
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
|
||||
if (date >= today) {
|
||||
// 今天:只显示时间
|
||||
return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', timeZone: 'Asia/Shanghai' });
|
||||
} else {
|
||||
// 昨天及更早:显示日期+时间
|
||||
return date.toLocaleString('zh-CN', {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
timeZone: 'Asia/Shanghai'
|
||||
});
|
||||
}
|
||||
})() : '未知时间'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<DropdownMenu
|
||||
open={openDropdownId === session.id}
|
||||
onOpenChange={(open) => setOpenDropdownId(open ? session.id : null)}
|
||||
>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="opacity-0 group-hover:opacity-100 transition-opacity h-6 w-6 p-0"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<MoreVertical className="w-3 h-3" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
|
||||
<DropdownMenuItem
|
||||
onSelect={() => {
|
||||
handleRenameSession(session.id, session.title);
|
||||
}}
|
||||
>
|
||||
<Edit2 className="w-4 h-4 mr-2" />
|
||||
重命名
|
||||
</DropdownMenuItem>
|
||||
<ExportDialog
|
||||
sessionId={session.id}
|
||||
sessionTitle={session.title}
|
||||
onClose={() => setOpenDropdownId(null)}
|
||||
>
|
||||
<DropdownMenuItem onSelect={(e) => e.preventDefault()}>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
导出
|
||||
</DropdownMenuItem>
|
||||
</ExportDialog>
|
||||
<DropdownMenuItem
|
||||
onSelect={() => {
|
||||
handleDeleteSession(session.id);
|
||||
}}
|
||||
className="text-destructive"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
删除
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
const groups = groupSessionsByDate(filteredSessions());
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 移动端菜单按钮 */}
|
||||
<div className="lg:hidden fixed top-4 left-4 z-50">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
|
||||
>
|
||||
{isMobileMenuOpen ? <X className="w-4 h-4" /> : <Menu className="w-4 h-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 侧边栏 */}
|
||||
<div className={`
|
||||
fixed lg:static inset-y-0 left-0 z-40 w-80 max-w-[85vw] bg-card/50 backdrop-blur-sm border-r border-border transform transition-transform duration-300 ease-in-out mobile-safe-area lg:h-full
|
||||
${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'}
|
||||
`}>
|
||||
<div className="flex flex-col h-full">
|
||||
{/* 头部 */}
|
||||
<div className="p-4 border-b">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold text-foreground">对话历史</h2>
|
||||
<Button
|
||||
onClick={handleNewChat}
|
||||
size="sm"
|
||||
className="h-8 px-3"
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
新建对话
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 搜索框 */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="搜索对话..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9 h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col h-full">
|
||||
{/* Header */}
|
||||
<div className="px-3 pt-4 pb-3 space-y-3 border-b border-border/30">
|
||||
<div className="flex items-center justify-between px-1">
|
||||
<span className="text-sm font-semibold text-foreground">对话</span>
|
||||
<Button onClick={handleNewChat} size="sm" variant="ghost" className="h-7 w-7 p-0 hover:bg-primary/10 hover:text-primary">
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="搜索"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-8 h-8 text-sm bg-muted/30 border border-border/20 focus-visible:ring-1 focus-visible:border-primary/30"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 会话列表 */}
|
||||
<ScrollArea className="flex-1 px-2">
|
||||
<div className="py-4">
|
||||
<div className="space-y-1">
|
||||
{filteredSessions().map(renderSessionItem)}
|
||||
</div>
|
||||
|
||||
{sessions.length === 0 && (
|
||||
<div className="text-center py-8">
|
||||
<MessageSquare className="w-12 h-12 text-muted-foreground mx-auto mb-3" />
|
||||
<p className="text-sm text-muted-foreground mb-2">还没有对话记录</p>
|
||||
<p className="text-xs text-muted-foreground">开始一个新的对话吧</p>
|
||||
{/* Session list with date groups */}
|
||||
<ScrollArea className="flex-1 px-2">
|
||||
<div className="pb-4">
|
||||
{groups.map(group => (
|
||||
<div key={group.label} className="mb-3">
|
||||
<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground/70 uppercase tracking-wider">
|
||||
{group.label}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div className="space-y-0.5">
|
||||
{group.sessions.map(session => (
|
||||
<div
|
||||
key={session.id}
|
||||
className="relative rounded-lg cursor-pointer transition-colors hover:bg-muted/50"
|
||||
style={{
|
||||
backgroundColor: currentSession?.id === session.id ? 'var(--muted)' : undefined,
|
||||
color: currentSession?.id === session.id ? 'var(--foreground)' : undefined
|
||||
}}
|
||||
onClick={() => handleSelectSession(session.id)}
|
||||
>
|
||||
{/* Title row */}
|
||||
<div className="flex items-center gap-2 px-2.5 py-2 pr-28">
|
||||
<MessageSquare className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0" />
|
||||
<span className="text-sm truncate">{session.title}</span>
|
||||
</div>
|
||||
|
||||
{/* Action buttons — absolute positioned, always visible */}
|
||||
<div
|
||||
className="absolute right-1.5 top-1/2 -translate-y-1/2 flex items-center gap-1"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
className="inline-flex items-center justify-center w-7 h-7 rounded-md text-gray-500 hover:text-gray-800 hover:bg-gray-200 transition-colors"
|
||||
title="重命名"
|
||||
onClick={() => { setEditingSession(session.id); setEditTitle(session.title); }}
|
||||
>
|
||||
<Edit2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<ExportDialog sessionId={session.id} sessionTitle={session.title} onClose={() => {}}>
|
||||
<button
|
||||
className="inline-flex items-center justify-center w-7 h-7 rounded-md text-gray-500 hover:text-gray-800 hover:bg-gray-200 transition-colors"
|
||||
title="导出"
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</ExportDialog>
|
||||
<button
|
||||
className="inline-flex items-center justify-center w-7 h-7 rounded-md text-gray-500 hover:text-red-600 hover:bg-red-50 transition-colors"
|
||||
title="删除"
|
||||
onClick={() => setDeleteSessionId(session.id)}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{sessions.length === 0 && (
|
||||
<div className="text-center py-12">
|
||||
<MessageSquare className="w-8 h-8 text-muted-foreground/40 mx-auto mb-2" />
|
||||
<p className="text-xs text-muted-foreground">开始新的对话</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
{/* Footer — new chat button with distinct background */}
|
||||
<div className="px-3 py-3 border-t border-border/30 bg-muted/20">
|
||||
<Button
|
||||
onClick={handleNewChat}
|
||||
variant="outline"
|
||||
className="w-full h-9 text-sm justify-center gap-2 border-dashed border-border/50 hover:bg-primary/5 hover:text-primary hover:border-primary/30"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
新对话
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 移动端遮罩 */}
|
||||
{isMobileMenuOpen && (
|
||||
<div
|
||||
className="lg:hidden fixed inset-0 bg-black bg-opacity-50 z-30"
|
||||
onClick={() => setIsMobileMenuOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 重命名对话框 */}
|
||||
<Dialog open={!!editingSession} onOpenChange={handleCancelRename}>
|
||||
<DialogContent>
|
||||
{/* Rename dialog */}
|
||||
<Dialog open={!!editingSession} onOpenChange={() => { setEditingSession(null); setEditTitle(""); }}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>重命名会话</DialogTitle>
|
||||
<DialogDescription>
|
||||
为这个会话输入一个新的名称
|
||||
</DialogDescription>
|
||||
<DialogTitle>重命名</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<div className="py-2">
|
||||
<Input
|
||||
value={editTitle}
|
||||
onChange={(e) => setEditTitle(e.target.value)}
|
||||
placeholder="输入新的会话名称"
|
||||
onKeyPress={(e) => {
|
||||
if (e.key === 'Enter' && editTitle.trim()) {
|
||||
handleSaveRename();
|
||||
}
|
||||
}}
|
||||
placeholder="对话名称"
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && editTitle.trim()) handleSaveRename(); }}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancelRename}>
|
||||
取消
|
||||
</Button>
|
||||
<Button onClick={handleSaveRename} disabled={!editTitle.trim()}>
|
||||
保存
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => { setEditingSession(null); setEditTitle(""); }}>取消</Button>
|
||||
<Button onClick={handleSaveRename} disabled={!editTitle.trim()}>保存</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* 删除确认对话框 */}
|
||||
{/* Delete dialog */}
|
||||
<Dialog open={!!deleteSessionId} onOpenChange={() => setDeleteSessionId(null)}>
|
||||
<DialogContent>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>删除会话</DialogTitle>
|
||||
<DialogDescription>
|
||||
确定要删除这个会话吗?此操作无法撤销,会话中的所有消息都将被删除。
|
||||
</DialogDescription>
|
||||
<DialogTitle>删除对话</DialogTitle>
|
||||
<DialogDescription>确定要删除这个对话吗?此操作无法撤销。</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancelDelete}>
|
||||
取消
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={handleConfirmDelete}>
|
||||
删除
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setDeleteSessionId(null)}>取消</Button>
|
||||
<Button variant="destructive" onClick={handleConfirmDelete}>删除</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
+8
-21
@@ -40,39 +40,25 @@ async function apiRequest<T>(
|
||||
};
|
||||
|
||||
try {
|
||||
console.log(`🌐 API请求: ${endpoint}`, { url, headers: defaultHeaders });
|
||||
const response = await fetch(url, config);
|
||||
console.log(`📡 API响应: ${endpoint}`, { status: response.status, ok: response.ok });
|
||||
|
||||
|
||||
if (!response.ok) {
|
||||
// 401错误:token无效或过期,跳转到登录页
|
||||
if (response.status === 401) {
|
||||
console.warn("🚨 收到401错误,token可能无效或过期");
|
||||
console.log("🔍 当前路径:", window.location.pathname);
|
||||
console.log("🔍 当前token:", localStorage.getItem("auth_token") ? "存在" : "不存在");
|
||||
|
||||
// 清除本地存储的token
|
||||
localStorage.removeItem("auth_token");
|
||||
|
||||
// 只在非登录/注册页面才跳转,避免死循环
|
||||
if (typeof window !== 'undefined' &&
|
||||
if (typeof window !== 'undefined' &&
|
||||
!window.location.pathname.includes('/login') &&
|
||||
!window.location.pathname.includes('/register')) {
|
||||
console.warn("🔄 Token无效或已过期,跳转到登录页");
|
||||
// 使用replace而不是href,避免在历史记录中留下当前页面
|
||||
window.location.replace("/login");
|
||||
}
|
||||
|
||||
throw new Error("认证已过期,请重新登录");
|
||||
}
|
||||
|
||||
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.detail || `HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`API请求失败 ${endpoint}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -443,7 +429,7 @@ export const chatAPI = {
|
||||
knowledgeBaseIds?: string[],
|
||||
signal?: AbortSignal,
|
||||
onChunk?: (chunk: string) => void,
|
||||
onComplete?: (sessionId: number) => void,
|
||||
onComplete?: (sessionId: number, messageId?: number, userMessageId?: number) => void,
|
||||
onError?: (error: string) => void,
|
||||
onStatus?: (status: string) => void,
|
||||
onThinking?: (step: { step: string; message: string; details?: Record<string, any>; timestamp?: string }) => void,
|
||||
@@ -598,8 +584,8 @@ export const chatAPI = {
|
||||
console.log("[DEBUG-STREAM] 接收chunk:", data.content);
|
||||
onChunk?.(data.content);
|
||||
} else if (data.type === "done") {
|
||||
console.log("[DEBUG-STREAM] 流式完成, session_id:", data.session_id);
|
||||
onComplete?.(data.session_id);
|
||||
console.log("[DEBUG-STREAM] 流式完成, session_id:", data.session_id, "message_id:", data.message_id, "user_message_id:", data.user_message_id);
|
||||
onComplete?.(data.session_id, data.message_id, data.user_message_id);
|
||||
} else if (data.error) {
|
||||
console.log("[DEBUG-STREAM] 流式错误:", data.error);
|
||||
onError?.(data.error);
|
||||
@@ -685,13 +671,14 @@ export const chatAPI = {
|
||||
});
|
||||
},
|
||||
|
||||
async regenerateMessage(messageId: number) {
|
||||
async regenerateMessage(messageId: number, model?: string) {
|
||||
return apiRequest<{
|
||||
message: string;
|
||||
new_message_id: number;
|
||||
content: string;
|
||||
}>(`/chat/messages/${messageId}/regenerate`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: model || null }),
|
||||
});
|
||||
},
|
||||
|
||||
|
||||
+31
-27
@@ -28,7 +28,7 @@ interface ChatActions {
|
||||
addMessage: (message: ChatMessage) => void;
|
||||
updateMessage: (messageId: number, content: string) => void;
|
||||
editMessage: (messageId: number, newContent: string) => Promise<void>;
|
||||
regenerateMessage: (messageId: number) => Promise<void>;
|
||||
regenerateMessage: (messageId: number, model?: string) => Promise<void>;
|
||||
feedbackMessage: (messageId: number, feedback: "like" | "dislike") => Promise<void>;
|
||||
stopGeneration: () => void;
|
||||
|
||||
@@ -228,12 +228,6 @@ export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
// 创建新的 AbortController
|
||||
const abortController = new AbortController();
|
||||
|
||||
console.log("[DEBUG-CHAT] 开始流式发送:", {
|
||||
message: message,
|
||||
sessionId: currentSession.id,
|
||||
knowledgeBaseIds: knowledgeBaseIds
|
||||
});
|
||||
|
||||
set({ isStreaming: true, error: null, abortController });
|
||||
|
||||
// 添加用户消息
|
||||
@@ -299,8 +293,7 @@ export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
// 处理内容chunk
|
||||
chunkCount++;
|
||||
totalChars += data.content.length;
|
||||
console.log(`[DEBUG-STREAM] 接收并显示chunk ${chunkCount}:`, data.content);
|
||||
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
set((state) => ({
|
||||
messages: state.messages.map(msg =>
|
||||
@@ -315,8 +308,7 @@ export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
// 向后兼容:纯文本chunk
|
||||
chunkCount++;
|
||||
totalChars += chunk.length;
|
||||
console.log(`[DEBUG-STREAM] 接收并显示chunk ${chunkCount}:`, chunk);
|
||||
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
set((state) => ({
|
||||
messages: state.messages.map(msg =>
|
||||
@@ -328,17 +320,30 @@ export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
});
|
||||
}
|
||||
},
|
||||
(sessionId: number) => {
|
||||
// 流式完成,直接处理
|
||||
console.log(`[DEBUG-STREAM] 流式完成 - 总chunk数: ${chunkCount}, 总字符数: ${totalChars}`);
|
||||
set({ isStreaming: false, abortController: null });
|
||||
|
||||
(sessionId: number, messageId?: number, userMessageId?: number) => {
|
||||
if (messageId) {
|
||||
set((state) => ({
|
||||
messages: state.messages.map(msg => {
|
||||
if (msg.id === assistantMessage.id) return { ...msg, id: messageId };
|
||||
if (userMessageId && msg.id === userMessage.id) return { ...msg, id: userMessageId };
|
||||
return msg;
|
||||
}),
|
||||
isStreaming: false,
|
||||
abortController: null,
|
||||
}));
|
||||
} else {
|
||||
const { currentSession } = get();
|
||||
if (currentSession) {
|
||||
get().loadMessages(currentSession.id);
|
||||
}
|
||||
set({ isStreaming: false, abortController: null });
|
||||
}
|
||||
|
||||
// 刷新会话列表以确保新会话显示在顶部
|
||||
get().loadSessions();
|
||||
},
|
||||
(error: string) => {
|
||||
// 流式错误
|
||||
console.log("[DEBUG-STREAM] 流式错误:", error);
|
||||
set({ error, isStreaming: false, abortController: null });
|
||||
},
|
||||
undefined, // onStatus
|
||||
@@ -409,20 +414,20 @@ export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
}
|
||||
},
|
||||
|
||||
// 重新生成消息
|
||||
regenerateMessage: async (messageId: number) => {
|
||||
// 重新生成消息(支持 assistant 消息 ID)
|
||||
regenerateMessage: async (messageId: number, model?: string) => {
|
||||
try {
|
||||
set({ isLoading: true, error: null });
|
||||
const response = await chatAPI.regenerateMessage(messageId);
|
||||
|
||||
// 删除该消息之后的所有消息
|
||||
const response = await chatAPI.regenerateMessage(messageId, model);
|
||||
|
||||
// 找到该消息,删除它及之后的所有消息
|
||||
const messageIndex = get().messages.findIndex(msg => msg.id === messageId);
|
||||
if (messageIndex !== -1) {
|
||||
set((state) => ({
|
||||
messages: state.messages.slice(0, messageIndex + 1),
|
||||
messages: state.messages.slice(0, messageIndex),
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
// 添加新的助手回复
|
||||
const newMessage: ChatMessage = {
|
||||
id: response.new_message_id,
|
||||
@@ -430,7 +435,7 @@ export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
content: response.content,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
|
||||
set((state) => ({
|
||||
messages: [...state.messages, newMessage],
|
||||
isLoading: false,
|
||||
@@ -465,9 +470,8 @@ export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
// 如果存在 AbortController,调用 abort 中止请求
|
||||
if (abortController) {
|
||||
abortController.abort();
|
||||
console.log("[DEBUG-STOP] 已中止流式请求");
|
||||
}
|
||||
|
||||
|
||||
// 清理状态
|
||||
set({ isStreaming: false, abortController: null });
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user