调整onlogin 代码量

This commit is contained in:
CakeCN
2025-12-11 17:28:20 +08:00
parent 7300b304e3
commit 77cd53c241
2 changed files with 377 additions and 115 deletions

View File

@@ -2,6 +2,27 @@ import requests
from flask_socketio import Namespace
def clear_user_session(namespace_entry, user_id):
'''
快速清理用户会话的函数
'''
try:
base_url = namespace_entry.app.config['ASE_ENGINE_URL']
clear_url = f"{base_url}/clear_user_session"
payload = {
'namespace_url': namespace_entry.app.config['ASE_ENGINE_URL_TOKEN'], # WebSocket命名空间URL
'user_id': user_id, # 用户ID对应session_info.id
'clear_type': 'all' # 清理类型,默认为全部
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(clear_url, json=payload, headers=headers)
response.raise_for_status() # 检查请求是否成功
except Exception as e:
print(f"Error clearing user session: {e}")
def on_connect_to_ase(client, entry, init_data, **kwargs):
'''
此时刚刚建立好aseclient连接并向前端发送打开code-server-like指令。
@@ -10,24 +31,12 @@ def on_connect_to_ase(client, entry, init_data, **kwargs):
namespace_entry.emit('open-iframe',"", room=init_data['room'], namespace='/agent')
namespace_entry.emit('message', "Agents服务已连接, 加载教案中", room=init_data['room'], namespace='/agent')
if init_data.get("restart", False):
try:
base_url = namespace_entry.app.config['ASE_ENGINE_URL']
clear_url = f"{base_url}/clear_user_session"
payload = {
'namespace_url': namespace_entry.app.config['ASE_ENGINE_URL_TOKEN'], # WebSocket命名空间URL
'user_id': init_data['room'], # 用户ID对应session_info.id
'clear_type': 'all' # 清理类型,默认为全部
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(clear_url, json=payload, headers=headers)
response.raise_for_status() # 检查请求是否成功
except Exception as e:
print(f"Error clearing user session: {e}")
ase_client.chatmanager.load_now_chapter()
ase_client.send_text("chapter-start", "")
clear_user_session(namespace_entry, init_data['room'])
restart = init_data.get("restart", False)
if restart:
ase_client.chatmanager.load_now_chapter()
ase_client.send_text("chapter-start", "")
namespace_entry.emit('message', "教案加载完毕", room=init_data['room'], namespace='/agent')

View File

@@ -62,123 +62,376 @@ class VSCodeNamespace(Namespace):
class AgentNamespace(Namespace):
def on_login(self, data):
def _setup_initial_state(self, data):
"""Set up initial state, parse data, and join user to room."""
self.app = current_app
ex = current_app.extensions
uuid2username = ex["uuid2username"]
backboard_manager = ex["backboard_manager"]
data = json.loads(data)
# Extract required fields
user_uuid = data['user_uuid']
course_id = data['course_id']
lesson_name = data['lesson_name']
chapter_name = data['chapter_name']
# Get user_id and set session
uuid2username = ex["uuid2username"]
user_id = uuid2username[user_uuid]
session['user_uuid'] = user_uuid
join_room(user_uuid, namespace='/agent') # 将该用户加入以user_id为名的room
# Join user to room
join_room(user_uuid, namespace='/agent')
print(f'User connected with session user_uuid: {user_uuid}')
return {
'ex': ex,
'user_uuid': user_uuid,
'user_id': user_id,
'course_id': course_id,
'lesson_name': lesson_name,
'chapter_name': chapter_name
}
def _manage_ase_client(self, ex, user_uuid):
"""Manage ASE client: disconnect existing if connected and return chatmanager."""
user_uuid2chatmanager = ex["user_uuid2chatmanager"]
user_uuid2ase_client = ex["user_uuid2ase_client"]
if (user_uuid2ase_client.get(user_uuid,None) is not None and user_uuid2ase_client[user_uuid].connected):
# Disconnect existing ASE client if connected
if user_uuid2ase_client.get(user_uuid) is not None and user_uuid2ase_client[user_uuid].connected:
user_uuid2ase_client[user_uuid].disconnect()
# Get chatmanager
chatmanager = user_uuid2chatmanager[user_uuid]
chatmanager.function_manager.add_function(judge, {'course_id': course_id, 'root_path': f'/home/{user_id}/{course_id}/{chapter_name}/{lesson_name}'})
chatmanager.function_manager.add_function(next_chapter, {'user_uuid': user_uuid})
if not chatmanager.restart:# 尝试加载用户学习进度
progress_result = load_learning_progress(user_id, course_id, chapter_name, lesson_name)
need_skip_chapters = 0
if progress_result['exists']:
progress = progress_result['data']
# 恢复学习进度数据
if 'scores' in progress:
# 根据scores的数量确定需要跳过的章节数
need_skip_chapters = len(progress['scores'])
chatmanager.scores = progress['scores']
# 恢复聊天历史
if 'chat_historys' in progress:
chatmanager.chat_historys = progress['chat_historys']
else:
chatmanager.chat_historys = []
# 恢复当前章节链
if 'chapter_chain_now' in progress:
chatmanager.chapter_chain_now = progress['chapter_chain_now']
upload_learning_progress_to_cloud(progress)
else:
# 使用默认值,确保有完整的结构
chatmanager.chat_historys = progress_result['data']['chat_historys']
chatmanager.scores = progress_result['data']['scores']
return {
'chatmanager': chatmanager,
'user_uuid2ase_client': user_uuid2ase_client
}
def on_login(self, data):
initial_state = self._setup_initial_state(data)
ex = initial_state['ex']
user_uuid = initial_state['user_uuid']
user_id = initial_state['user_id']
course_id = initial_state['course_id']
lesson_name = initial_state['lesson_name']
chapter_name = initial_state['chapter_name']
backboard_manager = ex["backboard_manager"]
fmd,fmdp,fsp = load_full_markdown_file(course_id, chapter_name, lesson_name)
user_uuid2ase_client[user_uuid] = HSAEngineClient(current_app.config["ASE_ENGINE_URL"], current_app.config["ASE_ENGINE_NAMESPACE"],id=user_id, chatmanager = chatmanager)
chatmanager.init(user_uuid, user_uuid2ase_client[user_uuid], fmd, fmdp, fsp, course_id, chapter_name, lesson_name, max_iter=5, app=current_app, socketio=self)
backboard_manager.add_backboard(user_uuid, user_id, course_id, lesson_name, root_path=f'/home/{user_id}/{course_id}/{chapter_name}/{lesson_name}')
chatmanager.bb = backboard_manager.get_backboard(user_uuid)
if not progress:
chatmanager.next_chapter()
def _register_chatmanager_functions(self, chatmanager, course_id, user_id, chapter_name, lesson_name, user_uuid):
"""Register required functions to chatmanager's function manager."""
# Add judge function
chatmanager.function_manager.add_function(
judge,
{'course_id': course_id, 'root_path': f'/home/{user_id}/{course_id}/{chapter_name}/{lesson_name}'}
)
# 如果有保存的进度,需要跳过已经完成的章节
# Add next_chapter function
chatmanager.function_manager.add_function(
next_chapter,
{'user_uuid': user_uuid}
)
return not chatmanager.restart
def on_login(self, data):
initial_state = self._setup_initial_state(data)
ex = initial_state['ex']
user_uuid = initial_state['user_uuid']
user_id = initial_state['user_id']
course_id = initial_state['course_id']
lesson_name = initial_state['lesson_name']
chapter_name = initial_state['chapter_name']
backboard_manager = ex["backboard_manager"]
ase_management = self._manage_ase_client(ex, user_uuid)
chatmanager = ase_management['chatmanager']
user_uuid2ase_client = ase_management['user_uuid2ase_client']
def _load_and_restore_progress(self, chatmanager, user_id, course_id, chapter_name, lesson_name):
"""Load and restore user learning progress if available."""
need_skip_chapters = 0
# Load learning progress
progress_result = load_learning_progress(user_id, course_id, chapter_name, lesson_name)
if progress_result['exists']:
progress = progress_result['data']
# Restore scores and calculate chapters to skip
if 'scores' in progress:
need_skip_chapters = len(progress['scores'])
chatmanager.scores = progress['scores']
# Restore chat history
chatmanager.chat_historys = progress.get('chat_historys', [])
# Restore chapter chain
if 'chapter_chain_now' in progress:
chatmanager.chapter_chain_now = progress['chapter_chain_now']
# Upload progress to cloud
upload_learning_progress_to_cloud(progress)
else:
# Use default values from progress_result
chatmanager.chat_historys = progress_result['data']['chat_historys']
chatmanager.scores = progress_result['data']['scores']
return need_skip_chapters
def on_login(self, data):
initial_state = self._setup_initial_state(data)
ex = initial_state['ex']
user_uuid = initial_state['user_uuid']
user_id = initial_state['user_id']
course_id = initial_state['course_id']
lesson_name = initial_state['lesson_name']
chapter_name = initial_state['chapter_name']
backboard_manager = ex["backboard_manager"]
ase_management = self._manage_ase_client(ex, user_uuid)
chatmanager = ase_management['chatmanager']
user_uuid2ase_client = ase_management['user_uuid2ase_client']
continue_learn = self._register_chatmanager_functions(
chatmanager, course_id, user_id, chapter_name, lesson_name, user_uuid
)
need_skip_chapters = 0
if continue_learn:
need_skip_chapters = self._load_and_restore_progress(
chatmanager, user_id, course_id, chapter_name, lesson_name
)
def _initialize_ase_client_and_chatmanager(self, user_uuid, user_id, course_id, chapter_name, lesson_name, chatmanager, user_uuid2ase_client):
"""Initialize ASE client and chatmanager with required parameters."""
# Load full markdown file
fmd, fmdp, fsp = load_full_markdown_file(course_id, chapter_name, lesson_name)
# Create and initialize ASE client
ase_client = HSAEngineClient(
current_app.config["ASE_ENGINE_URL"],
current_app.config["ASE_ENGINE_NAMESPACE"],
id=user_id,
chatmanager=chatmanager
)
user_uuid2ase_client[user_uuid] = ase_client
# Initialize chatmanager
chatmanager.init(
user_uuid,
ase_client,
fmd,
fmdp,
fsp,
course_id,
chapter_name,
lesson_name,
max_iter=5,
app=current_app,
socketio=self
)
return ase_client
def _setup_backboard(self, backboard_manager, user_uuid, user_id, course_id, lesson_name, chapter_name, chatmanager):
"""Set up backboard for the user and associate with chatmanager."""
# Add backboard
root_path = f'/home/{user_id}/{course_id}/{chapter_name}/{lesson_name}'
backboard_manager.add_backboard(user_uuid, user_id, course_id, lesson_name, root_path=root_path)
# Associate backboard with chatmanager
chatmanager.bb = backboard_manager.get_backboard(user_uuid)
def on_login(self, data):
initial_state = self._setup_initial_state(data)
ex = initial_state['ex']
user_uuid = initial_state['user_uuid']
user_id = initial_state['user_id']
course_id = initial_state['course_id']
lesson_name = initial_state['lesson_name']
chapter_name = initial_state['chapter_name']
backboard_manager = ex["backboard_manager"]
ase_management = self._manage_ase_client(ex, user_uuid)
chatmanager = ase_management['chatmanager']
user_uuid2ase_client = ase_management['user_uuid2ase_client']
continue_learn = self._register_chatmanager_functions(
chatmanager, course_id, user_id, chapter_name, lesson_name, user_uuid
)
need_skip_chapters = 0
if continue_learn:
need_skip_chapters = self._load_and_restore_progress(
chatmanager, user_id, course_id, chapter_name, lesson_name
)
# Initialize ASE client and chatmanager
ase_client = self._initialize_ase_client_and_chatmanager(
user_uuid, user_id, course_id, chapter_name, lesson_name, chatmanager, user_uuid2ase_client
)
def _skip_completed_chapters(self, chatmanager, need_skip_chapters):
"""Skip chapters that have already been completed based on learning progress."""
for _ in range(need_skip_chapters):
chatmanager.next_chapter()
self.chatmanager = chatmanager
self.ase_client = user_uuid2ase_client[user_uuid]
user_uuid2ase_client[user_uuid].register_on_connect_entry(
callback=on_connect_to_ase,
entry=(self, user_uuid2ase_client[user_uuid]),
init_data={'room':user_uuid, 'restart':chatmanager.restart}
def on_login(self, data):
initial_state = self._setup_initial_state(data)
ex = initial_state['ex']
user_uuid = initial_state['user_uuid']
user_id = initial_state['user_id']
course_id = initial_state['course_id']
lesson_name = initial_state['lesson_name']
chapter_name = initial_state['chapter_name']
backboard_manager = ex["backboard_manager"]
ase_management = self._manage_ase_client(ex, user_uuid)
chatmanager = ase_management['chatmanager']
user_uuid2ase_client = ase_management['user_uuid2ase_client']
continue_learn = self._register_chatmanager_functions(
chatmanager, course_id, user_id, chapter_name, lesson_name, user_uuid
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='dialog',
callback=receive_ase_dialog,
entry=self,
init_data={'room': user_uuid}
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='dialog-hint',
callback=receive_ase_message_hint,
entry=self,
init_data={'room': user_uuid}
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='voice_out',
callback=receive_ase_voice_out,
entry=self,
init_data={'room': user_uuid}
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='judge',
callback=receive_ase_judge,
entry=self,
init_data={'room': user_uuid}
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='next_chapter',
callback=receive_ase_next_chapter,
entry=self,
init_data={'room': user_uuid}
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='chapter_score',
callback=receive_ase_chapter_score,
entry=(get_or_load_current_user(),chatmanager),
init_data={'room': user_uuid}
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='process',
callback=receive_ase_process,
entry=self,
init_data={'room': user_uuid}
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='paste_detected',
callback=receive_ase_paste_detected,
entry=self,
init_data={'room': user_uuid}
)
user_uuid2ase_client[user_uuid].connect()
need_skip_chapters = 0
if continue_learn:
need_skip_chapters = self._load_and_restore_progress(
chatmanager, user_id, course_id, chapter_name, lesson_name
)
# Initialize ASE client and chatmanager
ase_client = self._initialize_ase_client_and_chatmanager(
user_uuid, user_id, course_id, chapter_name, lesson_name, chatmanager, user_uuid2ase_client
)
# Set up backboard
self._setup_backboard(backboard_manager, user_uuid, user_id, course_id, lesson_name, chapter_name, chatmanager)
# Skip completed chapters if continuing learning
if continue_learn:
self._skip_completed_chapters(chatmanager, need_skip_chapters)
def _register_ase_routes(self, ase_client, user_uuid, chatmanager):
"""Register all required routes with ASE client."""
# Register on_connect entry
ase_client.register_on_connect_entry(
callback=on_connect_to_ase,
entry=(self, ase_client),
init_data={'room': user_uuid, 'restart': chatmanager.restart}
)
# Register dialog route
ase_client.register_route_with_entry(
route='dialog',
callback=receive_ase_dialog,
entry=self,
init_data={'room': user_uuid}
)
# Register dialog-hint route
ase_client.register_route_with_entry(
route='dialog-hint',
callback=receive_ase_message_hint,
entry=self,
init_data={'room': user_uuid}
)
# Register voice_out route
ase_client.register_route_with_entry(
route='voice_out',
callback=receive_ase_voice_out,
entry=self,
init_data={'room': user_uuid}
)
# Register judge route
ase_client.register_route_with_entry(
route='judge',
callback=receive_ase_judge,
entry=self,
init_data={'room': user_uuid}
)
# Register next_chapter route
ase_client.register_route_with_entry(
route='next_chapter',
callback=receive_ase_next_chapter,
entry=self,
init_data={'room': user_uuid}
)
# Register chapter_score route
ase_client.register_route_with_entry(
route='chapter_score',
callback=receive_ase_chapter_score,
entry=(get_or_load_current_user(), chatmanager),
init_data={'room': user_uuid}
)
# Register process route
ase_client.register_route_with_entry(
route='process',
callback=receive_ase_process,
entry=self,
init_data={'room': user_uuid}
)
# Register paste_detected route
ase_client.register_route_with_entry(
route='paste_detected',
callback=receive_ase_paste_detected,
entry=self,
init_data={'room': user_uuid}
)
# Connect the ASE client
ase_client.connect()
def on_login(self, data):
initial_state = self._setup_initial_state(data)
ex = initial_state['ex']
user_uuid = initial_state['user_uuid']
user_id = initial_state['user_id']
course_id = initial_state['course_id']
lesson_name = initial_state['lesson_name']
chapter_name = initial_state['chapter_name']
backboard_manager = ex["backboard_manager"]
ase_management = self._manage_ase_client(ex, user_uuid)
chatmanager = ase_management['chatmanager']
user_uuid2ase_client = ase_management['user_uuid2ase_client']
continue_learn = self._register_chatmanager_functions(
chatmanager, course_id, user_id, chapter_name, lesson_name, user_uuid
)
need_skip_chapters = 0
if continue_learn:
need_skip_chapters = self._load_and_restore_progress(
chatmanager, user_id, course_id, chapter_name, lesson_name
)
# Initialize ASE client and chatmanager
ase_client = self._initialize_ase_client_and_chatmanager(
user_uuid, user_id, course_id, chapter_name, lesson_name, chatmanager, user_uuid2ase_client
)
# Set up backboard
self._setup_backboard(backboard_manager, user_uuid, user_id, course_id, lesson_name, chapter_name, chatmanager)
# Skip completed chapters if continuing learning
if continue_learn:
self._skip_completed_chapters(chatmanager, need_skip_chapters)
# Set instance variables
self.chatmanager = chatmanager
self.ase_client = ase_client
# Register all ASE routes and connect
self._register_ase_routes(ase_client, user_uuid, chatmanager)
def on_language(self, language):