Compare commits

..

No commits in common. "92c3e25f7a883587d8400fcc311a833e9ba51e83" and "f7ce0559b7187b2561e1ae3be49840a0b74a0de9" have entirely different histories.

6 changed files with 36 additions and 110 deletions

View File

@ -132,17 +132,10 @@ class WebTerminal(MainTerminal):
try: try:
success = self.context_manager.load_conversation_by_id(conversation_id) success = self.context_manager.load_conversation_by_id(conversation_id)
if success: if success:
# 根据对话元数据同步思考模式
try:
conv_data = self.context_manager.conversation_manager.load_conversation(conversation_id) or {}
meta = conv_data.get("metadata", {}) or {}
mode = bool(meta.get("thinking_mode", self.thinking_mode))
self.thinking_mode = mode
self.api_client.thinking_mode = mode
self.api_client.start_new_task()
except Exception:
pass
# 重置相关状态 # 重置相关状态
if self.thinking_mode:
self.api_client.start_new_task()
self.current_session_id += 1 self.current_session_id += 1
# 获取对话信息 # 获取对话信息

View File

@ -110,7 +110,8 @@ async function bootstrapApp() {
// 系统信息 // 系统信息
projectPath: '', projectPath: '',
agentVersion: '', agentVersion: '',
thinkingMode: true, // true=思考模式, false=快速模式 thinkingMode: '未知',
nextThinkingMode: null,
// 消息相关 // 消息相关
messages: [], messages: [],
@ -592,7 +593,8 @@ async function bootstrapApp() {
this.socket.on('system_ready', (data) => { this.socket.on('system_ready', (data) => {
this.projectPath = data.project_path || ''; this.projectPath = data.project_path || '';
this.agentVersion = data.version || this.agentVersion; this.agentVersion = data.version || this.agentVersion;
this.thinkingMode = !!data.thinking_mode; this.thinkingMode = data.thinking_mode || '未知';
this.nextThinkingMode = null;
console.log('系统就绪:', data); console.log('系统就绪:', data);
// 系统就绪后立即加载对话列表 // 系统就绪后立即加载对话列表
@ -1321,7 +1323,13 @@ async function bootstrapApp() {
const statusData = await statusResponse.json(); const statusData = await statusResponse.json();
this.projectPath = statusData.project_path || ''; this.projectPath = statusData.project_path || '';
this.agentVersion = statusData.version || this.agentVersion; this.agentVersion = statusData.version || this.agentVersion;
this.thinkingMode = !!statusData.thinking_mode; if (statusData.thinking_mode) {
this.thinkingMode = statusData.thinking_mode.label || '未知';
this.nextThinkingMode = statusData.thinking_mode.next ?? null;
} else {
this.thinkingMode = '未知';
this.nextThinkingMode = null;
}
// 获取当前对话信息 // 获取当前对话信息
const statusConversationId = statusData.conversation && statusData.conversation.current_id; const statusConversationId = statusData.conversation && statusData.conversation.current_id;
@ -1854,7 +1862,7 @@ async function bootstrapApp() {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
body: JSON.stringify({ body: JSON.stringify({
thinking_mode: this.thinkingMode thinking_mode: this.thinkingMode !== '快速模式'
}) })
}); });
@ -1979,31 +1987,6 @@ async function bootstrapApp() {
toggleSidebar() { toggleSidebar() {
this.sidebarCollapsed = !this.sidebarCollapsed; this.sidebarCollapsed = !this.sidebarCollapsed;
}, },
async toggleThinkingMode() {
try {
const resp = await fetch('/api/thinking-mode', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ thinking_mode: !this.thinkingMode })
});
const data = await resp.json();
if (data.success && data.data) {
if (typeof data.data === 'object') {
this.thinkingMode = !!data.data.enabled;
} else {
this.thinkingMode = data.data === '思考模式';
}
} else {
throw new Error(data.message || data.error || '切换失败');
}
} catch (error) {
console.error('切换思考模式失败:', error);
alert(`切换思考模式失败: ${error.message}`);
}
},
formatTime(timeString) { formatTime(timeString) {
if (!timeString) return ''; if (!timeString) return '';

View File

@ -45,7 +45,7 @@
<span class="agent-version" v-if="agentVersion">{{ agentVersion }}</span> <span class="agent-version" v-if="agentVersion">{{ agentVersion }}</span>
</div> </div>
<div class="header-right"> <div class="header-right">
<span class="thinking-mode">{{ thinkingMode ? '思考模式' : '快速模式' }}</span> <span class="thinking-mode">{{ thinkingMode }}</span>
<span class="connection-status" :class="{ connected: isConnected }"> <span class="connection-status" :class="{ connected: isConnected }">
<span class="status-dot" :class="{ active: isConnected }"></span> <span class="status-dot" :class="{ active: isConnected }"></span>
{{ isConnected ? '已连接' : '未连接' }} {{ isConnected ? '已连接' : '未连接' }}
@ -534,18 +534,18 @@
:disabled="streamingMessage || !isConnected"> :disabled="streamingMessage || !isConnected">
{{ rightCollapsed ? '展开聚焦面板' : '折叠聚焦面板' }} {{ rightCollapsed ? '展开聚焦面板' : '折叠聚焦面板' }}
</button> </button>
<button type="button"
class="menu-btn mode-entry"
@click="toggleThinkingMode"
:disabled="streamingMessage || !isConnected">
{{ thinkingMode ? '思考模式' : '快速模式' }}
</button>
<button type="button" <button type="button"
class="menu-btn compress-entry" class="menu-btn compress-entry"
@click="compressConversation" @click="compressConversation"
:disabled="compressing || streamingMessage || !isConnected"> :disabled="compressing || streamingMessage || !isConnected">
{{ compressing ? '压缩中...' : '压缩' }} {{ compressing ? '压缩中...' : '压缩' }}
</button> </button>
<button type="button"
class="menu-btn mode-entry"
@click="toggleNextThinkingMode"
:disabled="streamingMessage || !isConnected">
{{ nextThinkingMode ? '下一次: 思考模式' : '下一次: 快速模式' }}
</button>
</div> </div>
</transition> </transition>
</div> </div>

View File

@ -47,10 +47,6 @@ class DeepSeekClient:
} }
self.thinking_mode = thinking_mode # True=智能思考模式, False=快速模式 self.thinking_mode = thinking_mode # True=智能思考模式, False=快速模式
self.web_mode = web_mode # Web模式标志用于禁用print输出 self.web_mode = web_mode # Web模式标志用于禁用print输出
# 兼容旧代码路径
self.api_base_url = self.fast_api_config["base_url"]
self.api_key = self.fast_api_config["api_key"]
self.model_id = self.fast_api_config["model_id"]
# 每个任务的独立状态 # 每个任务的独立状态
self.current_task_first_call = True # 当前任务是否是第一次调用 self.current_task_first_call = True # 当前任务是否是第一次调用
self.current_task_thinking = "" # 当前任务的思考内容 self.current_task_thinking = "" # 当前任务的思考内容

View File

@ -370,8 +370,7 @@ class ContextManager:
conversation_id=self.current_conversation_id, conversation_id=self.current_conversation_id,
messages=self.conversation_history, messages=self.conversation_history,
project_path=str(self.project_path), project_path=str(self.project_path),
todo_list=self.todo_list, todo_list=self.todo_list
thinking_mode=getattr(self.main_terminal, "thinking_mode", None) if hasattr(self, "main_terminal") else None
) )
if success: if success:

View File

@ -280,16 +280,6 @@ def ensure_conversation_loaded(terminal: WebTerminal, conversation_id: Optional[
load_result = terminal.load_conversation(conversation_id) load_result = terminal.load_conversation(conversation_id)
if not load_result.get("success"): if not load_result.get("success"):
raise RuntimeError(load_result.get("message", "对话加载失败")) raise RuntimeError(load_result.get("message", "对话加载失败"))
# 切换到对话记录的思考模式
try:
conv_data = terminal.context_manager.conversation_manager.load_conversation(conversation_id) or {}
meta = conv_data.get("metadata", {}) or {}
mode = bool(meta.get("thinking_mode", terminal.thinking_mode))
terminal.thinking_mode = mode
terminal.api_client.thinking_mode = mode
terminal.api_client.start_new_task()
except Exception:
pass
return conversation_id, created_new return conversation_id, created_new
def reset_system_state(terminal: Optional[WebTerminal]): def reset_system_state(terminal: Optional[WebTerminal]):
@ -507,47 +497,6 @@ def get_status(terminal: WebTerminal, workspace: UserWorkspace, username: str):
status['version'] = AGENT_VERSION status['version'] = AGENT_VERSION
return jsonify(status) return jsonify(status)
@app.route('/api/thinking-mode', methods=['POST'])
@api_login_required
@with_terminal
def update_thinking_mode(terminal: WebTerminal, workspace: UserWorkspace, username: str):
"""切换思考模式"""
try:
data = request.get_json() or {}
desired_mode = bool(data.get('thinking_mode'))
terminal.thinking_mode = desired_mode
terminal.api_client.thinking_mode = desired_mode
terminal.api_client.start_new_task()
session['thinking_mode'] = desired_mode
# 更新当前对话的元数据
ctx = terminal.context_manager
if ctx.current_conversation_id:
try:
ctx.conversation_manager.save_conversation(
conversation_id=ctx.current_conversation_id,
messages=ctx.conversation_history,
project_path=str(ctx.project_path),
todo_list=ctx.todo_list,
thinking_mode=desired_mode
)
except Exception as exc:
print(f"[API] 保存思考模式到对话失败: {exc}")
status = terminal.get_status()
socketio.emit('status_update', status, room=f"user_{username}")
return jsonify({
"success": True,
"data": status.get("thinking_mode")
})
except Exception as exc:
print(f"[API] 切换思考模式失败: {exc}")
return jsonify({
"success": False,
"error": str(exc),
"message": "切换思考模式时发生异常"
}), 500
@app.route('/api/files') @app.route('/api/files')
@api_login_required @api_login_required
@with_terminal @with_terminal
@ -1104,7 +1053,7 @@ def handle_connect():
reset_system_state(terminal) reset_system_state(terminal)
emit('system_ready', { emit('system_ready', {
'project_path': str(workspace.project_path), 'project_path': str(workspace.project_path),
'thinking_mode': bool(getattr(terminal, "thinking_mode", False)), 'thinking_mode': terminal.get_thinking_mode_status(),
'version': AGENT_VERSION 'version': AGENT_VERSION
}, room=request.sid) }, room=request.sid)
@ -3013,6 +2962,12 @@ async def handle_task_with_sender(terminal: WebTerminal, message, sender, client
'content': f'⚠️ 追加写入失败:{append_result.get("error")}' 'content': f'⚠️ 追加写入失败:{append_result.get("error")}'
}) })
# 重置文本流状态,避免后续错误处理
text_streaming = False
text_started = False
text_has_content = False
full_response = ""
if modify_result["handled"]: if modify_result["handled"]:
modify_metadata = modify_result.get("assistant_metadata") modify_metadata = modify_result.get("assistant_metadata")
modify_content_text = modify_result.get("assistant_content") modify_content_text = modify_result.get("assistant_content")
@ -3084,6 +3039,12 @@ async def handle_task_with_sender(terminal: WebTerminal, message, sender, client
'content': f'⚠️ 修改操作存在未完成的内容:{error_message}' 'content': f'⚠️ 修改操作存在未完成的内容:{error_message}'
}) })
text_streaming = False
text_started = False
text_has_content = False
full_response = ""
# 保存思考内容(如果这是第一次迭代且有思考) # 保存思考内容(如果这是第一次迭代且有思考)
if web_terminal.thinking_mode and web_terminal.api_client.current_task_first_call: if web_terminal.thinking_mode and web_terminal.api_client.current_task_first_call:
web_terminal.api_client.current_task_thinking = current_thinking or "" web_terminal.api_client.current_task_thinking = current_thinking or ""
@ -3146,12 +3107,6 @@ async def handle_task_with_sender(terminal: WebTerminal, message, sender, client
reasoning_content=current_thinking or None reasoning_content=current_thinking or None
) )
# 为下一轮迭代重置流状态标志,但保留 full_response 供上面保存使用
text_streaming = False
text_started = False
text_has_content = False
full_response = ""
if append_result["handled"] and append_result.get("tool_content"): if append_result["handled"] and append_result.get("tool_content"):
tool_call_id = append_result.get("tool_call_id") or f"append_{int(time.time() * 1000)}" tool_call_id = append_result.get("tool_call_id") or f"append_{int(time.time() * 1000)}"
system_notice = format_tool_result_notice("append_to_file", tool_call_id, append_result["tool_content"]) system_notice = format_tool_result_notice("append_to_file", tool_call_id, append_result["tool_content"])