A Simple and Universal Swarm Intelligence Engine, Predicting Anything. 简洁通用的群体智能引擎,预测万物
Python agent-memoryfinancial-forecastingfuture-predictionknowledge-graphllmsmulti-agent-simulationpublic-opinion-analysispython3social-predictionswarm-intelligence
Enhance simulation functionality and frontend components for improved user experience
666ghjf8a58819fa05
diff --git a/backend/app/api/simulation.py b/backend/app/api/simulation.pyindex c7ef7f08..3e0174b6 100644--- a/backend/app/api/simulation.py+++ b/backend/app/api/simulation.py@@ -1274,21 +1274,28 @@ def generate_profiles():def start_simulation():"""开始运行模拟-+请求(JSON):{"simulation_id": "sim_xxxx", // 必填,模拟ID"platform": "parallel", // 可选: twitter / reddit / parallel (默认)"max_rounds": 100, // 可选: 最大模拟轮数,用于截断过长的模拟- "enable_graph_memory_update": false // 可选: 是否将Agent活动动态更新到Zep图谱记忆+ "enable_graph_memory_update": false, // 可选: 是否将Agent活动动态更新到Zep图谱记忆+ "force": false // 可选: 强制重新开始(会停止运行中的模拟并清理日志)}-++ 关于 force 参数:+ - 启用后,如果模拟正在运行或已完成,会先停止并清理运行日志+ - 清理的内容包括:run_state.json, actions.jsonl, simulation.log 等+ - 不会清理配置文件(simulation_config.json)和 profile 文件+ - 适用于需要重新运行模拟的场景+关于 enable_graph_memory_update:- 启用后,模拟中所有Agent的活动(发帖、评论、点赞等)都会实时更新到Zep图谱- 这可以让图谱"记住"模拟过程,用于后续分析或AI对话- 需要模拟关联的项目有有效的 graph_id- 采用批量更新机制,减少API调用次数-+返回:{"success": true,@@ -1299,24 +1306,26 @@ def start_simulation():"twitter_running": true,"reddit_running": true,"started_at": "2025-12-01T10:00:00",- "graph_memory_update_enabled": true // 是否启用了图谱记忆更新+ "graph_memory_update_enabled": true, // 是否启用了图谱记忆更新+ "force_restarted": true // 是否是强制重新开始}}"""try:data = request.get_json() or {}-+simulation_id = data.get('simulation_id')if not simulation_id:return jsonify({"success": False,"error": "请提供 simulation_id"}), 400-+platform = data.get('platform', 'parallel')max_rounds = data.get('max_rounds') # 可选:最大模拟轮数enable_graph_memory_update = data.get('enable_graph_memory_update', False) # 可选:是否启用图谱记忆更新-+ force = data.get('force', False) # 可选:强制重新开始+# 验证 max_rounds 参数if max_rounds is not None:try:@@ -1331,28 +1340,30 @@ def start_simulation():"success": False,"error": "max_rounds 必须是有效的整数"}), 400-+if platform not in ['twitter', 'reddit', 'parallel']:return jsonify({"success": False,"error": f"无效的平台类型: {platform},可选: twitter/reddit/parallel"}), 400-+# 检查模拟是否已准备好manager = SimulationManager()state = manager.get_simulation(simulation_id)-+if not state:return jsonify({"success": False,"error": f"模拟不存在: {simulation_id}"}), 404++ force_restarted = False# 智能处理状态:如果准备工作已完成,允许重新启动if state.status != SimulationStatus.READY:# 检查准备工作是否已完成is_prepared, prepare_info = _check_simulation_prepared(simulation_id)-+if is_prepared:# 准备工作已完成,检查是否有正在运行的进程if state.status == SimulationStatus.RUNNING:@@ -1360,11 +1371,27 @@ def start_simulation():run_state = SimulationRunner.get_run_state(simulation_id)if run_state and run_state.runner_status.value == "running":# 进程确实在运行- return jsonify({- "success": False,- "error": f"模拟正在运行中,请先调用 /stop 接口停止"- }), 400-+ if force:+ # 强制模式:停止运行中的模拟+ logger.info(f"强制模式:停止运行中的模拟 {simulation_id}")+ try:+ SimulationRunner.stop_simulation(simulation_id)+ except Exception as e:+ logger.warning(f"停止模拟时出现警告: {str(e)}")+ else:+ return jsonify({+ "success": False,+ "error": f"模拟正在运行中,请先调用 /stop 接口停止,或使用 force=true 强制重新开始"+ }), 400++ # 如果是强制模式,清理运行日志+ if force:+ logger.info(f"强制模式:清理模拟日志 {simulation_id}")+ cleanup_result = SimulationRunner.cleanup_simulation_logs(simulation_id)+ if not cleanup_result.get("success"):+ logger.warning(f"清理日志时出现警告: {cleanup_result.get('errors')}")+ force_restarted = True+# 进程不存在或已结束,重置状态为 readylogger.info(f"模拟 {simulation_id} 准备工作已完成,重置状态为 ready(原状态: {state.status.value})")state.status = SimulationStatus.READY@@ -1412,6 +1439,7 @@ def start_simulation():if max_rounds:response_data['max_rounds_applied'] = max_roundsresponse_data['graph_memory_update_enabled'] = enable_graph_memory_update+ response_data['force_restarted'] = force_restartedif enable_graph_memory_update:response_data['graph_id'] = graph_id@@ -1557,10 +1585,13 @@ def get_run_status(simulation_id: str):@simulation_bp.route('/<simulation_id>/run-status/detail', methods=['GET'])def get_run_status_detail(simulation_id: str):"""- 获取模拟运行详细状态(包含最近动作)+ 获取模拟运行详细状态(包含所有动作)用于前端展示实时动态+ Query参数:+ platform: 过滤平台(twitter/reddit,可选)+返回:{"success": true,@@ -1569,7 +1600,7 @@ def get_run_status_detail(simulation_id: str):"runner_status": "running","current_round": 5,...- "recent_actions": [+ "all_actions": [{"round_num": 5,"timestamp": "2025-12-01T10:30:00",@@ -1582,12 +1613,15 @@ def get_run_status_detail(simulation_id: str):"success": true},...- ]+ ],+ "twitter_actions": [...], # Twitter 平台的所有动作+ "reddit_actions": [...] # Reddit 平台的所有动作}}"""try:run_state = SimulationRunner.get_run_state(simulation_id)+ platform_filter = request.args.get('platform')if not run_state:return jsonify({@@ -1595,13 +1629,49 @@ def get_run_status_detail(simulation_id: str):"data": {"simulation_id": simulation_id,"runner_status": "idle",- "recent_actions": []+ "all_actions": [],+ "twitter_actions": [],+ "reddit_actions": []}})+ # 获取完整的动作列表+ all_actions = SimulationRunner.get_all_actions(+ simulation_id=simulation_id,+ platform=platform_filter+ )++ # 分平台获取动作+ twitter_actions = SimulationRunner.get_all_actions(+ simulation_id=simulation_id,+ platform="twitter"+ ) if not platform_filter or platform_filter == "twitter" else []++ reddit_actions = SimulationRunner.get_all_actions(+ simulation_id=simulation_id,+ platform="reddit"+ ) if not platform_filter or platform_filter == "reddit" else []++ # 获取当前轮次的动作(recent_actions 只展示最新一轮)+ current_round = run_state.current_round+ recent_actions = SimulationRunner.get_all_actions(+ simulation_id=simulation_id,+ platform=platform_filter,+ round_num=current_round+ ) if current_round > 0 else []++ # 获取基础状态信息+ result = run_state.to_dict()+ result["all_actions"] = [a.to_dict() for a in all_actions]+ result["twitter_actions"] = [a.to_dict() for a in twitter_actions]+ result["reddit_actions"] = [a.to_dict() for a in reddit_actions]+ result["rounds_count"] = len(run_state.rounds)+ # recent_actions 只展示当前最新一轮两个平台的内容+ result["recent_actions"] = [a.to_dict() for a in recent_actions]+return jsonify({"success": True,- "data": run_state.to_detail_dict()+ "data": result})except Exception as e:diff --git a/backend/app/services/oasis_profile_generator.py b/backend/app/services/oasis_profile_generator.pyindex 662ffdce..ac3b7e39 100644--- a/backend/app/services/oasis_profile_generator.py+++ b/backend/app/services/oasis_profile_generator.py@@ -61,7 +61,7 @@ class OasisAgentProfile:"""转换为Reddit平台格式"""profile = {"user_id": self.user_id,- "user_name": self.user_name,+ "username": self.user_name, # OASIS 库要求字段名为 username(无下划线)"name": self.name,"bio": self.bio,"persona": self.persona,@@ -89,7 +89,7 @@ class OasisAgentProfile:"""转换为Twitter平台格式"""profile = {"user_id": self.user_id,- "user_name": self.user_name,+ "username": self.user_name, # OASIS 库要求字段名为 username(无下划线)"name": self.name,"bio": self.bio,"persona": self.persona,diff --git a/backend/app/services/simulation_runner.py b/backend/app/services/simulation_runner.pyindex 56614a57..2985a50c 100644--- a/backend/app/services/simulation_runner.py+++ b/backend/app/services/simulation_runner.py@@ -671,38 +671,30 @@ class SimulationRunner:return state@classmethod- def get_actions(+ def _read_actions_from_file(cls,- simulation_id: str,- limit: int = 100,- offset: int = 0,- platform: Optional[str] = None,+ file_path: str,+ default_platform: Optional[str] = None,+ platform_filter: Optional[str] = None,agent_id: Optional[int] = None,round_num: Optional[int] = None) -> List[AgentAction]:"""- 获取动作历史+ 从单个动作文件中读取动作Args:- simulation_id: 模拟ID- limit: 返回数量限制- offset: 偏移量- platform: 过滤平台- agent_id: 过滤Agent+ file_path: 动作日志文件路径+ default_platform: 默认平台(当动作记录中没有 platform 字段时使用)+ platform_filter: 过滤平台+ agent_id: 过滤 Agent IDround_num: 过滤轮次-- Returns:- 动作列表"""- sim_dir = os.path.join(cls.RUN_STATE_DIR, simulation_id)- actions_log = os.path.join(sim_dir, "actions.jsonl")-- if not os.path.exists(actions_log):+ if not os.path.exists(file_path):return []actions = []- with open(actions_log, 'r', encoding='utf-8') as f:+ with open(file_path, 'r', encoding='utf-8') as f:for line in f:line = line.strip()if not line:@@ -711,8 +703,19 @@ class SimulationRunner:try:data = json.loads(line)+ # 跳过非动作记录(如 simulation_start, round_start, round_end 等事件)+ if "event_type" in data:+ continue++ # 跳过没有 agent_id 的记录(非 Agent 动作)+ if "agent_id" not in data:+ continue++ # 获取平台:优先使用记录中的 platform,否则使用默认平台+ record_platform = data.get("platform") or default_platform or ""+# 过滤- if platform and data.get("platform") != platform:+ if platform_filter and record_platform != platform_filter:continueif agent_id is not None and data.get("agent_id") != agent_id:continue@@ -722,7 +725,7 @@ class SimulationRunner:actions.append(AgentAction(round_num=data.get("round", 0),timestamp=data.get("timestamp", ""),- platform=data.get("platform", ""),+ platform=record_platform,agent_id=data.get("agent_id", 0),agent_name=data.get("agent_name", ""),action_type=data.get("action_type", ""),@@ -734,8 +737,99 @@ class SimulationRunner:except json.JSONDecodeError:continue- # 按时间倒序排列- actions.reverse()+ return actions++ @classmethod+ def get_all_actions(+ cls,+ simulation_id: str,+ platform: Optional[str] = None,+ agent_id: Optional[int] = None,+ round_num: Optional[int] = None+ ) -> List[AgentAction]:+ """+ 获取所有平台的完整动作历史(无分页限制)++ Args:+ simulation_id: 模拟ID+ platform: 过滤平台(twitter/reddit)+ agent_id: 过滤Agent+ round_num: 过滤轮次++ Returns:+ 完整的动作列表(按时间戳排序,新的在前)+ """+ sim_dir = os.path.join(cls.RUN_STATE_DIR, simulation_id)+ actions = []++ # 读取 Twitter 动作文件(根据文件路径自动设置 platform 为 twitter)+ twitter_actions_log = os.path.join(sim_dir, "twitter", "actions.jsonl")+ if not platform or platform == "twitter":+ actions.extend(cls._read_actions_from_file(+ twitter_actions_log,+ default_platform="twitter", # 自动填充 platform 字段+ platform_filter=platform,+ agent_id=agent_id,+ round_num=round_num+ ))++ # 读取 Reddit 动作文件(根据文件路径自动设置 platform 为 reddit)+ reddit_actions_log = os.path.join(sim_dir, "reddit", "actions.jsonl")+ if not platform or platform == "reddit":+ actions.extend(cls._read_actions_from_file(+ reddit_actions_log,+ default_platform="reddit", # 自动填充 platform 字段+ platform_filter=platform,+ agent_id=agent_id,+ round_num=round_num+ ))++ # 如果分平台文件不存在,尝试读取旧的单一文件格式+ if not actions:+ actions_log = os.path.join(sim_dir, "actions.jsonl")+ actions = cls._read_actions_from_file(+ actions_log,+ default_platform=None, # 旧格式文件中应该有 platform 字段+ platform_filter=platform,+ agent_id=agent_id,+ round_num=round_num+ )++ # 按时间戳排序(新的在前)+ actions.sort(key=lambda x: x.timestamp, reverse=True)++ return actions++ @classmethod+ def get_actions(+ cls,+ simulation_id: str,+ limit: int = 100,+ offset: int = 0,+ platform: Optional[str] = None,+ agent_id: Optional[int] = None,+ round_num: Optional[int] = None+ ) -> List[AgentAction]:+ """+ 获取动作历史(带分页)++ Args:+ simulation_id: 模拟ID+ limit: 返回数量限制+ offset: 偏移量+ platform: 过滤平台+ agent_id: 过滤Agent+ round_num: 过滤轮次++ Returns:+ 动作列表+ """+ actions = cls.get_all_actions(+ simulation_id=simulation_id,+ platform=platform,+ agent_id=agent_id,+ round_num=round_num+ )# 分页return actions[offset:offset + limit]@@ -854,6 +948,81 @@ class SimulationRunner:return result+ @classmethod+ def cleanup_simulation_logs(cls, simulation_id: str) -> Dict[str, Any]:+ """+ 清理模拟的运行日志(用于强制重新开始模拟)++ 会删除以下文件:+ - run_state.json+ - twitter/actions.jsonl+ - reddit/actions.jsonl+ - simulation.log+ - stdout.log / stderr.log++ 注意:不会删除配置文件(simulation_config.json)和 profile 文件++ Args:+ simulation_id: 模拟ID++ Returns:+ 清理结果信息+ """+ import shutil++ sim_dir = os.path.join(cls.RUN_STATE_DIR, simulation_id)++ if not os.path.exists(sim_dir):+ return {"success": True, "message": "模拟目录不存在,无需清理"}++ cleaned_files = []+ errors = []++ # 要删除的文件列表+ files_to_delete = [+ "run_state.json",+ "simulation.log",+ "stdout.log",+ "stderr.log",+ ]++ # 要删除的目录列表(包含动作日志)+ dirs_to_clean = ["twitter", "reddit"]++ # 删除文件+ for filename in files_to_delete:+ file_path = os.path.join(sim_dir, filename)+ if os.path.exists(file_path):+ try:+ os.remove(file_path)+ cleaned_files.append(filename)+ except Exception as e:+ errors.append(f"删除 {filename} 失败: {str(e)}")++ # 清理平台目录中的动作日志+ for dir_name in dirs_to_clean:+ dir_path = os.path.join(sim_dir, dir_name)+ if os.path.exists(dir_path):+ actions_file = os.path.join(dir_path, "actions.jsonl")+ if os.path.exists(actions_file):+ try:+ os.remove(actions_file)+ cleaned_files.append(f"{dir_name}/actions.jsonl")+ except Exception as e:+ errors.append(f"删除 {dir_name}/actions.jsonl 失败: {str(e)}")++ # 清理内存中的运行状态+ if simulation_id in cls._run_states:+ del cls._run_states[simulation_id]++ logger.info(f"清理模拟日志完成: {simulation_id}, 删除文件: {cleaned_files}")++ return {+ "success": len(errors) == 0,+ "cleaned_files": cleaned_files,+ "errors": errors if errors else None+ }+# 防止重复清理的标志_cleanup_done = Falsediff --git a/frontend/src/api/simulation.js b/frontend/src/api/simulation.jsindex f3c85c1b..907911a4 100644--- a/frontend/src/api/simulation.js+++ b/frontend/src/api/simulation.js@@ -108,3 +108,47 @@ export const getRunStatusDetail = (simulationId) => {return service.get(`/api/simulation/${simulationId}/run-status/detail`)}+/**+ * 获取模拟中的帖子+ * @param {string} simulationId+ * @param {string} platform - 'reddit' | 'twitter'+ * @param {number} limit - 返回数量+ * @param {number} offset - 偏移量+ */+export const getSimulationPosts = (simulationId, platform = 'reddit', limit = 50, offset = 0) => {+ return service.get(`/api/simulation/${simulationId}/posts`, {+ params: { platform, limit, offset }+ })+}++/**+ * 获取模拟时间线(按轮次汇总)+ * @param {string} simulationId+ * @param {number} startRound - 起始轮次+ * @param {number} endRound - 结束轮次+ */+export const getSimulationTimeline = (simulationId, startRound = 0, endRound = null) => {+ const params = { start_round: startRound }+ if (endRound !== null) {+ params.end_round = endRound+ }+ return service.get(`/api/simulation/${simulationId}/timeline`, { params })+}++/**+ * 获取Agent统计信息+ * @param {string} simulationId+ */+export const getAgentStats = (simulationId) => {+ return service.get(`/api/simulation/${simulationId}/agent-stats`)+}++/**+ * 获取模拟动作历史+ * @param {string} simulationId+ * @param {Object} params - { limit, offset, platform, agent_id, round_num }+ */+export const getSimulationActions = (simulationId, params = {}) => {+ return service.get(`/api/simulation/${simulationId}/actions`, { params })+}+diff --git a/frontend/src/components/Step3Simulation.vue b/frontend/src/components/Step3Simulation.vuenew file mode 100644index 00000000..40208092--- /dev/null+++ b/frontend/src/components/Step3Simulation.vue@@ -0,0 +1,1312 @@+<template>+ <div class="simulation-panel">+ <div class="scroll-container">+ <!-- Step 01: 启动模拟 -->+ <div class="step-card" :class="{ 'active': phase === 0, 'completed': phase > 0 }">+ <div class="card-header">+ <div class="step-info">+ <span class="step-num">01</span>+ <span class="step-title">启动模拟引擎</span>+ </div>+ <div class="step-status">+ <span v-if="phase > 0" class="badge success">已启动</span>+ <span v-else-if="isStarting" class="badge processing">启动中</span>+ <span v-else class="badge pending">等待</span>+ </div>+ </div>++ <div class="card-content">+ <p class="api-note">POST /api/simulation/start</p>+ <p class="description">+ 启动双平台并行模拟引擎,Twitter与Reddit世界同步推演+ </p>++ <div v-if="phase === 0 && !isStarting" class="start-config">+ <div class="config-row">+ <span class="config-label">模拟ID</span>+ <span class="config-value mono">{{ simulationId }}</span>+ </div>+ <div class="config-row">+ <span class="config-label">模拟轮数</span>+ <span class="config-value">{{ maxRounds || '自动配置' }} 轮</span>+ </div>+ <div class="config-row">+ <span class="config-label">运行平台</span>+ <span class="config-value">Twitter + Reddit (并行)</span>+ </div>+ </div>++ <div v-if="isStarting" class="starting-indicator">+ <div class="spinner-sm"></div>+ <span>正在初始化模拟引擎...</span>+ </div>++ <div v-if="startError" class="error-box">+ <span class="error-icon">✗</span>+ <span class="error-text">{{ startError }}</span>+ <button class="retry-btn" @click="doStartSimulation">重试</button>+ </div>+ </div>+ </div>++ <!-- Step 02: 模拟进度 -->+ <div class="step-card" :class="{ 'active': phase === 1, 'completed': phase > 1 }">+ <div class="card-header">+ <div class="step-info">+ <span class="step-num">02</span>+ <span class="step-title">双世界并行推演</span>+ </div>+ <div class="step-status">+ <span v-if="phase > 1" class="badge success">已完成</span>+ <span v-else-if="phase === 1" class="badge processing">{{ progressPercent }}%</span>+ <span v-else class="badge pending">等待</span>+ </div>+ </div>++ <div class="card-content">+ <p class="api-note">GET /api/simulation/{{ simulationId }}/run-status</p>+ <p class="description">+ 实时监控模拟进度,观察Agent在双平台的社交行为+ </p>++ <!-- 进度条 -->+ <div v-if="phase >= 1" class="progress-section">+ <div class="progress-bar-container">+ <div class="progress-bar" :style="{ width: progressPercent + '%' }"></div>+ </div>+ <div class="progress-stats">+ <div class="stat-item">+ <span class="stat-label">当前轮次</span>+ <span class="stat-value">{{ runStatus.current_round || 0 }} / {{ runStatus.total_rounds || maxRounds || '-' }}</span>+ </div>+ <div class="stat-item">+ <span class="stat-label">模拟时间</span>+ <span class="stat-value">{{ runStatus.simulated_hours || 0 }}h / {{ runStatus.total_simulation_hours || '-' }}h</span>+ </div>+ </div>+ </div>++ <!-- 平台状态 -->+ <div v-if="phase >= 1" class="platforms-status">+ <div class="platform-item" :class="{ 'running': runStatus.twitter_running }">+ <div class="platform-header">+ <span class="platform-icon">𝕏</span>+ <span class="platform-name">Twitter / 广场</span>+ <span class="platform-badge" :class="runStatus.twitter_running ? 'active' : 'idle'">+ {{ runStatus.twitter_running ? '运行中' : '等待' }}+ </span>+ </div>+ <div class="platform-stats">+ <span class="action-count">+ <span class="count-num">{{ runStatus.twitter_actions_count || 0 }}</span> 动作+ </span>+ </div>+ </div>+ <div class="platform-item" :class="{ 'running': runStatus.reddit_running }">+ <div class="platform-header">+ <span class="platform-icon">📮</span>+ <span class="platform-name">Reddit / 社区</span>+ <span class="platform-badge" :class="runStatus.reddit_running ? 'active' : 'idle'">+ {{ runStatus.reddit_running ? '运行中' : '等待' }}+ </span>+ </div>+ <div class="platform-stats">+ <span class="action-count">+ <span class="count-num">{{ runStatus.reddit_actions_count || 0 }}</span> 动作+ </span>+ </div>+ </div>+ </div>++ <!-- 统计卡片 -->+ <div v-if="phase >= 1" class="stats-grid">+ <div class="stat-card">+ <span class="stat-value">{{ runStatus.total_actions_count || 0 }}</span>+ <span class="stat-label">总动作数</span>+ </div>+ <div class="stat-card">+ <span class="stat-value">{{ actionStats.posts }}</span>+ <span class="stat-label">帖子数</span>+ </div>+ <div class="stat-card">+ <span class="stat-value">{{ actionStats.comments }}</span>+ <span class="stat-label">评论数</span>+ </div>+ <div class="stat-card">+ <span class="stat-value">{{ actionStats.likes }}</span>+ <span class="stat-label">点赞数</span>+ </div>+ </div>+ </div>+ </div>++ <!-- Step 03: 实时动态 -->+ <div class="step-card" :class="{ 'active': phase >= 1 }">+ <div class="card-header">+ <div class="step-info">+ <span class="step-num">03</span>+ <span class="step-title">实时动态流</span>+ </div>+ <div class="step-status">+ <span v-if="recentActions.length > 0" class="badge accent">{{ recentActions.length }} 条</span>+ <span v-else class="badge pending">等待</span>+ </div>+ </div>++ <div class="card-content">+ <p class="api-note">GET /api/simulation/{{ simulationId }}/run-status/detail</p>+ <p class="description">+ 观察Agent们在模拟世界中的实时行为:发帖、评论、点赞、转发...+ </p>++ <!-- 平台筛选 -->+ <div v-if="recentActions.length > 0" class="filter-bar">+ <button+ class="filter-btn"+ :class="{ active: actionFilter === 'all' }"+ @click="actionFilter = 'all'"+ >+ 全部+ </button>+ <button+ class="filter-btn"+ :class="{ active: actionFilter === 'twitter' }"+ @click="actionFilter = 'twitter'"+ >+ 𝕏 Twitter+ </button>+ <button+ class="filter-btn"+ :class="{ active: actionFilter === 'reddit' }"+ @click="actionFilter = 'reddit'"+ >+ </button>+ </div>++ <!-- 动作流 -->+ <div v-if="filteredActions.length > 0" class="actions-stream">+ <TransitionGroup name="action-list" tag="div" class="actions-list">+ <div+ v-for="action in filteredActions"+ :key="action.id || `${action.timestamp}-${action.agent_id}-${Math.random()}`"+ class="action-item"+ :class="'action-' + (action.action_type || 'unknown').toLowerCase()"+ >+ <div class="action-header">+ <span class="action-platform" :class="action.platform">+ {{ action.platform === 'twitter' ? '𝕏' : '📮' }}+ </span>+ <span class="action-agent">+ <span class="agent-name">{{ action.agent_name || `Agent ${action.agent_id}` }}</span>+ </span>+ <span class="action-type-badge" :class="getActionTypeClass(action.action_type)">+ {{ getActionTypeLabel(action.action_type) }}+ </span>+ <span class="action-round">R{{ action.round_num }}</span>+ </div>+ <div v-if="action.action_args?.content" class="action-content">+ {{ truncateContent(action.action_args.content) }}+ </div>+ <div class="action-footer">+ <span class="action-time">{{ formatActionTime(action.timestamp) }}</span>+ <span v-if="action.action_args?.target_post_id" class="action-target">+ 回复 #{{ action.action_args.target_post_id }}+ </span>+ </div>+ </div>+ </TransitionGroup>+ </div>++ <div v-else-if="phase >= 1" class="empty-actions">+ <div class="spinner-sm"></div>+ <span>等待Agent行动...</span>+ </div>+ </div>+ </div>++ <!-- Step 04: 模拟完成 -->+ <div class="step-card" :class="{ 'active': phase === 2 }">+ <div class="card-header">+ <div class="step-info">+ <span class="step-num">04</span>+ <span class="step-title">模拟完成</span>+ </div>+ <div class="step-status">+ <span v-if="phase >= 2" class="badge success">完成</span>+ <span v-else class="badge pending">等待</span>+ </div>+ </div>++ <div class="card-content">+ <p class="api-note">POST /api/simulation/stop</p>+ <p class="description">+ 模拟结束后,可进入报告生成阶段,深度分析模拟结果+ </p>++ <!-- 完成统计 -->+ <div v-if="phase >= 2" class="completion-stats">+ <div class="completion-summary">+ <div class="summary-icon">✓</div>+ <div class="summary-content">+ <span class="summary-title">模拟已完成</span>+ <span class="summary-desc">双平台并行推演结束,所有Agent动作已记录</span>+ </div>+ </div>+ <div class="completion-grid">+ <div class="completion-item">+ <span class="completion-value">{{ runStatus.current_round || 0 }}</span>+ <span class="completion-label">完成轮次</span>+ </div>+ <div class="completion-item">+ <span class="completion-value">{{ runStatus.simulated_hours || 0 }}h</span>+ <span class="completion-label">模拟时长</span>+ </div>+ <div class="completion-item">+ <span class="completion-value">{{ runStatus.total_actions_count || 0 }}</span>+ <span class="completion-label">总动作数</span>+ </div>+ </div>+ </div>++ <div class="action-group" :class="{ 'dual': phase === 1 }">+ <button+ v-if="phase === 1"+ class="action-btn secondary"+ @click="handleStopSimulation"+ :disabled="isStopping"+ >+ <span v-if="isStopping" class="spinner-sm"></span>+ {{ isStopping ? '停止中...' : '⏹ 停止模拟' }}+ </button>+ <button+ class="action-btn primary"+ :disabled="phase < 2"+ @click="handleNextStep"+ >+ 进入报告生成 ➝+ </button>+ </div>+ </div>+ </div>+ </div>++ <!-- Bottom Info / Logs -->+ <div class="system-logs">+ <div class="log-header">+ <span class="log-title">SIMULATION MONITOR</span>+ <span class="log-id">{{ simulationId || 'NO_SIMULATION' }}</span>+ </div>+ <div class="log-content" ref="logContent">+ <div class="log-line" v-for="(log, idx) in systemLogs" :key="idx">+ <span class="log-time">{{ log.time }}</span>+ <span class="log-msg">{{ log.msg }}</span>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup>+import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'+import {+ startSimulation,+ stopSimulation,+ getRunStatus,+ getRunStatusDetail+} from '../api/simulation'++const props = defineProps({+ simulationId: String,+ maxRounds: Number, // 从Step2传入的最大轮数+ projectData: Object,+ graphData: Object,+ systemLogs: Array+})++const emit = defineEmits(['go-back', 'next-step', 'add-log', 'update-status'])++// State+const phase = ref(0) // 0: 未开始, 1: 运行中, 2: 已完成+const isStarting = ref(false)+const isStopping = ref(false)+const startError = ref(null)+const runStatus = ref({})+const recentActions = ref([])+const actionFilter = ref('all')++// 动作统计+const actionStats = ref({+ posts: 0,+ comments: 0,+ likes: 0,+ reposts: 0+})++// Polling timers+let statusTimer = null+let detailTimer = null++// Computed+const progressPercent = computed(() => {+ if (!runStatus.value.total_rounds) return 0+ return Math.round((runStatus.value.current_round / runStatus.value.total_rounds) * 100)+})++const filteredActions = computed(() => {+ if (actionFilter.value === 'all') {+ return recentActions.value+ }+ return recentActions.value.filter(a => a.platform === actionFilter.value)+})++// Methods+const addLog = (msg) => {+ emit('add-log', msg)+}++// 启动模拟+const doStartSimulation = async () => {+ if (!props.simulationId) {+ addLog('错误:缺少 simulationId')+ return+ }++ isStarting.value = true+ startError.value = null+ addLog('正在启动双平台并行模拟...')+ emit('update-status', 'processing')++ try {+ const params = {+ simulation_id: props.simulationId,+ platform: 'parallel',+ force: true // 强制重新开始,如果已有模拟会自动停止并清理日志+ }++ // 如果有自定义轮数+ if (props.maxRounds) {+ params.max_rounds = props.maxRounds+ addLog(`设置最大模拟轮数: ${props.maxRounds}`)+ }++ const res = await startSimulation(params)++ if (res.success && res.data) {+ if (res.data.force_restarted) {+ addLog('✓ 已清理旧的模拟日志,重新开始模拟')+ }+ addLog('✓ 模拟引擎启动成功')+ addLog(` ├─ PID: ${res.data.process_pid || '-'}`)+ addLog(` ├─ Twitter: ${res.data.twitter_running ? '运行中' : '等待'}`)+ addLog(` └─ Reddit: ${res.data.reddit_running ? '运行中' : '等待'}`)++ phase.value = 1+ runStatus.value = res.data++ // 开始轮询状态+ startStatusPolling()+ startDetailPolling()+ } else {+ startError.value = res.error || '启动失败'+ addLog(`✗ 启动失败: ${res.error || '未知错误'}`)+ emit('update-status', 'error')+ }+ } catch (err) {+ startError.value = err.message+ addLog(`✗ 启动异常: ${err.message}`)+ emit('update-status', 'error')+ } finally {+ isStarting.value = false+ }+}++// 停止模拟+const handleStopSimulation = async () => {+ if (!props.simulationId) return++ isStopping.value = true+ addLog('正在停止模拟...')++ try {+ const res = await stopSimulation({ simulation_id: props.simulationId })++ if (res.success) {+ addLog('✓ 模拟已停止')+ phase.value = 2+ stopPolling()+ emit('update-status', 'completed')+ } else {+ addLog(`停止失败: ${res.error || '未知错误'}`)+ }+ } catch (err) {+ addLog(`停止异常: ${err.message}`)+ } finally {+ isStopping.value = false+ }+}++// 轮询状态+const startStatusPolling = () => {+ statusTimer = setInterval(fetchRunStatus, 2000)+}++const startDetailPolling = () => {+ detailTimer = setInterval(fetchRunStatusDetail, 3000)+}++const stopPolling = () => {+ if (statusTimer) {+ clearInterval(statusTimer)+ statusTimer = null+ }+ if (detailTimer) {+ clearInterval(detailTimer)+ detailTimer = null+ }+}++const fetchRunStatus = async () => {+ if (!props.simulationId) return++ try {+ const res = await getRunStatus(props.simulationId)++ if (res.success && res.data) {+ const data = res.data+ const prevRound = runStatus.value.current_round || 0++ runStatus.value = data++ // 检查是否有新轮次+ if (data.current_round > prevRound) {+ addLog(`轮次 ${data.current_round}/${data.total_rounds} - 动作数: ${data.total_actions_count}`)+ }++ // 检查是否完成+ if (data.runner_status === 'completed' || data.runner_status === 'stopped') {+ addLog('✓ 模拟已完成')+ phase.value = 2+ stopPolling()+ emit('update-status', 'completed')+ }+ }+ } catch (err) {+ console.warn('获取运行状态失败:', err)+ }+}++const fetchRunStatusDetail = async () => {+ if (!props.simulationId) return++ try {+ const res = await getRunStatusDetail(props.simulationId)++ if (res.success && res.data?.recent_actions) {+ // 更新最近动作,保留最新30条+ const newActions = res.data.recent_actions.slice(0, 30)+ recentActions.value = newActions++ // 统计动作类型+ updateActionStats(newActions)+ }+ } catch (err) {+ console.warn('获取详细状态失败:', err)+ }+}++// 统计动作类型+const updateActionStats = (actions) => {+ const stats = { posts: 0, comments: 0, likes: 0, reposts: 0 }+ actions.forEach(a => {+ const type = a.action_type?.toUpperCase()+ if (type === 'CREATE_POST') stats.posts+++ else if (type === 'CREATE_COMMENT') stats.comments+++ else if (type === 'LIKE_POST' || type === 'LIKE_COMMENT') stats.likes+++ else if (type === 'REPOST') stats.reposts+++ })+ actionStats.value = stats+}++// 工具函数+const getActionTypeLabel = (type) => {+ const labels = {+ 'CREATE_POST': '发帖',+ 'REPOST': '转发',+ 'LIKE_POST': '点赞',+ 'CREATE_COMMENT': '评论',+ 'LIKE_COMMENT': '赞评',+ 'DO_NOTHING': '观望',+ 'FOLLOW': '关注',+ 'SEARCH_POSTS': '搜索',+ 'SEARCH_USER': '找人'+ }+ return labels[type] || type || '未知'+}++const getActionTypeClass = (type) => {+ const classes = {+ 'CREATE_POST': 'post',+ 'REPOST': 'repost',+ 'LIKE_POST': 'like',+ 'CREATE_COMMENT': 'comment',+ 'LIKE_COMMENT': 'like',+ 'DO_NOTHING': 'nothing',+ 'FOLLOW': 'follow',+ 'SEARCH_POSTS': 'search',+ 'SEARCH_USER': 'search'+ }+ return classes[type] || 'default'+}++const truncateContent = (content) => {+ if (!content) return ''+ if (content.length > 120) {+ return content.substring(0, 120) + '...'+ }+ return content+}++const formatActionTime = (timestamp) => {+ if (!timestamp) return '--:--'+ try {+ const d = new Date(timestamp)+ return d.toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' })+ } catch {+ return timestamp+ }+}++const handleNextStep = () => {+ addLog('进入 Step 4: 报告生成')+ emit('next-step')+}++// Scroll log to bottom+const logContent = ref(null)+watch(() => props.systemLogs?.length, () => {+ nextTick(() => {+ if (logContent.value) {+ logContent.value.scrollTop = logContent.value.scrollHeight+ }+ })+})++onMounted(() => {+ addLog('Step3 模拟运行初始化')+ // 自动启动模拟+ if (props.simulationId) {+ doStartSimulation()+ }+})++onUnmounted(() => {+ stopPolling()+})+</script>++<style scoped>+.simulation-panel {+ height: 100%;+ display: flex;+ flex-direction: column;+ background: #FAFAFA;+ font-family: 'Space Grotesk', -apple-system, BlinkMacSystemFont, sans-serif;+}++.scroll-container {+ flex: 1;+ overflow-y: auto;+ padding: 24px;+ display: flex;+ flex-direction: column;+ gap: 20px;+}++/* Step Card */+.step-card {+ background: #FFF;+ border-radius: 8px;+ padding: 20px;+ box-shadow: 0 2px 8px rgba(0,0,0,0.04);+ border: 1px solid #EAEAEA;+ transition: all 0.3s ease;+ position: relative;+}++.step-card.active {+ border-color: #FF5722;+ box-shadow: 0 4px 12px rgba(255, 87, 34, 0.08);+}++.step-card.completed {+ border-color: #4CAF50;+}++.card-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 16px;+}++.step-info {+ display: flex;+ align-items: center;+ gap: 12px;+}++.step-num {+ font-family: 'JetBrains Mono', monospace;+ font-size: 20px;+ font-weight: 700;+ color: #E0E0E0;+}++.step-card.active .step-num,+.step-card.completed .step-num {+ color: #000;+}++.step-title {+ font-weight: 600;+ font-size: 14px;+ letter-spacing: 0.5px;+}++.badge {+ font-size: 10px;+ padding: 4px 8px;+ border-radius: 4px;+ font-weight: 600;+ text-transform: uppercase;+}++.badge.success { background: #E8F5E9; color: #2E7D32; }+.badge.processing { background: #FF5722; color: #FFF; }+.badge.pending { background: #F5F5F5; color: #999; }+.badge.accent { background: #E3F2FD; color: #1565C0; }++.api-note {+ font-family: 'JetBrains Mono', monospace;+ font-size: 10px;+ color: #999;+ margin-bottom: 8px;+}++.description {+ font-size: 12px;+ color: #666;+ line-height: 1.5;+ margin-bottom: 16px;+}++/* Start Config */+.start-config {+ background: #F9F9F9;+ border-radius: 6px;+ padding: 16px;+ margin-bottom: 16px;+}++.config-row {+ display: flex;+ justify-content: space-between;+ padding: 8px 0;+ border-bottom: 1px dashed #E5E5E5;+}++.config-row:last-child {+ border-bottom: none;+}++.config-label {+ font-size: 12px;+ color: #666;+}++.config-value {+ font-size: 12px;+ font-weight: 600;+ color: #333;+}++.config-value.mono {+ font-family: 'JetBrains Mono', monospace;+}++.starting-indicator {+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 12px;+ color: #FF5722;+ margin-bottom: 12px;+}++.error-box {+ display: flex;+ align-items: center;+ gap: 8px;+ background: #FFEBEE;+ padding: 12px;+ border-radius: 6px;+ margin-top: 12px;+}++.error-icon {+ color: #E53935;+ font-weight: 700;+}++.error-text {+ font-size: 12px;+ color: #C62828;+ flex: 1;+}++.retry-btn {+ background: #E53935;+ color: #FFF;+ border: none;+ padding: 6px 12px;+ border-radius: 4px;+ font-size: 11px;+ font-weight: 600;+ cursor: pointer;+ transition: opacity 0.2s;+}++.retry-btn:hover {+ opacity: 0.8;+}++/* Progress Section */+.progress-section {+ margin-bottom: 16px;+}++.progress-bar-container {+ height: 8px;+ background: #E5E5E5;+ border-radius: 4px;+ overflow: hidden;+ margin-bottom: 12px;+}++.progress-bar {+ height: 100%;+ background: linear-gradient(90deg, #FF5722, #FF9800);+ border-radius: 4px;+ transition: width 0.5s ease;+}++.progress-stats {+ display: flex;+ justify-content: space-between;+}++.stat-item {+ display: flex;+ flex-direction: column;+ gap: 2px;+}++.stat-item .stat-label {+ font-size: 10px;+ color: #999;+ text-transform: uppercase;+}++.stat-item .stat-value {+ font-family: 'JetBrains Mono', monospace;+ font-size: 13px;+ font-weight: 600;+ color: #333;+}++/* Platforms Status */+.platforms-status {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 12px;+ margin-bottom: 16px;+}++.platform-item {+ background: #F9F9F9;+ border: 1px solid #E5E5E5;+ border-radius: 8px;+ padding: 14px;+ transition: all 0.3s ease;+}++.platform-item.running {+ border-color: #FF5722;+ background: #FFF;+}++.platform-header {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 8px;+}++.platform-icon {+ font-size: 16px;+}++.platform-name {+ font-size: 13px;+ font-weight: 600;+ flex: 1;+}++.platform-badge {+ font-size: 9px;+ padding: 2px 6px;+ border-radius: 3px;+ font-weight: 600;+ text-transform: uppercase;+}++.platform-badge.active {+ background: #FF5722;+ color: #FFF;+}++.platform-badge.idle {+ background: #E5E5E5;+ color: #666;+}++.platform-stats {+ font-family: 'JetBrains Mono', monospace;+ font-size: 11px;+ color: #666;+}++.count-num {+ font-size: 16px;+ font-weight: 700;+ color: #333;+}++/* Stats Grid */+.stats-grid {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 12px;+ background: #F9F9F9;+ padding: 16px;+ border-radius: 6px;+}++.stat-card {+ text-align: center;+}++.stat-card .stat-value {+ display: block;+ font-size: 20px;+ font-weight: 700;+ color: #000;+ font-family: 'JetBrains Mono', monospace;+}++.stat-card .stat-label {+ font-size: 9px;+ color: #999;+ text-transform: uppercase;+ margin-top: 4px;+ display: block;+}++/* Filter Bar */+.filter-bar {+ display: flex;+ gap: 8px;+ margin-bottom: 12px;+}++.filter-btn {+ border: 1px solid #E5E5E5;+ background: #FFF;+ padding: 6px 12px;+ border-radius: 16px;+ font-size: 11px;+ font-weight: 500;+ color: #666;+ cursor: pointer;+ transition: all 0.2s;+}++.filter-btn:hover {+ border-color: #999;+}++.filter-btn.active {+ background: #000;+ border-color: #000;+ color: #FFF;+}++/* Actions Stream */+.actions-stream {+ max-height: 400px;+ overflow-y: auto;+ border: 1px solid #E5E5E5;+ border-radius: 8px;+ background: #FAFAFA;+}++.actions-stream::-webkit-scrollbar {+ width: 6px;+}++.actions-stream::-webkit-scrollbar-thumb {+ background: #DDD;+ border-radius: 3px;+}++.actions-list {+ padding: 8px;+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.action-item {+ background: #FFF;+ border: 1px solid #E5E5E5;+ border-radius: 6px;+ padding: 12px;+ transition: all 0.3s ease;+}++.action-item:hover {+ border-color: #CCC;+}++.action-item.action-create_post {+ border-left: 3px solid #1DA1F2;+}++.action-item.action-repost {+ border-left: 3px solid #17BF63;+}++.action-item.action-like_post,+.action-item.action-like_comment {+ border-left: 3px solid #E0245E;+}++.action-item.action-create_comment {+ border-left: 3px solid #794BC4;+}++.action-item.action-do_nothing {+ border-left: 3px solid #AAB8C2;+ opacity: 0.7;+}++.action-header {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 6px;+}++.action-platform {+ font-size: 14px;+}++.action-platform.twitter {+ color: #1DA1F2;+}++.action-platform.reddit {+ color: #FF4500;+}++.action-agent {+ flex: 1;+}++.agent-name {+ font-size: 12px;+ font-weight: 600;+ color: #333;+}++.action-type-badge {+ font-size: 9px;+ padding: 2px 6px;+ border-radius: 3px;+ font-weight: 600;+ text-transform: uppercase;+}++.action-type-badge.post { background: #E3F2FD; color: #1565C0; }+.action-type-badge.repost { background: #E8F5E9; color: #2E7D32; }+.action-type-badge.like { background: #FCE4EC; color: #C2185B; }+.action-type-badge.comment { background: #F3E5F5; color: #7B1FA2; }+.action-type-badge.nothing { background: #F5F5F5; color: #757575; }+.action-type-badge.follow { background: #E0F7FA; color: #00838F; }+.action-type-badge.search { background: #FFF3E0; color: #EF6C00; }+.action-type-badge.default { background: #ECEFF1; color: #546E7A; }++.action-round {+ font-family: 'JetBrains Mono', monospace;+ font-size: 10px;+ color: #999;+}++.action-content {+ font-size: 12px;+ color: #555;+ line-height: 1.5;+ padding: 8px;+ background: #F9F9F9;+ border-radius: 4px;+ margin-bottom: 6px;+}++.action-footer {+ display: flex;+ justify-content: space-between;+ align-items: center;+}++.action-time {+ font-family: 'JetBrains Mono', monospace;+ font-size: 10px;+ color: #AAA;+}++.action-target {+ font-size: 10px;+ color: #999;+}++.empty-actions {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 10px;+ padding: 40px;+ color: #999;+ font-size: 12px;+}++/* Action List Animation */+.action-list-enter-active {+ transition: all 0.4s ease;+}++.action-list-leave-active {+ transition: all 0.3s ease;+}++.action-list-enter-from {+ opacity: 0;+ transform: translateY(-20px);+}++.action-list-leave-to {+ opacity: 0;+ transform: translateX(20px);+}++/* Completion Stats */+.completion-stats {+ margin-bottom: 16px;+}++.completion-summary {+ display: flex;+ align-items: center;+ gap: 16px;+ padding: 16px;+ background: linear-gradient(135deg, #E8F5E9, #C8E6C9);+ border-radius: 8px;+ margin-bottom: 16px;+}++.summary-icon {+ width: 48px;+ height: 48px;+ background: #4CAF50;+ color: #FFF;+ border-radius: 50%;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 24px;+ font-weight: 700;+}++.summary-content {+ flex: 1;+}++.summary-title {+ display: block;+ font-size: 16px;+ font-weight: 700;+ color: #2E7D32;+ margin-bottom: 4px;+}++.summary-desc {+ font-size: 12px;+ color: #388E3C;+}++.completion-grid {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 16px;+}++.completion-item {+ text-align: center;+ padding: 16px;+ background: #F9F9F9;+ border-radius: 8px;+}++.completion-value {+ display: block;+ font-size: 24px;+ font-weight: 700;+ color: #333;+ font-family: 'JetBrains Mono', monospace;+}++.completion-label {+ font-size: 11px;+ color: #666;+ text-transform: uppercase;+ margin-top: 4px;+}++/* Action Buttons */+.action-group {+ display: flex;+ gap: 12px;+ margin-top: 16px;+}++.action-group.dual {+ display: grid;+ grid-template-columns: 1fr 1fr;+}++.action-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ padding: 12px 24px;+ font-size: 13px;+ font-weight: 600;+ border: none;+ border-radius: 6px;+ cursor: pointer;+ transition: all 0.2s ease;+}++.action-btn.primary {+ background: #000;+ color: #FFF;+}++.action-btn.primary:hover:not(:disabled) {+ opacity: 0.8;+}++.action-btn.secondary {+ background: #F5F5F5;+ color: #333;+}++.action-btn.secondary:hover:not(:disabled) {+ background: #E5E5E5;+}++.action-btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++/* System Logs */+.system-logs {+ background: #000;+ color: #DDD;+ padding: 16px;+ font-family: 'JetBrains Mono', monospace;+ border-top: 1px solid #222;+ flex-shrink: 0;+}++.log-header {+ display: flex;+ justify-content: space-between;+ border-bottom: 1px solid #333;+ padding-bottom: 8px;+ margin-bottom: 8px;+ font-size: 10px;+ color: #888;+}++.log-content {+ display: flex;+ flex-direction: column;+ gap: 4px;+ height: 80px;+ overflow-y: auto;+ padding-right: 4px;+}++.log-content::-webkit-scrollbar {+ width: 4px;+}++.log-content::-webkit-scrollbar-thumb {+ background: #333;+ border-radius: 2px;+}++.log-line {+ font-size: 11px;+ display: flex;+ gap: 12px;+ line-height: 1.5;+}++.log-time {+ color: #666;+ min-width: 75px;+}++.log-msg {+ color: #CCC;+ word-break: break-all;+}++/* Spinner */+.spinner-sm {+ width: 14px;+ height: 14px;+ border: 2px solid #FFCCBC;+ border-top-color: #FF5722;+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+}++@keyframes spin {+ to { transform: rotate(360deg); }+}+</style>diff --git a/frontend/src/router/index.js b/frontend/src/router/index.jsindex f8a7a02c..beabb645 100644--- a/frontend/src/router/index.js+++ b/frontend/src/router/index.js@@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router'import Home from '../views/Home.vue'import Process from '../views/MainView.vue'import SimulationView from '../views/SimulationView.vue'+import SimulationRunView from '../views/SimulationRunView.vue'const routes = [{@@ -20,6 +21,12 @@ const routes = [name: 'Simulation',component: SimulationView,props: true+ },+ {+ path: '/simulation/:simulationId/start',+ name: 'SimulationRun',+ component: SimulationRunView,+ props: true}]diff --git a/frontend/src/views/SimulationRunView.vue b/frontend/src/views/SimulationRunView.vuenew file mode 100644index 00000000..d22611d2--- /dev/null+++ b/frontend/src/views/SimulationRunView.vue@@ -0,0 +1,343 @@+<template>+ <div class="main-view">+ <!-- Header -->+ <header class="app-header">+ <div class="header-left">+ <div class="brand" @click="router.push('/')">MIROFISH</div>+ </div>++ <div class="header-center">+ <div class="view-switcher">+ <button+ v-for="mode in ['graph', 'split', 'workbench']"+ :key="mode"+ class="switch-btn"+ :class="{ active: viewMode === mode }"+ @click="viewMode = mode"+ >+ {{ { graph: '图谱', split: '双栏', workbench: '工作台' }[mode] }}+ </button>+ </div>+ </div>++ <div class="header-right">+ <div class="workflow-step">+ <span class="step-num">Step 3/5</span>+ <span class="step-name">开始模拟</span>+ </div>+ <div class="step-divider"></div>+ <span class="status-indicator" :class="statusClass">+ <span class="dot"></span>+ {{ statusText }}+ </span>+ </div>+ </header>++ <!-- Main Content Area -->+ <main class="content-area">+ <!-- Left Panel: Graph -->+ <div class="panel-wrapper left" :style="leftPanelStyle">+ <GraphPanel+ :graphData="graphData"+ :loading="graphLoading"+ :currentPhase="3"+ @refresh="refreshGraph"+ @toggle-maximize="toggleMaximize('graph')"+ />+ </div>++ <!-- Right Panel: Step3 开始模拟 -->+ <div class="panel-wrapper right" :style="rightPanelStyle">+ <Step3Simulation+ :simulationId="currentSimulationId"+ :maxRounds="maxRounds"+ :projectData="projectData"+ :graphData="graphData"+ :systemLogs="systemLogs"+ @go-back="handleGoBack"+ @next-step="handleNextStep"+ @add-log="addLog"+ @update-status="updateStatus"+ />+ </div>+ </main>+ </div>+</template>++<script setup>+import { ref, computed, onMounted } from 'vue'+import { useRoute, useRouter } from 'vue-router'+import GraphPanel from '../components/GraphPanel.vue'+import Step3Simulation from '../components/Step3Simulation.vue'+import { getProject, getGraphData } from '../api/graph'+import { getSimulation } from '../api/simulation'++const route = useRoute()+const router = useRouter()++// Props+const props = defineProps({+ simulationId: String+})++// Layout State+const viewMode = ref('split')++// Data State+const currentSimulationId = ref(route.params.simulationId)+// 直接在初始化时从 query 参数获取 maxRounds,确保子组件能立即获取到值+const maxRounds = ref(route.query.maxRounds ? parseInt(route.query.maxRounds) : null)+const projectData = ref(null)+const graphData = ref(null)+const graphLoading = ref(false)+const systemLogs = ref([])+const currentStatus = ref('processing') // processing | completed | error++// --- Computed Layout Styles ---+const leftPanelStyle = computed(() => {+ if (viewMode.value === 'graph') return { width: '100%', opacity: 1, transform: 'translateX(0)' }+ if (viewMode.value === 'workbench') return { width: '0%', opacity: 0, transform: 'translateX(-20px)' }+ return { width: '50%', opacity: 1, transform: 'translateX(0)' }+})++const rightPanelStyle = computed(() => {+ if (viewMode.value === 'workbench') return { width: '100%', opacity: 1, transform: 'translateX(0)' }+ if (viewMode.value === 'graph') return { width: '0%', opacity: 0, transform: 'translateX(20px)' }+ return { width: '50%', opacity: 1, transform: 'translateX(0)' }+})++// --- Status Computed ---+const statusClass = computed(() => {+ return currentStatus.value+})++const statusText = computed(() => {+ if (currentStatus.value === 'error') return 'Error'+ if (currentStatus.value === 'completed') return 'Completed'+ return 'Running'+})++// --- Helpers ---+const addLog = (msg) => {+ const time = new Date().toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' }) + '.' + new Date().getMilliseconds().toString().padStart(3, '0')+ systemLogs.value.push({ time, msg })+ if (systemLogs.value.length > 200) {+ systemLogs.value.shift()+ }+}++const updateStatus = (status) => {+ currentStatus.value = status+}++// --- Layout Methods ---+const toggleMaximize = (target) => {+ if (viewMode.value === target) {+ viewMode.value = 'split'+ } else {+ viewMode.value = target+ }+}++const handleGoBack = () => {+ // 返回到 Step 2 (环境搭建)+ router.push({ name: 'Simulation', params: { simulationId: currentSimulationId.value } })+}++const handleNextStep = () => {+ addLog('进入 Step 4: 报告生成')+ // TODO: 跳转到 Step 4 报告生成页面+ alert('Step 4: 报告生成 - Coming soon...')+}++// --- Data Logic ---+const loadSimulationData = async () => {+ try {+ addLog(`加载模拟数据: ${currentSimulationId.value}`)++ // 获取 simulation 信息+ const simRes = await getSimulation(currentSimulationId.value)+ if (simRes.success && simRes.data) {+ const simData = simRes.data++ // 获取 project 信息+ if (simData.project_id) {+ const projRes = await getProject(simData.project_id)+ if (projRes.success && projRes.data) {+ projectData.value = projRes.data+ addLog(`项目加载成功: ${projRes.data.project_id}`)++ // 获取 graph 数据+ if (projRes.data.graph_id) {+ await loadGraph(projRes.data.graph_id)+ }+ }+ }+ } else {+ addLog(`加载模拟数据失败: ${simRes.error || '未知错误'}`)+ }+ } catch (err) {+ addLog(`加载异常: ${err.message}`)+ }+}++const loadGraph = async (graphId) => {+ graphLoading.value = true+ try {+ const res = await getGraphData(graphId)+ if (res.success) {+ graphData.value = res.data+ addLog('图谱数据加载成功')+ }+ } catch (err) {+ addLog(`图谱加载失败: ${err.message}`)+ } finally {+ graphLoading.value = false+ }+}++const refreshGraph = () => {+ if (projectData.value?.graph_id) {+ loadGraph(projectData.value.graph_id)+ }+}++onMounted(() => {+ addLog('SimulationRunView 初始化')++ // 记录 maxRounds 配置(值已在初始化时从 query 参数获取)+ if (maxRounds.value) {+ addLog(`自定义模拟轮数: ${maxRounds.value}`)+ }++ loadSimulationData()+})+</script>++<style scoped>+.main-view {+ height: 100vh;+ display: flex;+ flex-direction: column;+ background: #FFF;+ overflow: hidden;+ font-family: 'Space Grotesk', -apple-system, BlinkMacSystemFont, sans-serif;+}++/* Header */+.app-header {+ height: 60px;+ border-bottom: 1px solid #EAEAEA;+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 0 24px;+ background: #FFF;+ z-index: 100;+}++.brand {+ font-family: 'JetBrains Mono', monospace;+ font-weight: 800;+ font-size: 18px;+ letter-spacing: 1px;+ cursor: pointer;+}++.view-switcher {+ display: flex;+ background: #F5F5F5;+ padding: 4px;+ border-radius: 6px;+ gap: 4px;+}++.switch-btn {+ border: none;+ background: transparent;+ padding: 6px 16px;+ font-size: 12px;+ font-weight: 600;+ color: #666;+ border-radius: 4px;+ cursor: pointer;+ transition: all 0.2s;+}++.switch-btn.active {+ background: #FFF;+ color: #000;+ box-shadow: 0 2px 4px rgba(0,0,0,0.05);+}++.header-right {+ display: flex;+ align-items: center;+ gap: 16px;+}++.workflow-step {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 14px;+}++.step-num {+ font-family: 'JetBrains Mono', monospace;+ font-weight: 700;+ color: #999;+}++.step-name {+ font-weight: 700;+ color: #000;+}++.step-divider {+ width: 1px;+ height: 14px;+ background-color: #E0E0E0;+}++.status-indicator {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 12px;+ color: #666;+ font-weight: 500;+}++.dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: #CCC;+}++.status-indicator.processing .dot { background: #FF5722; animation: pulse 1s infinite; }+.status-indicator.completed .dot { background: #4CAF50; }+.status-indicator.error .dot { background: #F44336; }++@keyframes pulse { 50% { opacity: 0.5; } }++/* Content */+.content-area {+ flex: 1;+ display: flex;+ position: relative;+ overflow: hidden;+}++.panel-wrapper {+ height: 100%;+ overflow: hidden;+ transition: width 0.4s cubic-bezier(0.25, 0.8, 0.25, 1), opacity 0.3s ease, transform 0.3s ease;+ will-change: width, opacity, transform;+}++.panel-wrapper.left {+ border-right: 1px solid #EAEAEA;+}+</style>diff --git a/frontend/src/views/SimulationView.vue b/frontend/src/views/SimulationView.vueindex 12053e88..ad41e08a 100644--- a/frontend/src/views/SimulationView.vue+++ b/frontend/src/views/SimulationView.vue@@ -155,14 +155,19 @@ const handleNextStep = (params = {}) => {addLog('使用自动配置的模拟轮数')}- // TODO: 调用 startSimulation API 并跳转到 Step 3- // 可以在这里调用 /api/simulation/start 接口- // const startParams = {- // simulation_id: currentSimulationId.value,- // ...(params.maxRounds && { max_rounds: params.maxRounds })- // }+ // 构建路由参数+ const routeParams = {+ name: 'SimulationRun',+ params: { simulationId: currentSimulationId.value }+ }++ // 如果有自定义轮数,通过 query 参数传递+ if (params.maxRounds) {+ routeParams.query = { maxRounds: params.maxRounds }+ }- alert(`Step 3: 开始模拟 - Coming soon...\n${params.maxRounds ? `轮数: ${params.maxRounds}` : '使用自动配置轮数'}`)+ // 跳转到 Step 3 页面+ router.push(routeParams)}// --- Data Logic ---