Compare commits

..

5 Commits

6 changed files with 110 additions and 36 deletions

View File

@ -132,10 +132,17 @@ class WebTerminal(MainTerminal):
try:
success = self.context_manager.load_conversation_by_id(conversation_id)
if success:
# 重置相关状态
if self.thinking_mode:
# 根据对话元数据同步思考模式
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
# 重置相关状态
self.current_session_id += 1
# 获取对话信息

View File

@ -110,8 +110,7 @@ async function bootstrapApp() {
// 系统信息
projectPath: '',
agentVersion: '',
thinkingMode: '未知',
nextThinkingMode: null,
thinkingMode: true, // true=思考模式, false=快速模式
// 消息相关
messages: [],
@ -593,8 +592,7 @@ async function bootstrapApp() {
this.socket.on('system_ready', (data) => {
this.projectPath = data.project_path || '';
this.agentVersion = data.version || this.agentVersion;
this.thinkingMode = data.thinking_mode || '未知';
this.nextThinkingMode = null;
this.thinkingMode = !!data.thinking_mode;
console.log('系统就绪:', data);
// 系统就绪后立即加载对话列表
@ -1323,13 +1321,7 @@ async function bootstrapApp() {
const statusData = await statusResponse.json();
this.projectPath = statusData.project_path || '';
this.agentVersion = statusData.version || this.agentVersion;
if (statusData.thinking_mode) {
this.thinkingMode = statusData.thinking_mode.label || '未知';
this.nextThinkingMode = statusData.thinking_mode.next ?? null;
} else {
this.thinkingMode = '未知';
this.nextThinkingMode = null;
}
this.thinkingMode = !!statusData.thinking_mode;
// 获取当前对话信息
const statusConversationId = statusData.conversation && statusData.conversation.current_id;
@ -1862,7 +1854,7 @@ async function bootstrapApp() {
'Content-Type': 'application/json'
},
body: JSON.stringify({
thinking_mode: this.thinkingMode !== '快速模式'
thinking_mode: this.thinkingMode
})
});
@ -1988,6 +1980,31 @@ async function bootstrapApp() {
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) {
if (!timeString) return '';

View File

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

View File

@ -47,6 +47,10 @@ class DeepSeekClient:
}
self.thinking_mode = thinking_mode # True=智能思考模式, False=快速模式
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_thinking = "" # 当前任务的思考内容

View File

@ -370,7 +370,8 @@ class ContextManager:
conversation_id=self.current_conversation_id,
messages=self.conversation_history,
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:

View File

@ -280,6 +280,16 @@ def ensure_conversation_loaded(terminal: WebTerminal, conversation_id: Optional[
load_result = terminal.load_conversation(conversation_id)
if not load_result.get("success"):
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
def reset_system_state(terminal: Optional[WebTerminal]):
@ -497,6 +507,47 @@ def get_status(terminal: WebTerminal, workspace: UserWorkspace, username: str):
status['version'] = AGENT_VERSION
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')
@api_login_required
@with_terminal
@ -1053,7 +1104,7 @@ def handle_connect():
reset_system_state(terminal)
emit('system_ready', {
'project_path': str(workspace.project_path),
'thinking_mode': terminal.get_thinking_mode_status(),
'thinking_mode': bool(getattr(terminal, "thinking_mode", False)),
'version': AGENT_VERSION
}, room=request.sid)
@ -2962,12 +3013,6 @@ async def handle_task_with_sender(terminal: WebTerminal, message, sender, client
'content': f'⚠️ 追加写入失败:{append_result.get("error")}'
})
# 重置文本流状态,避免后续错误处理
text_streaming = False
text_started = False
text_has_content = False
full_response = ""
if modify_result["handled"]:
modify_metadata = modify_result.get("assistant_metadata")
modify_content_text = modify_result.get("assistant_content")
@ -3039,12 +3084,6 @@ async def handle_task_with_sender(terminal: WebTerminal, message, sender, client
'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:
web_terminal.api_client.current_task_thinking = current_thinking or ""
@ -3107,6 +3146,12 @@ async def handle_task_with_sender(terminal: WebTerminal, message, sender, client
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"):
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"])