All files / src/components ActiveLearningPanel.tsx

0% Statements 0/307
0% Branches 0/1
0% Functions 0/1
0% Lines 0/307

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * ActiveLearningPanel - 主动学习状态面板
 *
 * 展示学习事件、模式和系统建议。
 */
 
import { useCallback, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Brain,
  TrendingUp,
  Lightbulb,
  Check,
  X,
  Download,
  Clock,
  BarChart3,
} from 'lucide-react';
import { Button, EmptyState, Badge } from './ui';
import { useActiveLearningStore } from '../store/activeLearningStore';
import {
  type LearningEvent,
  type LearningSuggestion,
  type LearningEventType,
} from '../types/active-learning';
import { useChatStore } from '../store/chatStore';
import { cardHover, defaultTransition } from '../lib/animations';
 
// === Constants ===
 
const EVENT_TYPE_LABELS: Record<LearningEventType, { label: string; color: string }> = {
  preference: { label: '偏好', color: 'text-amber-400' },
  correction: { label: '纠正', color: 'text-red-400' },
  context: { label: '上下文', color: 'text-purple-400' },
  feedback: { label: '反馈', color: 'text-blue-400' },
  behavior: { label: '行为', color: 'text-green-400' },
  implicit: { label: '隐式', color: 'text-gray-400' },
};
 
const PATTERN_TYPE_LABELS: Record<string, { label: string; icon: string }> = {
  preference: { label: '偏好模式', icon: '🎯' },
  rule: { label: '规则模式', icon: '📋' },
  context: { label: '上下文模式', icon: '🔗' },
  behavior: { label: '行为模式', icon: '⚡' },
};
 
// === Sub-Components ===
 
interface EventItemProps {
  event: LearningEvent;
  onAcknowledge: () => void;
}
 
function EventItem({ event, onAcknowledge }: EventItemProps) {
  const typeInfo = EVENT_TYPE_LABELS[event.type];
  const timeAgo = getTimeAgo(event.timestamp);
 
  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -10 }}
      whileHover={cardHover}
      transition={defaultTransition}
      className={`p-3 rounded-lg border ${
        event.acknowledged
          ? 'bg-gray-50 dark:bg-gray-800 border-gray-100 dark:border-gray-700'
          : 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-700'
      }`}
    >
      <div className="flex items-start justify-between gap-2">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <span className={`text-xs px-2 py-0.5 rounded ${typeInfo.color}`}>
              {typeInfo.label}
            </span>
            <span className="text-xs text-gray-500 dark:text-gray-400">{timeAgo}</span>
          </div>
          <p className="text-sm text-gray-700 dark:text-gray-300 truncate">{event.observation}</p>
          {event.inferredPreference && (
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">→ {event.inferredPreference}</p>
          )}
        </div>
 
        {!event.acknowledged && (
          <Button variant="ghost" size="sm" onClick={onAcknowledge}>
            <Check className="w-4 h-4" />
          </Button>
        )}
      </div>
 
      <div className="flex items-center gap-2 mt-2 text-xs text-gray-500 dark:text-gray-400">
        <span>置信度: {(event.confidence * 100).toFixed(0)}%</span>
        {event.appliedCount > 0 && (
          <span>• 应用 {event.appliedCount} 次</span>
        )}
      </div>
    </motion.div>
  );
}
 
interface SuggestionCardProps {
  suggestion: LearningSuggestion;
  onApply: () => void;
  onDismiss: () => void;
}
 
function SuggestionCard({ suggestion, onApply, onDismiss }: SuggestionCardProps) {
  const daysLeft = Math.ceil(
    (suggestion.expiresAt.getTime() - Date.now()) / (1000 * 60 * 60 * 24)
  );
 
  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={{ opacity: 0, scale: 0.95 }}
      whileHover={cardHover}
      transition={defaultTransition}
      className="p-4 bg-gradient-to-r from-amber-50 to-transparent dark:from-amber-900/20 dark:to-transparent rounded-lg border border-amber-200 dark:border-amber-700/50"
    >
      <div className="flex items-start gap-3">
        <Lightbulb className="w-5 h-5 text-amber-500 flex-shrink-0 mt-0.5" />
        <div className="flex-1 min-w-0">
          <p className="text-sm text-gray-700 dark:text-gray-200">{suggestion.suggestion}</p>
          <div className="flex items-center gap-2 mt-2 text-xs text-gray-500 dark:text-gray-400">
            <span>置信度: {(suggestion.confidence * 100).toFixed(0)}%</span>
            {daysLeft > 0 && <span>• {daysLeft} 天后过期</span>}
          </div>
        </div>
      </div>
 
      <div className="flex items-center gap-2 mt-3">
        <Button variant="primary" size="sm" onClick={onApply}>
          <Check className="w-3 h-3 mr-1" />
          应用
        </Button>
        <Button variant="ghost" size="sm" onClick={onDismiss}>
          <X className="w-3 h-3 mr-1" />
          忽略
        </Button>
      </div>
    </motion.div>
  );
}
 
// === Main Component ===
 
interface ActiveLearningPanelProps {
  className?: string;
}
 
export function ActiveLearningPanel({ className = '' }: ActiveLearningPanelProps) {
  const { currentAgent } = useChatStore();
  const agentId = currentAgent?.id || 'default';
 
  const [activeTab, setActiveTab] = useState<'events' | 'patterns' | 'suggestions'>('suggestions');
 
  const {
    events,
    config,
    acknowledgeEvent,
    getPatterns,
    getSuggestions,
    applySuggestion,
    dismissSuggestion,
    getStats,
    setConfig,
    exportLearningData,
    clearEvents,
  } = useActiveLearningStore();
 
  const stats = getStats(agentId);
  const agentEvents = events.filter(e => e.agentId === agentId).slice(0, 20);
  const agentPatterns = getPatterns(agentId);
  const agentSuggestions = getSuggestions(agentId);
 
  // 处理确认事件
  const handleAcknowledge = useCallback((eventId: string) => {
    acknowledgeEvent(eventId);
  }, [acknowledgeEvent]);
 
  // 处理应用建议
  const handleApplySuggestion = useCallback((suggestionId: string) => {
    applySuggestion(suggestionId);
  }, [applySuggestion]);
 
  // 处理忽略建议
  const handleDismissSuggestion = useCallback((suggestionId: string) => {
    dismissSuggestion(suggestionId);
  }, [dismissSuggestion]);
 
  // 导出学习数据
  const handleExport = useCallback(async () => {
    const data = await exportLearningData(agentId);
    const blob = new Blob([data], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `zclaw-learning-${agentId}-${new Date().toISOString().slice(0, 10)}.json`;
    a.click();
    URL.revokeObjectURL(url);
  }, [agentId, exportLearningData]);
 
  // 清除学习数据
  const handleClear = useCallback(() => {
    if (confirm('确定要清除所有学习数据吗?此操作不可撤销。')) {
      clearEvents(agentId);
    }
  }, [agentId, clearEvents]);
 
  return (
    <div className={`space-y-4 ${className}`}>
      {/* 启用开关和导出 */}
      <motion.div
        whileHover={cardHover}
        transition={defaultTransition}
        className="bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-100 dark:border-gray-700 p-3"
      >
        <div className="flex items-center justify-between">
          <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
            <Brain className="w-4 h-4 text-blue-500" />
            <span>主动学习</span>
            <Badge variant={config.enabled ? 'success' : 'default'} className="ml-1">
              {config.enabled ? '已启用' : '已禁用'}
            </Badge>
          </label>
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={config.enabled}
              onChange={(e) => setConfig({ enabled: e.target.checked })}
              className="rounded border-gray-300 dark:border-gray-600"
            />
            <Button variant="ghost" size="sm" onClick={handleExport} title="导出数据">
              <Download className="w-4 h-4" />
            </Button>
          </div>
        </div>
      </motion.div>
 
      {/* 统计概览 */}
      <motion.div
        whileHover={cardHover}
        transition={defaultTransition}
        className="bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-100 dark:border-gray-700 p-3"
      >
        <h3 className="text-xs font-semibold text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-1.5">
          <BarChart3 className="w-3.5 h-3.5" />
          学习统计
        </h3>
        <div className="grid grid-cols-4 gap-2">
          <div className="text-center">
            <div className="text-lg font-bold text-blue-500">{stats.totalEvents}</div>
            <div className="text-xs text-gray-500 dark:text-gray-400">事件</div>
          </div>
          <div className="text-center">
            <div className="text-lg font-bold text-green-500">{stats.totalPatterns}</div>
            <div className="text-xs text-gray-500 dark:text-gray-400">模式</div>
          </div>
          <div className="text-center">
            <div className="text-lg font-bold text-amber-500">{agentSuggestions.length}</div>
            <div className="text-xs text-gray-500 dark:text-gray-400">建议</div>
          </div>
          <div className="text-center">
            <div className="text-lg font-bold text-purple-500">
              {(stats.avgConfidence * 100).toFixed(0)}%
            </div>
            <div className="text-xs text-gray-500 dark:text-gray-400">置信度</div>
          </div>
        </div>
      </motion.div>
 
      {/* Tab 切换 */}
      <div className="flex border-b border-gray-200 dark:border-gray-700">
        {(['suggestions', 'events', 'patterns'] as const).map(tab => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`flex-1 py-2 text-sm font-medium transition-colors ${
              activeTab === tab
                ? 'text-emerald-600 dark:text-emerald-400 border-b-2 border-emerald-500'
                : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
            }`}
          >
            {tab === 'suggestions' && '建议'}
            {tab === 'events' && '事件'}
            {tab === 'patterns' && '模式'}
          </button>
        ))}
      </div>
 
      {/* 内容区域 */}
      <div className="space-y-3">
        <AnimatePresence mode="wait">
          {activeTab === 'suggestions' && (
            <motion.div
              key="suggestions"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="space-y-3"
            >
              {agentSuggestions.length === 0 ? (
                <EmptyState
                  icon={<Lightbulb className="w-8 h-8" />}
                  title="暂无学习建议"
                  description="系统会根据您的反馈自动生成改进建议"
                  className="py-4"
                />
              ) : (
                agentSuggestions.map(suggestion => (
                  <SuggestionCard
                    key={suggestion.id}
                    suggestion={suggestion}
                    onApply={() => handleApplySuggestion(suggestion.id)}
                    onDismiss={() => handleDismissSuggestion(suggestion.id)}
                  />
                ))
              )}
            </motion.div>
          )}
 
          {activeTab === 'events' && (
            <motion.div
              key="events"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="space-y-2"
            >
              {agentEvents.length === 0 ? (
                <EmptyState
                  icon={<Clock className="w-8 h-8" />}
                  title="暂无学习事件"
                  description="开始对话后,系统会自动记录学习事件"
                  className="py-4"
                />
              ) : (
                agentEvents.map(event => (
                  <EventItem
                    key={event.id}
                    event={event}
                    onAcknowledge={() => handleAcknowledge(event.id)}
                  />
                ))
              )}
            </motion.div>
          )}
 
          {activeTab === 'patterns' && (
            <motion.div
              key="patterns"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="space-y-2"
            >
              {agentPatterns.length === 0 ? (
                <EmptyState
                  icon={<TrendingUp className="w-8 h-8" />}
                  title="暂无学习模式"
                  description="积累更多反馈后,系统会识别出行为模式"
                  className="py-4"
                />
              ) : (
                agentPatterns.map(pattern => {
                  const typeInfo = PATTERN_TYPE_LABELS[pattern.type] || { label: pattern.type, icon: '📊' };
                  return (
                    <motion.div
                      key={`${pattern.agentId}-${pattern.pattern}`}
                      whileHover={cardHover}
                      transition={defaultTransition}
                      className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-100 dark:border-gray-700"
                    >
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-2">
                          <span>{typeInfo.icon}</span>
                          <span className="text-sm font-medium text-gray-800 dark:text-gray-200">{typeInfo.label}</span>
                        </div>
                        <span className="text-xs px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-300">
                          {(pattern.confidence * 100).toFixed(0)}%
                        </span>
                      </div>
                      <p className="text-sm text-gray-600 dark:text-gray-400">{pattern.description}</p>
                      <div className="mt-2 text-xs text-gray-500 dark:text-gray-400">
                        {pattern.examples.length} 个示例
                      </div>
                    </motion.div>
                  );
                })
              )}
            </motion.div>
          )}
        </AnimatePresence>
      </div>
 
      {/* 底部操作栏 */}
      <div className="flex items-center justify-between pt-2 border-t border-gray-100 dark:border-gray-700">
        <div className="text-xs text-gray-500 dark:text-gray-400">
          上次更新: {agentEvents[0] ? getTimeAgo(agentEvents[0].timestamp) : '无'}
        </div>
        <Button variant="ghost" size="sm" onClick={handleClear} className="text-red-500 hover:text-red-600">
          <X className="w-3 h-3 mr-1" />
          清除
        </Button>
      </div>
    </div>
  );
}
 
// === Helpers ===
 
function getTimeAgo(timestamp: number): string {
  const seconds = Math.floor((Date.now() - timestamp) / 1000);
 
  if (seconds < 60) return '刚刚';
  if (seconds < 3600) return `${Math.floor(seconds / 60)} 分钟前`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)} 小时前`;
  return `${Math.floor(seconds / 86400)} 天前`;
}
 
export default ActiveLearningPanel;