MessageBubble.tsx 10.8 KB
import React, { useMemo, useState, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { cn } from '@/lib/utils';
import { 
  ChevronDown, ChevronRight, 
  CheckCircle2, Loader2, Lightbulb, Terminal, 
  BookOpen, FileText 
} from 'lucide-react';

export type ReasoningStep = {
  id: string;
  type: 'status' | 'thought' | 'call' | 'response' | 'sources';
  content: string;
  name?: string;
  data?: {
    original: string[];
    wiki: string[];
  };
  time?: string;
};

interface MessageProps {
  role: 'user' | 'ai' | 'error';
  content: string;
  reasoning?: ReasoningStep[];
  isStreaming?: boolean;
  startTime?: number;
  endTime?: number;
  serverDurationMs?: number;
}

export function MessageBubble({ role, content, reasoning, isStreaming, startTime, endTime, serverDurationMs }: MessageProps) {
  // 1. 默认折叠思考过程
  const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
  const [elapsedMs, setElapsedMs] = useState<number>(0);
  const isUser = role === 'user';

  useEffect(() => {
    if (isStreaming && startTime && !endTime) {
      const interval = setInterval(() => {
        setElapsedMs(Date.now() - startTime);
      }, 100);
      return () => clearInterval(interval);
    } else if (startTime && endTime) {
      Promise.resolve().then(() => {
        setElapsedMs(endTime - startTime);
      });
    } else if (startTime && !isStreaming) {
      // If it stopped streaming but endTime wasn't set, just freeze it
      Promise.resolve().then(() => {
        setElapsedMs(Date.now() - startTime);
      });
    }
  }, [isStreaming, startTime, endTime]);

  // 结束后优先用服务器权威耗时(真实秒数);流式中用本地 tick 实时展示
  const effectiveMs = (!isStreaming && typeof serverDurationMs === 'number') ? serverDurationMs : elapsedMs;
  const displayTime = effectiveMs > 0 ? Math.round(effectiveMs / 1000) + 's' : null;

  // 提取 interactive json 并剔除
  const displayContent = useMemo(() => {
    if (!content) return '';
    const regex = /```json_interactive\s*(\{[\s\S]*?\})\s*```/;
    let newContent = content;
    if (content.match(regex)) {
      newContent = content.replace(regex, '');
    }
    newContent = newContent.replace(/`+$/, '').trim();
    return newContent;
  }, [content]);


  const hasMeaningfulReasoning = useMemo(() => {
    if (!reasoning || reasoning.length === 0) return false;
    return true;
  }, [reasoning]);

  if (role === 'error') {
    return (
      <div className="flex justify-center my-4 w-full">
        <div className="bg-red-50 border border-red-100 text-red-600 px-4 py-2 rounded-lg text-sm flex items-center space-x-2">
          <span className="font-bold">错误:</span>
          <span>{content}</span>
        </div>
      </div>
    );
  }

  return (
    <div className={cn("flex mb-6 w-full", isUser ? "justify-end" : "justify-start")}>
      <div className={cn(
        "flex items-start space-x-3 w-full max-w-[95%] md:max-w-[90%]", 
        isUser && "flex-row-reverse space-x-reverse"
      )}>
        <div className={cn(
          "w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5 shadow-sm font-bold text-xs text-white",
          isUser ? "bg-slate-700" : "bg-blue-600"
        )}>
          {isUser ? "我" : "AI"}
        </div>
        
        <div className="flex flex-col space-y-2 flex-1 min-w-0">
          {/* Reasoning Block */}
          {!isUser && hasMeaningfulReasoning && (
            <div className="w-full">
              <div className={cn(
                "bg-slate-50 border border-slate-200 rounded-xl overflow-hidden transition-all duration-200",
                !isReasoningExpanded && "max-h-12"
              )}>
                <button 
                  onClick={() => setIsReasoningExpanded(!isReasoningExpanded)}
                  className="w-full px-4 py-3 flex items-center justify-between hover:bg-slate-100/50 transition-colors"
                >
                  <div className="flex items-center space-x-2 text-xs font-bold text-slate-500 tracking-wider">
                    {isReasoningExpanded ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
                    {isStreaming ? (
                      <Loader2 className="w-3.5 h-3.5 animate-spin text-blue-500" />
                    ) : (
                      <CheckCircle2 className="w-3.5 h-3.5 text-green-500" />
                    )}
                    <span>查看思考过程 ({reasoning!.length} 步{displayTime ? `, ${displayTime}` : ''})</span>
                  </div>
                </button>
                
                {isReasoningExpanded && (
                  <div className="px-4 pb-4 space-y-3 border-t border-slate-100 pt-3 bg-white/50">
                    {reasoning!.map((step, idx) => (
                      <div key={step.id || idx} className="text-xs flex flex-col space-y-1 mt-2 first:mt-0">
                        <div className="flex items-center justify-between">
                          <div className="flex items-center space-x-1.5 text-slate-400 font-semibold uppercase tracking-wider text-[9px]">
                            {step.type === 'thought' && <Lightbulb className="w-3 h-3 text-yellow-500" />}
                            {step.type === 'call' && <Terminal className="w-3 h-3 text-blue-500" />}
                            {step.type === 'response' && <CheckCircle2 className="w-3 h-3 text-green-500" />}
                            {step.type === 'sources' && <BookOpen className="w-3 h-3 text-indigo-500" />}
                            <span>
                              {step.type === 'call' ? '工具调用' : 
                               step.type === 'response' ? '工具返回' : 
                               step.type === 'sources' ? '引用来源' : '思考'} 
                              {step.name ? ` | ${step.name}` : ''}
                            </span>
                          </div>
                          {step.time && (
                            <span className="text-[9px] text-slate-400 font-medium tracking-wide tabular-nums">
                              {step.time}
                            </span>
                          )}
                        </div>
                        
                        {/* 工具详情折叠 */}
                        {(step.type === 'call' || step.type === 'response') ? (
                          <details className="group ml-4.5 border-l-2 border-slate-100 pl-3 py-1">
                             <summary className="text-[10px] text-slate-500 cursor-pointer hover:text-blue-600 transition-colors list-none flex items-center gap-1">
                                <ChevronRight className="w-2.5 h-2.5 transition-transform group-open:rotate-90" />
                                <span>点击查看数据详情</span>
                             </summary>
                             <pre className="mt-2 p-2 text-slate-600 leading-relaxed font-mono whitespace-pre-wrap break-all max-h-60 overflow-y-auto bg-slate-100/50 rounded-md border border-slate-200/50 shadow-inner">
                                {step.content}
                             </pre>
                          </details>
                        ) : step.type === 'sources' && step.data ? (
                          /* 增强参考资料显示 */
                          <div className="ml-4.5 border-l-2 border-indigo-100 pl-3 py-1 space-y-2">
                            {step.data.original && step.data.original.length > 0 && (
                              <div className="space-y-1">
                                <div className="text-[9px] text-slate-400 font-bold uppercase tracking-tight flex items-center gap-1">
                                  <FileText className="w-2.5 h-2.5" /> 原始文档来源
                                </div>
                                <div className="flex flex-wrap gap-1.5">
                                  {step.data.original.map(s => (
                                    <span key={s} className="px-2 py-0.5 bg-blue-50 text-blue-600 rounded-md text-[10px] font-semibold border border-blue-100 shadow-sm">
                                      {s}
                                    </span>
                                  ))}
                                </div>
                              </div>
                            )}
                            {step.data.wiki && step.data.wiki.length > 0 && (
                              <div className="space-y-1">
                                <div className="text-[9px] text-slate-400 font-bold uppercase tracking-tight flex items-center gap-1">
                                  <BookOpen className="w-2.5 h-2.5" /> 关联 Wiki 知识点
                                </div>
                                <div className="space-y-0.5">
                                  {step.data.wiki.map(s => (
                                    <div key={s} className="text-[10px] text-slate-600 flex items-center gap-1.5 py-0.5 px-2 bg-slate-100/30 rounded border border-transparent hover:border-slate-200 hover:bg-slate-100/60 transition-all">
                                      <div className="w-1 h-1 rounded-full bg-indigo-300" />
                                      {s}
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}
                          </div>
                        ) : (
                          <div className="ml-4.5 border-l-2 border-slate-100 pl-3 py-1 text-slate-600 leading-relaxed font-sans whitespace-pre-wrap">
                             {step.content}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Main Content Bubble */}
          {(displayContent || isUser) && (
            <div className={cn(
              "px-5 py-3.5 shadow-sm text-[15px] leading-relaxed break-words",
              isUser 
                ? "bg-blue-600 text-white rounded-2xl rounded-tr-sm self-end" 
                : "bg-white border border-slate-100 text-slate-800 rounded-2xl rounded-tl-sm"
            )}>
              {isUser ? (
                <div className="whitespace-pre-wrap">{displayContent}</div>
              ) : (
                <div className="prose prose-sm max-w-none prose-p:leading-relaxed prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-slate prose-headings:text-slate-900 prose-a:text-blue-600">
                  <ReactMarkdown remarkPlugins={[remarkGfm]}>
                    {displayContent}
                  </ReactMarkdown>
                </div>
              )}
            </div>
          )}

          {/* Interactive UI Cards have been moved to Dashboard in page.tsx */}
        </div>
      </div>
    </div>
  );
}