104 Commits

Author SHA1 Message Date
CakeCN
36bbedd3cf no caddy reload 2026-01-09 12:06:55 +08:00
CakeCN
0e3703b1f4 more log 2026-01-09 11:45:17 +08:00
CakeCN
52696707dd log in connect 2026-01-09 11:31:00 +08:00
CakeCN
0a812e496f fix namespace init 2026-01-09 11:24:13 +08:00
CakeCN
de1ba08d7e 修改了 AgentNamespace 类,将全局实例变量替换为字典,使用用户 UUID 作为键 2026-01-09 11:23:02 +08:00
CakeCN
3f14cbd6c1 some log 2026-01-09 11:16:30 +08:00
CakeCN
c51565199c more log 2026-01-09 01:40:36 +08:00
CakeCN
8d29a26d7d no connect on server 2026-01-09 01:27:24 +08:00
CakeCN
decf24020a use user-joined 2026-01-09 01:22:29 +08:00
CakeCN
3dc219adc2 use join 2026-01-09 01:19:08 +08:00
CakeCN
40d1341685 more set alwaysconnect to True 2026-01-09 00:58:46 +08:00
CakeCN
0d606fb171 ,always_connect=True 2026-01-09 00:56:56 +08:00
CakeCN
e1f32ec980 ase_client add user-connected 2026-01-09 00:04:31 +08:00
CakeCN
ad8d7d069c 增加log 2026-01-08 23:54:27 +08:00
CakeCN
687b316db6 删去earning_progess_process的log 2026-01-08 23:51:55 +08:00
CakeCN
60248d5c51 log connect_to_ase 2026-01-08 23:38:50 +08:00
CakeCN
befec5543c fix: 前端打开codelike 2026-01-08 21:06:11 +08:00
CakeCN
af24c51a2f fix previous 前端发送用户信息 2026-01-08 21:04:37 +08:00
CakeCN
fa91696aae fix previous 2026-01-08 21:02:44 +08:00
CakeCN
e698c50a4b 调整前端user-connected 2026-01-08 21:01:11 +08:00
CakeCN
75795dd853 fix previous 2026-01-08 20:52:51 +08:00
CakeCN
5b8180b48e 将join room提前到on_connect 2026-01-08 20:50:56 +08:00
CakeCN
09103abf38 移除了不存在的属性引用 :删除了导致错误的 eventlet.greenthread.main 相关代码 2026-01-08 00:11:31 +08:00
CakeCN
6ecd0c6735 包装了 eventlet.greenthread.main 函数,捕获所有绿色线程中的异常 2026-01-08 00:10:33 +08:00
CakeCN
a07eee1ffc fix 语音识别重复增加的问题 2026-01-08 00:05:23 +08:00
CakeCN
848b235ddc 移除了不存在的属性引用 :删除了导致错误的代码行 eventlet.debug.hub_prevent_multiple_readers(False) 2026-01-08 00:02:50 +08:00
CakeCN
7f469803df 在捕获到致命错误时,调用 self.close() 彻底关闭连接 2026-01-08 00:01:26 +08:00
CakeCN
4dd2667785 fix module 'eventlet.hubs' has no attribute 'handle_error' 2026-01-07 23:57:25 +08:00
CakeCN
f8e0b461ba fix module 'eventlet.hubs.hub' has no attribute 'Hub' 错误 2026-01-07 23:55:16 +08:00
CakeCN
607c6dfbab 有 eventlet.hubs 相关的错误都会被捕获并打印而不会向外传播导致服务器崩溃 2026-01-07 23:52:01 +08:00
CakeCN
73275cffad 每次 IO 操作之前或期间都会检查文件可用性,并在文件不可用时优雅处理 2026-01-07 20:46:32 +08:00
CakeCN
ee20e8b85b replacing the dynamic selectedItem.path+'/'+selectedItem.name with the filePath 2026-01-07 19:13:38 +08:00
CakeCN
b806da10c4 对 terminal_service.py 文件的全面检查和修复:在子进程中使用 os._exit(1) 替代 disconnect() ,避免在子进程中调用 SocketIO 方法导致的错误;修复了 SSH 硬编码端口问题 等 2026-01-07 18:57:00 +08:00
CakeCN
f818d84208 添加了对 errno 88 (Socket operation on non-socket)的处理 2026-01-07 18:52:17 +08:00
CakeCN
9231c14013 从run 中移除了全局try-except块,增强了eventlet内部错误处理 2026-01-07 01:33:25 +08:00
CakeCN
8aa567cdf2 全局异常捕获,特别是IOClosed错误,避免服务器崩溃 2026-01-07 01:06:13 +08:00
CakeCN
a3b3018de7 客户端断开连接后,文件描述符已经被关闭,但仍有事件在处理中:对 app/sockets/terminal_service.py 文件进行了全面修复 2026-01-07 00:57:27 +08:00
CakeCN
761095d61d 修复了code-server-like服务中的eventlet.hubs.IOClosed错误:当客户端断开连接时,文件描述符被关闭,但后台任务仍在尝试读取,导致eventlet核心代码抛出IOClosed错误。 2026-01-06 21:05:39 +08:00
Cai
643c16fdf7 fix:课时编辑页面步骤处保存冗余保存问题 2026-01-05 17:26:14 +08:00
Cai
5082436289 fix:index.html的课程详情页面跳转缺失 2026-01-05 16:08:55 +08:00
Cai
7193b9a000 fix:修复前端this undefined导致的无法选课问题 2026-01-05 15:50:51 +08:00
Cai
042f6ee99e restore some file 2025-12-31 10:45:42 +08:00
CakeCN
8fd88b0088 add jquery to dashboard 2025-12-31 10:35:25 +08:00
CakeCN
319b111485 pro config 2025-12-29 21:29:54 +08:00
CakeCN
f060a17f6a 生产服 .com 2025-12-29 21:10:49 +08:00
CakeCN
ecdc2e320f Merge branch 'main' of https://hsamooc.com/git/CakeCN/hsa 2025-12-29 20:53:22 +08:00
CakeCN
aa9f39ca18 Merge branch 'main' of https://hsamooc.com/git/CakeCN/hsa 2025-12-29 20:52:54 +08:00
CakeCN
f444e86136 许多更新
Merge branch 'test'
2025-12-29 20:52:03 +08:00
CakeCN
22d9fb39f1 project token change 2025-12-29 20:45:20 +08:00
68493d6a62 add:教师端新增删除课程,增加并更换footer-brief模板 2025-12-25 15:52:29 +08:00
f3c30a80a3 fix:教师端新增课程卡片中选择从课程创建的渲染错误问题(传递的是materials而不是courses) 2025-12-25 15:17:12 +08:00
f09d82571f fix:教师端新增课程的卡片自适应布局 2025-12-25 14:33:52 +08:00
CakeCN
cb435ecade fix chapter now 2025-12-14 14:33:29 +08:00
CakeCN
c8942cedac 初始为0 2025-12-14 14:22:23 +08:00
CakeCN
1f6e75f006 history 重构 2025-12-14 14:07:27 +08:00
CakeCN
5438dc99ba DEBUG 模式 2025-12-14 11:10:54 +08:00
CakeCN
f65b5bf32a try except 2025-12-14 11:05:01 +08:00
CakeCN
da93289799 eventlet green subprocess 2025-12-14 10:58:15 +08:00
CakeCN
1554c85616 event let hub_prevent_multiple_readers(False) 配置,禁用了Eventlet的同时读取检测 2025-12-14 10:56:38 +08:00
CakeCN
70410d2c4b some static bug 2025-12-14 10:32:52 +08:00
CakeCN
3c8821b225 Merge branch 'test' 2025-12-13 23:51:11 +08:00
CakeCN
496c5be90a code-server-like ssh clash 2025-12-13 23:50:45 +08:00
CakeCN
ec6be8233c 增加code-serverlike cdnback 2025-12-13 22:52:16 +08:00
CakeCN
d0331d9361 navbar adjust 2025-12-13 21:47:10 +08:00
CakeCN
8e79380ba4 progress 检查 2025-12-13 18:56:21 +08:00
CakeCN
6acb1db093 direct no load history when no history 2025-12-13 18:36:33 +08:00
CakeCN
af0ebda419 try fix nextchapter bug 2025-12-13 18:16:34 +08:00
CakeCN
ae9f7b84f4 Merge branch 'test'
修复progress Bar和提示美化
2025-12-12 16:59:58 +08:00
CakeCN
ac74c28f64 提示helpTip的标准化 2025-12-12 16:58:27 +08:00
CakeCN
41c17fcde1 help tips 标准化 2025-12-12 16:46:41 +08:00
CakeCN
5789974d2e 修复一些progressbar bug 2025-12-12 16:34:42 +08:00
CakeCN
221f3faace 美化processbar 2025-12-12 16:26:51 +08:00
CakeCN
560c590067 fix chatmanager 2025-12-12 16:15:48 +08:00
CakeCN
02cf3c0f78 优化前端js代码 2025-12-12 16:11:46 +08:00
CakeCN
9a7571f832 增加function approval button 2025-12-12 00:55:16 +08:00
CakeCN
14dd164545 function 提交 2025-12-12 00:47:09 +08:00
CakeCN
ff3d6e5bf9 fix chatmanager no scores bug 2025-12-12 00:29:03 +08:00
CakeCN
97df0f6407 logger /download 2025-12-12 00:25:39 +08:00
CakeCN
58a25b3e07 fix clear session 2025-12-11 22:40:43 +08:00
CakeCN
c4743bcadd restart with clear user_session 2025-12-11 22:37:58 +08:00
CakeCN
f9b3cf53da 不再使用markdown编译html,而是直接markdown源文件,前端进行渲染 2025-12-11 21:46:04 +08:00
CakeCN
fe1784fa20 前后端next_chapter同步 2025-12-11 21:25:23 +08:00
CakeCN
140ece742e log clear session 2025-12-11 20:46:22 +08:00
CakeCN
97cda4031b clear user session fix 2025-12-11 20:23:21 +08:00
CakeCN
9c3ffce1e2 fix load_history always "false" 2025-12-11 20:20:38 +08:00
CakeCN
23bfc73bcf more log 2025-12-11 20:17:38 +08:00
CakeCN
4a5a34b0aa log restart 2025-12-11 20:16:24 +08:00
CakeCN
2f48f1b6b4 load now chapter with restart 2025-12-11 20:00:15 +08:00
CakeCN
b175407d4b 前端对话历史 2025-12-11 19:53:14 +08:00
CakeCN
ce4a9ac2ca onlogin reduce 2025-12-11 17:47:13 +08:00
CakeCN
be78f480a5 roll back 2025-12-11 17:38:28 +08:00
CakeCN
f804eac811 reduce onlogin 2025-12-11 17:33:36 +08:00
CakeCN
77cd53c241 调整onlogin 代码量 2025-12-11 17:28:20 +08:00
CakeCN
fc7c6708b4 Merge branch 'test' 2025-12-11 16:20:44 +08:00
CakeCN
7300b304e3 修复bug 2025-12-11 16:19:59 +08:00
CakeCN
7aa7bf1690 log receive ack 2025-12-11 15:42:45 +08:00
CakeCN
84a4a578a8 add some logger 2025-12-11 15:32:41 +08:00
CakeCN
5df2931fa1 fix logger 2025-12-11 15:23:50 +08:00
CakeCN
99758ce1f8 add app context log 2025-12-11 15:10:02 +08:00
CakeCN
ae91b62332 logger time 2025-12-11 15:02:33 +08:00
CakeCN
a041650a54 删除app back 2025-12-11 15:00:56 +08:00
CakeCN
ad7fd04f19 add .gitattributes 2025-12-11 14:19:14 +08:00
CakeCN
1bf13aacf6 little change 2025-12-11 14:04:58 +08:00
CakeCN
9dfa0c9738 speed up event wait 2025-12-10 22:47:39 +08:00
62 changed files with 11387 additions and 1666 deletions

1
Html/.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
Html/config.ini merge=ours

File diff suppressed because one or more lines are too long

View File

@@ -1,480 +0,0 @@
from bootstrap import bootstrap_paths
bootstrap_paths()
from functools import wraps
from flask import Flask, redirect, session, request, jsonify, render_template, send_from_directory, url_for
from flask_cors import CORS
from flask_socketio import SocketIO, join_room, emit, Namespace
import markdown
import os
import uuid
import shutil
import sys
import json
from apps.auth.decorators import require_role
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, parent_dir)
student_workspace_root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../study'))
current_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))
sys.path.insert(0, current_dir)
from AlgoriAgent.projects.algoriAgent.agent_manager import AgentManager
import configparser
from db.user_list import UserList
from db.user import User, load_user_from_json, create_user_json
from db.course_list import CourseList
from db.course import Course, load_course_from_json
GLOBAL_CONFIG = configparser.ConfigParser()
GLOBAL_CONFIG.read('config.ini')
VSCODE_WEB_URL = GLOBAL_CONFIG['VSCODE_WEB']['url']
USER_DATA_DIR = GLOBAL_CONFIG['USER_DATA']['dir']
COURSE_DATA_DIR = GLOBAL_CONFIG['COURSE_DATA']['dir']
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*",ping_timeout=60, ping_interval=5)
# socketio = SocketIO(app, cors_allowed_origins="http://localhost:9888") # 设置跨域支持
import logging
app.secret_key = 'cakebaker'
app.logger.setLevel(logging.DEBUG)
# 配置 CORS
CORS(app, resources={r"/*": {"origins": VSCODE_WEB_URL},}, supports_credentials=True)
userid_recorder = {} # user_id&path -> session['user_id']
'''
Backboard
'''
from backboardManager import BackBoardManager, Backboard
backboard_manager = BackBoardManager()
uuid2username = {}
username2uuid = {}
# 定义命名空间:用于和 VSCode 插件交流
class VSCodeNamespace(Namespace):
def on_login(self,data):
print("VSCode client connected")
print(data)
dataconfig = data['config']
user_id = dataconfig.get('user_id')
path = dataconfig.get('path')
course_id = dataconfig.get('course_id')
lesson_id = dataconfig.get('chapter_id')
print(f"User {user_id} connected with path: {path}")
useruuid = username2uuid[user_id]
join_room(useruuid, namespace='/vscode')
if backboard_manager.get_backboard(useruuid) == None:
backboard_manager.add_backboard(useruuid,user_id, course_id, lesson_id, path)
def on_message(self, data):
print(f"Received from VSCode client: {data}")
dataconfig = data['config']
realtime_response(dataconfig, data)
# emit('response', {'message': 'Config data received and connection established'})
def on_disconnect(self, data):
print("VSCode client disconnected")
print("Disconnect reason:"+str(data))
def realtime_response(config, realtime_action):
user_id = config['user_id']
folder_path = config['path']
useruuid = username2uuid[user_id]
bb = backboard_manager.get_backboard(useruuid)
assert type(bb) == Backboard
bb.add_history(realtime_action)
if realtime_action['type'] == 'workspaceFolders':
bb.file_tree = realtime_action['fileTree']
if realtime_action['type'] == 'activeFile':
file_path = realtime_action['filePath']
assert type(file_path) == str
with open(f"{file_path}") as f:
bb.active_file_content = f.read()
if realtime_action['type'] == 'paste':
file_path = realtime_action['filePath']
assert type(file_path) == str
bb.pasted_file_path = file_path
bb.pasted_content = realtime_action['content']
bb.active_file_path = file_path
with open(f"{file_path}") as f:
bb.active_file_content = f.read()
if realtime_action['type'] == 'fileEdit':
file_path = realtime_action['filePath']
assert type(file_path) == str
bb.active_file_path = file_path
with open(f"{file_path}") as f:
bb.active_file_content = f.read()
print("config"+str(config))
print("realtime_action"+str(realtime_action))
pass
'''
Agent and Chat
'''
agent_manager = AgentManager(app = app, socketio = socketio)
user_threads = {}
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
# 初始化线程池
executor = ThreadPoolExecutor(max_workers=10)
class AgentNamespace(Namespace):
def on_login(self, data):
data = json.loads(data)
user = data['username']
course_id = data['course_id']
chapter_id = data['chapter_id']
user_uuid = username2uuid[user]
session['user_id'] = user_uuid
print(f'User connected with session user_id: {user_uuid}')
# 从markdown、markdown_prompts、score_prompts中各读取数据folder.md并进行new_agent
with open(f'books/markdown/{course_id}/{chapter_id}.md','r',encoding='UTF-8') as fmd,\
open(f'books/markdown_prompts/{course_id}/{chapter_id}.md','r',encoding='UTF-8')as fmdp,\
open(f'books/score_prompts/{course_id}/{chapter_id}.md','r',encoding='UTF-8') as fsp:
markdown = fmd.read()
markdown_prompts = fmdp.read()
score_prompts = fsp.read()
user_uuid, agent = agent_manager.new_agent(course_id, chapter_id, markdown, markdown_prompts, score_prompts, id=user_uuid,
root_path=f'../../study/{user}/{course_id}/{chapter_id}')
print(user_uuid)
join_room(user_uuid, namespace='/agent') # 将该用户加入以user_id为名的room
backboard_manager.add_backboard(user_uuid, user, course_id, chapter_id, root_path=f'../../study/{user}/{course_id}/{chapter_id}')
def on_language(self, language):
id = session.get('user_id')
agent_manager.change_language(id, language)
def on_message(self, data):
print(f"Message from client: {data}")
id = session.get('user_id')
if (type(data)==str):
data = json.loads(data)
print(id)
if data['type'] == 'text':
res = agent_manager.invoke(id, data['data'], backboard_manager.get_backboard(id).get_info_prompt())
print('=*='*20)
print(res.content)
reply = f"{res.content['speak']}"
with app.app_context():
emit('message',reply, room=id, namespace='/agent')
emit('request_function',res.content['function'], room=id, namespace='/agent')
if data['type'] == 'function':
agent_manager.function_call(id, data['data'])
def on_initiative(self,data):
print("User active function call")
user_id = session['user_id']
if data['name'] == 'sample_judge':
agent_manager.sample_judge(user_id, backboard_manager.get_backboard(user_id))
if data['name'] == 'judge':
agent_manager.judge(user_id, backboard_manager.get_backboard(user_id))
def on_disconnect(self,data):
print("VSCode client disconnected")
print("Disconnect reason:"+str(data))
'''
Markdown to HTML
'''
# 配置文件路径
MARKDOWN_DIR = 'books/markdown' # 存放 markdown 文件的文件夹
STATIC_DIR = 'static' # 存放生成的 HTML 和图片资源的文件夹
IMAGE_DIR = 'image' # 图片资源相对于 markdown 的位置
@app.route('/<course_id>-<filename>-markdown', methods=['GET'])
def convert_md(course_id, filename):
md_file_path = os.path.join(MARKDOWN_DIR,course_id, f'{filename}.md')
if not os.path.exists(md_file_path):
return jsonify({'error': 'Markdown file not found'}), 404
# 读取 markdown 文件内容
with open(md_file_path, 'r', encoding='utf-8') as file:
md_content = file.read()
# 将 markdown 转换为 HTML
html_content = markdown.markdown(md_content)
# 插入 CSS 样式,限制图片最大宽度为 100%,高度自动调整
html_with_styles = f"""
<html>
<head>
<style>
img {{
max-width: 100%;
height: auto;
}}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css">
</head>
<body>
{html_content}
</body>
</html>
"""
# 保存 HTML 文件到 static 文件夹
html_output_path = os.path.join(STATIC_DIR, f'{filename}.html')
with open(html_output_path, 'w', encoding='utf-8') as html_file:
html_file.write(html_with_styles)
# 处理图片资源,将 image/xxx 文件夹拷贝到 static/image/xxx
image_source_dir = os.path.join(MARKDOWN_DIR,course_id, IMAGE_DIR, filename)
image_target_dir = os.path.join(STATIC_DIR, IMAGE_DIR, filename)
print(f"Copying image resources from {image_source_dir} to {image_target_dir}")
if os.path.exists(image_source_dir):
# 确保 static/image/xxx 目录存在
if not os.path.exists(image_target_dir):
os.makedirs(image_target_dir)
# 拷贝图片资源
for image_file in os.listdir(image_source_dir):
full_image_file_path = os.path.join(image_source_dir, image_file)
if os.path.isfile(full_image_file_path):
shutil.copy(full_image_file_path, image_target_dir)
return jsonify({'html_url': f'/static/{filename}.html'})
# 静态文件HTML 和图片资源)的访问
@app.route('/static/<path:filename>')
def serve_static(filename):
return send_from_directory(STATIC_DIR, filename)
'''
Vscode
'''
@app.route('/desktop/<user_id>/<course_id>/<chapter_id>')
def desktop(user_id, course_id, chapter_id):
if 'user_id' not in session:
# return redirect(url_for('login'))
session['user_id'] = 'user_' + str(uuid.uuid4())
print("user "+ user_id + "uuid is"+ session['user_id'])
username2uuid[user_id] = session['user_id']
uuid2username[session['user_id']] = user_id
userid_recorder[user_id+'&'+course_id] = session['user_id']
# 在学习目录下创建一个名为 user_id_path 的文件夹
path_dir = os.path.join(student_workspace_root_path, user_id, course_id,chapter_id)
os.makedirs(path_dir, exist_ok=True)
# 在此文件夹内部创建一个.config文件并写入 user_id=user_id\n path=path
config_path = os.path.join(path_dir, '.config')
if GLOBAL_CONFIG['VSCODE_WEB_PATH']['is_wsl']: # 如果是在 WSL 中运行,则将路径转换为 WSL 路径
path_dir = path_dir.replace('\\', '/')
path_dir = path_dir.replace(GLOBAL_CONFIG['VSCODE_WEB_PATH']['windows_path'] , GLOBAL_CONFIG['VSCODE_WEB_PATH']['wsl_path'])
with open(config_path, 'w', encoding='utf-8') as f:
tmpd = {'user_id': user_id, 'course_id': course_id, 'chapter_id': chapter_id, 'path': path_dir}
json.dump(tmpd, f)
print('---------------------')
print(config_path)
return render_template('desktop.html', vscode_web_url=VSCODE_WEB_URL, user_id=user_id, course_id=course_id, chapter_id=chapter_id, workspace_path=path_dir)
@app.route('/desktop_nouser/<course_id>/<chapter_id>')
def desktop_nouser(course_id, chapter_id):
if 'user_id' not in session:
return redirect(url_for('login'))
user_id = session['user_id']
username = uuid2username[user_id]
return redirect(url_for('desktop', user_id=username, course_id=course_id, chapter_id=chapter_id))
@app.route('/vscode_data', methods=['POST'])
def vscode_data():
data = request.json
config = data['config']
realtime_response(config,data)
print(f"Received data from VSCode: {data}")
return jsonify({"status": "success", "received": data})
'''
Login
'''
users_list = UserList()
course_list = CourseList()
@app.route('/register')
def register():
return render_template('register.html')
@app.route('/register_teacher')
def register_teacher():
return render_template('register_teacher.html')
@app.route('/register_teacher_post', methods=['POST'])
def register_teacher_post():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if users_list.has_user(username) is not None:
users_list.add_user(username, password, teacher=True)
create_user_json(username, USER_DATA_DIR)
return jsonify({'success': True, 'message': '注册成功'})
else: return jsonify({'success': False, 'message': '用户已存在,请更换用户名'})
@app.route('/register_post', methods=['POST'])
def register_post():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if users_list.has_user(username) is not None:
users_list.add_user(username, password)
create_user_json(username, USER_DATA_DIR)
return jsonify({'success': True, 'message': '注册成功'})
else: return jsonify({'success': False, 'message': '用户已存在,请更换用户名'})
@app.route('/login')
def login():
return render_template('login.html')
if 'user_id' not in session:
return render_template('login.html')
else:
return redirect(url_for('/'))
@app.route('/login_post', methods=['POST'])
def login_post():
# 获取请求的 JSON 数据
data = request.get_json()
username = data.get('username')
password = data.get('password')
pswd = users_list.get_user_pswd(username)
if pswd is None:
return jsonify({'success': False, 'message': '用户名或密码错误'})
if pswd != password:
return jsonify({'success': False, 'message': '用户名或密码错误'})
session['user_id'] = 'user_' + str(uuid.uuid4())
print("user "+ username + "uuid is"+ session['user_id'])
username2uuid[username] = session['user_id']
uuid2username[session['user_id']] = username
return jsonify({'success': True, 'message': '登录成功'})
@app.route('/login_teacher_post', methods=['POST'])
def login_teacher_post():
data = request.get_json()
username = data.get('username')
password = data.get('password')
pswd = users_list.get_user_pswd(username)
is_teacher = users_list.get_user_is_teacher(username)
if is_teacher is None or is_teacher == False:
return jsonify({'success': False, 'message': '用户名不存在或非教师账号'})
if pswd is None:
return jsonify({'success': False, 'message': '用户名或密码错误'})
if pswd != password:
return jsonify({'success': False, 'message': '用户名或密码错误'})
session['user_id'] = 'user_' + str(uuid.uuid4())
print("user "+ username + "uuid is"+ session['user_id'])
username2uuid[username] = session['user_id']
uuid2username[session['user_id']] = username
return jsonify({'success': True, 'message': '登录成功'})
@app.route('/teacherboard')
@require_role(roles="teacher")
def teacherboard():
return render_template('teacherboard.html')
@app.route('/logout')
def logout():
session.pop('user_id', None)
return redirect(url_for('login'))
@app.route('/get_session')
def get_session():
user_session = session.get('user_id', 'default_session')
return jsonify({"session": user_session})
'''
DashBoard
'''
user_id2UserClass = {}
@app.route('/dashboard')
@require_role
def dashboard():
user_id = session['user_id']
username = uuid2username[user_id]
if (user_id not in user_id2UserClass):
user_id2UserClass[user_id] = load_user_from_json(username, user_data_dir = USER_DATA_DIR)
user_course_data = []
for course_id in user_id2UserClass[user_id].select_course:
course_brief_info = course_list.get_course_brief_info(course_id, load_course_from_json(course_id, course_data_dir = COURSE_DATA_DIR))
user_course_data.append(course_brief_info)
return render_template('dashboard.html',user_data = user_id2UserClass[user_id].to_json_without_dialog(), user_course_data = json.dumps(user_course_data))
'''
Course
'''
@app.route('/course/<course_id>')
@require_role
def course(course_id):
c = load_course_from_json(course_id, course_data_dir = COURSE_DATA_DIR)
return render_template('course.html', course_id=course_id, course_data=c)
@app.route('/select_course', methods=['POST'])
@require_role
def select_course():
user = user_id2UserClass[session['user_id']]
data = request.get_json()
course_id = data.get('course_id')
if course_id:
user.select_new_course(course_id, load_course_from_json(course_id, COURSE_DATA_DIR))
return jsonify({'success': True, 'message': '课程选择成功'})
@app.route('/')
@require_role
def home_index():
selected_courses=[]
if ('user_id' in session):
if (session['user_id'] not in user_id2UserClass): return redirect(url_for('login'))
user = user_id2UserClass[session['user_id']]
for course_id in user.select_course:
selected_courses.append(course_id)
return render_template('index.html', courses_data = course_list, selected_courses =selected_courses)
# 一些app辅助函数主要提供给Agent与数据库的交互能力
class MyFunction:
def save_chapter_memory(self, id, course_id, lesson_id, subchapter_title, mem_list, score, is_rebuttal):
print("-=-=-=-=-=-=-=-")
print(id, course_id, lesson_id, subchapter_title, mem_list, score, is_rebuttal)
username = uuid2username[id]
u = load_user_from_json(username, user_data_dir = USER_DATA_DIR)
u.save_chapter_memory(course_id, lesson_id, subchapter_title, mem_list, score, is_rebuttal)
app.my_function = MyFunction()
if __name__ == '__main__':
socketio.on_namespace(VSCodeNamespace('/vscode'))
socketio.on_namespace(AgentNamespace('/agent'))
socketio.run(app, host='0.0.0.0', port=5551, debug=False,allow_unsafe_werkzeug=True)

View File

@@ -0,0 +1,165 @@
# HelpTip 组件文档
## 功能介绍
HelpTip 是一个通用的提示框组件,用于在鼠标悬停时显示提示信息。它具有以下特点:
- 提示框跟随鼠标移动
- 支持多行文本
- 自动防出界
- 平滑的显示/隐藏动画
- 支持在不同页面复用
- 代码标准化,易于维护
## 文件结构
```
/static/
├── css/
│ └── helpTip.css # 样式文件
└── js/
└── helpTip.js # 核心功能文件
```
## 使用方法
### 1. 引入文件
在需要使用 HelpTip 的 HTML 页面中引入以下文件:
```html
<!-- 样式文件 -->
<link rel="stylesheet" href="/static/css/helpTip.css">
<!-- 功能文件 -->
<script src="/static/js/helpTip.js"></script>
```
### 2. 基本用法
```javascript
// 获取需要绑定提示框的元素
const element = document.getElementById('target-element');
// 绑定提示框
attachImmediateTooltip(element, '这是一条提示信息');
```
### 3. 支持换行的提示信息
```javascript
attachImmediateTooltip(element, `这是一条\n多行提示信息\n\n支持换行符`);
```
### 4. 与问号图标配合使用
```html
<!-- HTML -->
<span>这是一个元素<span class="help-icon">?</span></span>
```
```javascript
// JavaScript
const helpIcon = document.querySelector('.help-icon');
attachImmediateTooltip(helpIcon, '这是一条详细的提示信息');
```
## API 说明
### attachImmediateTooltip(anchorEl, text)
绑定提示框到指定元素。
#### 参数
- `anchorEl` (HTMLElement): 触发提示框的元素
- `text` (string): 提示框显示的文本内容,支持换行符 `\n`
#### 返回值
- `Function`: 清理函数,用于移除事件监听器
## 样式说明
### 问号图标样式
| 类名 | 说明 |
|------|------|
| `.help-icon` | 问号图标基础样式 |
| `.help-icon:hover` | 问号图标悬停样式 |
### 提示框样式
| 类名 | 说明 |
|------|------|
| `.tooltip-portal` | 提示框基础样式 |
| `.tooltip-portal.show` | 提示框显示状态 |
| `.tooltip-portal.fade` | 提示框动画效果 |
## 示例场景
### 1. 进度条提示
```javascript
// 为进度条的每个阶段绑定提示框
for (let i = 0; i < progressItems.length; i++) {
const item = progressItems[i];
attachImmediateTooltip(item, `阶段 ${i + 1}: ${item.title}`);
}
```
### 2. 表单字段提示
```javascript
// 为表单字段绑定提示框
const formFields = document.querySelectorAll('.form-field');
formFields.forEach(field => {
const tip = field.getAttribute('data-tip');
if (tip) {
attachImmediateTooltip(field, tip);
}
});
```
### 3. 工具栏图标提示
```javascript
// 为工具栏图标绑定提示框
const toolbarIcons = document.querySelectorAll('.toolbar-icon');
toolbarIcons.forEach(icon => {
const title = icon.getAttribute('title');
if (title) {
attachImmediateTooltip(icon, title);
}
});
```
## 注意事项
1. 确保在 DOM 加载完成后再调用 `attachImmediateTooltip` 函数
2. 如果元素是动态生成的,需要在元素生成后再绑定提示框
3. 提示框会自动添加到 `document.body` 中,不会被父元素的 `overflow` 属性裁切
4. 提示框的 `z-index` 为 999999确保它能覆盖所有元素
5. 提示框默认支持多行文本,使用 `white-space: pre-wrap` 样式
## 浏览器兼容性
- Chrome/Edge (最新版)
- Firefox (最新版)
- Safari (最新版)
## 代码优化建议
1. 对于大量元素需要绑定提示框的情况,建议使用事件委托
2. 如果页面中不再需要使用提示框,可以调用返回的清理函数移除事件监听器
3. 提示文本应简洁明了,避免过长
## 更新日志
- v1.0.0: 初始版本,实现了基本的提示框功能
- v1.0.1: 优化了样式,增加了动画效果
- v1.0.2: 支持多行文本,自动防出界
## 贡献指南
如果您发现问题或有改进建议,欢迎提出 Issue 或 Pull Request。

View File

@@ -32,8 +32,6 @@ class ASEngineClient:
# ACK相关
self.ack_events: Dict[str, Event] = {} # 存储ack_id和对应的Event对象
# 注册基础事件处理函数
self._register_base_events()
def _register_base_events(self):
@@ -41,16 +39,19 @@ class ASEngineClient:
# 连接事件
@self.sio.on('connect', namespace=self.namespace)
def on_connect():
print("---------------ASEngineClient on_connect----------------")
self.sid = self.sio.sid
print(f"Connected to server with sid: {self.sid}")
self.connected = True
self.sid = self.sio.get_sid(namespace=self.namespace)
print(f"Connected to server. SID: {self.sid}")
self.sio.emit('join', {'id': self.id}, namespace=self.namespace)
if self._on_connect_callback is not None:
self._on_connect_callback(
self,
self._on_connect_callback_entry,
init_data=self._on_connect_callback_initData
)
# 断开连接事件
@self.sio.on('disconnect', namespace=self.namespace)
def on_disconnect():
@@ -74,7 +75,6 @@ class ASEngineClient:
def on_ack(data):
ack_id = data.get('ack_id')
if ack_id and ack_id in self.ack_events:
print(f"Received ACK for message: {ack_id}")
event = self.ack_events[ack_id]
event.set() # 触发事件,通知等待的线程
@@ -228,7 +228,7 @@ class ASEngineClient:
self.sid = None
print("Disconnected from server")
def send_text(self, route: str, text: str, id:str="", wait_for_ack: bool = False, timeout: int = 5) -> bool:
def send_text(self, route: str, text: str, id:str="", wait_for_ack: bool = False, timeout: int = 5, return_event: bool = False) -> Any:
"""
发送文本消息
:param route: 目标路由
@@ -236,7 +236,8 @@ class ASEngineClient:
:param id: 发送者ID
:param wait_for_ack: 是否等待服务器ACK确认
:param timeout: 等待ACK的超时时间
:return: 是否发送成功若wait_for_ack为True则返回是否收到ACK
:param return_event: 是否返回事件对象和ack_id而不是等待ACK
:return: 如果wait_for_ack为True且return_event为False返回是否收到ACK如果return_event为True返回(event, ack_id);否则返回是否发送成功
"""
if not self.connected:
print("Not connected to server")
@@ -247,20 +248,13 @@ class ASEngineClient:
try:
# 生成唯一ack_id
ack_id = f"{id}_{datetime.now().strftime('%Y%m%d%H%M%S%f')}"
# 准备发送数据
data = {
'type': 'text',
'data': text,
'id': id,
'ack_id': ack_id
}
# 发送数据
self.sio.emit(route, data, namespace=self.namespace)
print(f"Sent text to route '{route}': {text[:20]}")
# 如果不需要等待ACK直接返回True
if not wait_for_ack:
return True
@@ -268,6 +262,10 @@ class ASEngineClient:
event = Event()
self.ack_events[ack_id] = event
# 如果需要返回事件对象,直接返回
if return_event:
return event, ack_id
# 等待ACK或超时
received_ack = event.wait(timeout=timeout)
@@ -316,9 +314,6 @@ class ASEngineClient:
},
namespace=self.namespace
)
print(f"Sent voice file to route '{route}'")
# 如果不需要等待ACK直接返回True
if not wait_for_ack:
return True
@@ -384,7 +379,6 @@ class ASEngineClient:
},
namespace=self.namespace
)
print(f"Sent image file to route '{route}': {filename}")
# 如果不需要等待ACK直接返回True
if not wait_for_ack:
@@ -428,6 +422,17 @@ class HSAEngineClient(ASEngineClient):
super().__init__(server_url, namespace, id)
self.chatmanager = chatmanager
def loadmarkdown(self, fmd, fmdp, fsp):
self.send_text('markdown-in', fmd, self.id, wait_for_ack=True)
self.send_text('markdown-prompt-in', fmdp, self.id, wait_for_ack=True)
self.send_text('score-prompt-in', fsp, self.id, wait_for_ack=True)
event1, ack_id1 = self.send_text('markdown-in', fmd, self.id, wait_for_ack=True, return_event=True)
event2, ack_id2 = self.send_text('markdown-prompt-in', fmdp, self.id, wait_for_ack=True, return_event=True)
event3, ack_id3 = self.send_text('score-prompt-in', fsp, self.id, wait_for_ack=True, return_event=True)
timeout = 5 # 超时时间
success1 = event1.wait(timeout=timeout)
success2 = event2.wait(timeout=timeout)
success3 = event3.wait(timeout=timeout)
if ack_id1 in self.ack_events:
del self.ack_events[ack_id1]
if ack_id2 in self.ack_events:
del self.ack_events[ack_id2]
if ack_id3 in self.ack_events:
del self.ack_events[ack_id3]
return success1 and success2 and success3

View File

@@ -35,7 +35,6 @@ class ChatManager:
_lock = threading.RLock()
def __init__(self, restart=False):
self.restart = restart
self.chapter_chain_now = -1
self.ase_client = None
self.app = None
self.socketio = None
@@ -49,7 +48,8 @@ class ChatManager:
self.chapter_chain = None
self.function_manager = FunctionManager()
self.bb = None
self.chat_historys = None
self.chat_historys = []
self.scores = []
self.vscode_ws = None
self._vscode_queue = deque()
self._lock = Semaphore(1)
@@ -69,6 +69,9 @@ class ChatManager:
self.chapter_chain = load_chapters(raw_markdown, raw_markdown_prompts, raw_score_prompts)
self.bb = None
self.chat_historys = []
self.chapter_chain_now = 0
self.scores = []
def send_to_vscode(self, event: str, data: dict, room: str = None, namespace: str = '/vscode'):
@@ -119,6 +122,7 @@ class ChatManager:
def next_chapter(self):
print(f"now next chapter {self.chapter_chain_now} and len {len(self.chapter_chain)}")
assert self.chapter_chain_now + 1 < len(self.chapter_chain), "chapter_chain_now out of range"
self.chapter_chain_now += 1
self.bb.next_chapter()
@@ -129,10 +133,11 @@ class ChatManager:
self.chapter_chain_now = chapter_index
self.chapter_chain[chapter_index].Focus()
def load_next_chapter(self):
print(f"now load next chapter markdown {self.chapter_chain_now}")
def load_now_chapter(self, load_code = True):
print(f"now load now chapter markdown {self.chapter_chain_now}")
self.ase_client.loadmarkdown(self.chapter_chain[self.chapter_chain_now].chapter, self.chapter_chain[self.chapter_chain_now].chapter_prompt, self.chapter_chain[self.chapter_chain_now].score_prompt)
self.load_code_in_markdown()
if load_code:
self.load_code_in_markdown()
def upload_bb(self):

View File

@@ -14,7 +14,7 @@ from typing import Optional
mongo = PyMongo()
socketio = SocketIO(cors_allowed_origins="*",max_payload_size=52428800, async_mode="eventlet") # 不直接传 app
socketio = SocketIO(cors_allowed_origins="*",max_payload_size=52428800, async_mode="eventlet",always_connect=False) # 不直接传 app
cors = CORS()
# ===== 你的全局对象 =====
# Backboard
@@ -38,7 +38,7 @@ def init_extensions(app):
cors_allowed_origins='*',#app.config["VSCODE_WEB_URL"],
ping_timeout=app.config["SOCKETIO_PING_TIMEOUT"],
ping_interval=app.config["SOCKETIO_PING_INTERVAL"],
max_payload_size=50000000, async_mode="eventlet"
max_payload_size=50000000, async_mode="eventlet",always_connect=False
)
cors.init_app(
app,

View File

@@ -1,34 +1,50 @@
import requests
from flask_socketio import Namespace
def clear_user_session(asengine_url, asengine_token, user_id):
'''
快速清理用户会话的函数
'''
try:
base_url = asengine_url
clear_url = f"{base_url}/api/sync/clear_user_session"
payload = {
'namespace_url': asengine_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() # 检查请求是否成功
print(f"User session {user_id} cleared successfully. Response: {response.json()}")
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指令。
'''
namespace_entry, ase_client = entry
namespace_entry, ase_client, logger = entry
logger.info(f"on_connect_to_ase with init_data: {init_data}")
namespace_entry.emit('open-iframe',"", room=init_data['room'], namespace='/agent')
namespace_entry.emit('message', "Agents服务已连接, 加载教案中", room=init_data['room'], namespace='/agent')
namespace_entry.emit('message', f'{init_data}', 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() # 检查请求是否成功
print(f"Clear user session successful: {response.json()}")
except Exception as e:
print(f"Error clearing user session: {e}")
ase_client.chatmanager.load_next_chapter()
ase_client.send_text("chapter-start", "")
restart = init_data.get("restart", False)
# 不再需要手动next_chapter因为已经在on_login中根据mongo进度恢复了正确的章节
# if restart: # 重启时,从-1章进入 0章
# ase_client.chatmanager.next_chapter()
# 根据restart决定是否重新加载代码
ase_client.chatmanager.load_now_chapter(load_code=restart)
print("load_now_chapter with restart:", restart)
# 只有当需要restart时才发送chapter-start
if restart:
ase_client.send_text("chapter-start", "")
namespace_entry.emit('message', "教案加载完毕", room=init_data['room'], namespace='/agent')
@@ -69,5 +85,5 @@ def receive_ase_chapter_score(client_entry, user_and_manager, data, init_data):
chatmanager.scores[chatmanager.chapter_chain_now - 1] = data.get('data', None)
else: chatmanager.scores.append(data.get('data', None))
user.set_course_progress(chatmanager.chat_historys, chatmanager.scores, chatmanager.course_id, chatmanager.chapter_name, chatmanager.lesson_name)
chatmanager.load_next_chapter()
chatmanager.load_now_chapter()
chatmanager.ase_client.send_text("chapter-start", "")

View File

@@ -36,6 +36,7 @@ def save_learning_progress(chatmanager, user_id: str) -> bool:
"chat_historys": chatmanager.chat_historys,
"scores": chatmanager.scores,
"multiagents_dialogs": his_data,
"chapter_chain_length": len(chatmanager.chapter_chain),
"updated_at": datetime.now()
}
@@ -145,6 +146,7 @@ def load_learning_progress(user_id: str, material_id: str, chapter_name: str, le
"chat_historys": [],
"scores": [],
"chapter_chain_now": None,
"chapter_chain_length": 0,
"updated_at": datetime.now().isoformat()
},
"message": "未找到学习记录,返回默认值"
@@ -163,6 +165,7 @@ def load_learning_progress(user_id: str, material_id: str, chapter_name: str, le
"chat_historys": [],
"scores": [],
"chapter_chain_now": None,
"chapter_chain_length": 0,
"updated_at": datetime.now().isoformat()
},
"message": error_msg

View File

@@ -24,7 +24,6 @@ def load_markdown_file(course_id, chapter_name, lesson_name):
break
if file_link is None:
return None
print(f"load_markdown_file: {file_link}")
return get_text_file(file_link)
def convert_markdown_to_html(md_file: str) -> str:

View File

@@ -23,7 +23,8 @@ from ..services.asectrl_service import (
receive_ase_process,
receive_ase_judge,
receive_ase_next_chapter,
receive_ase_chapter_score
receive_ase_chapter_score,
clear_user_session
)
@@ -62,6 +63,57 @@ class VSCodeNamespace(Namespace):
class AgentNamespace(Namespace):
def __init__(self, namespace):
super().__init__(namespace)
# 使用字典存储每个用户的chatmanager和ase_client避免多用户冲突
self.user_chatmanagers = {}
self.user_ase_clients = {}
def _load_learning_progress(self, chatmanager, user_id, course_id, chapter_name, lesson_name, continue_learn):
"""加载并恢复用户学习进度
Args:
chatmanager: 聊天管理器实例
user_id: 用户ID
course_id: 课程ID
chapter_name: 章节名称
lesson_name: 课时名称
continue_learn: 是否继续学习现在总是为True保持兼容性
Returns:
int: 需要跳过的章节数
"""
# 总是从mongo加载学习进度
progress_result = load_learning_progress(user_id, course_id, chapter_name, lesson_name)
if progress_result['exists']:
progress = progress_result['data']
# 恢复学习进度数据
if 'scores' in progress:
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)
# 计算需要跳过的章节数:从初始的-1到当前的chapter_chain_now
need_skip_chapters = chatmanager.chapter_chain_now
else:
# 使用默认值,确保有完整的结构
chatmanager.chat_historys = progress_result['data']['chat_historys']
chatmanager.scores = progress_result['data']['scores']
chatmanager.chapter_chain_now = 0
need_skip_chapters = 0
return need_skip_chapters
def on_login(self, data):
self.app = current_app
ex = current_app.extensions
@@ -74,8 +126,8 @@ class AgentNamespace(Namespace):
chapter_name = data['chapter_name']
user_id = uuid2username[user_uuid]
session['user_uuid'] = user_uuid
join_room(user_uuid, namespace='/agent') # 将该用户加入以user_id为名的room
print(f'User connected with session user_uuid: {user_uuid}')
join_room(user_uuid)
user_uuid2chatmanager = ex["user_uuid2chatmanager"]
user_uuid2ase_client = ex["user_uuid2ase_client"]
@@ -84,57 +136,46 @@ class AgentNamespace(Namespace):
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})
clear_user_session(current_app.config["ASE_ENGINE_URL"], current_app.config["ASE_ENGINE_URL_TOKEN"], user_id)
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']
# 总是从mongo加载进度不管restart状态
need_skip_chapters = self._load_learning_progress(chatmanager, user_id, course_id, chapter_name, lesson_name, True)
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.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()
# 如果有保存的进度,需要跳过已经完成的章节
# 总是根据进度跳过章节,恢复对话历史
for _ in range(need_skip_chapters):
chatmanager.next_chapter()
self.chatmanager = chatmanager
self.ase_client = user_uuid2ase_client[user_uuid]
emit('next_chapter', room=user_uuid, namespace='/agent')
# 恢复对话历史到前端 - 使用批量发送消息列表
if chatmanager.chat_historys:
emit('messages', chatmanager.chat_historys, room=user_uuid, namespace='/agent')
# 存储每个用户的chatmanager和ase_client到字典中使用用户UUID作为键
self.user_chatmanagers[user_uuid] = chatmanager
self.user_ase_clients[user_uuid] = user_uuid2ase_client[user_uuid]
# 将restart设置为False避免后续重复处理
restart = chatmanager.restart
chatmanager.restart = False
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}
entry=(self, user_uuid2ase_client[user_uuid], current_app.logger),
init_data={'room':user_uuid, 'restart':restart}
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='dialog',
callback=receive_ase_dialog,
entry=self,
init_data={'room': user_uuid}
init_data={'room':user_uuid}
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='dialog-hint',
@@ -152,13 +193,13 @@ class AgentNamespace(Namespace):
route='judge',
callback=receive_ase_judge,
entry=self,
init_data={'room': user_uuid}
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}
init_data={'room':user_uuid}
)
user_uuid2ase_client[user_uuid].register_route_with_entry(
route='chapter_score',
@@ -252,4 +293,4 @@ class AgentNamespace(Namespace):
leave_room(uuid, namespace='/agent')
self.app.logger.info("VSCode client disconnected")
self.app.logger.info(f"Disconnect reason: {str(data)}")
self.app.logger.info(f"Disconnect reason: {str(data)}")

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,218 @@
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/
/**
* Default styles for xterm.js
*/
.xterm {
cursor: text;
position: relative;
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.xterm.focus,
.xterm:focus {
outline: none;
}
.xterm .xterm-helpers {
position: absolute;
top: 0;
/**
* The z-index of the helpers must be higher than the canvases in order for
* IMEs to appear on top.
*/
z-index: 5;
}
.xterm .xterm-helper-textarea {
padding: 0;
border: 0;
margin: 0;
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
position: absolute;
opacity: 0;
left: -9999em;
top: 0;
width: 0;
height: 0;
z-index: -5;
/** Prevent wrapping so the IME appears against the textarea at the correct position */
white-space: nowrap;
overflow: hidden;
resize: none;
}
.xterm .composition-view {
/* TODO: Composition position got messed up somewhere */
background: #000;
color: #FFF;
display: none;
position: absolute;
white-space: nowrap;
z-index: 1;
}
.xterm .composition-view.active {
display: block;
}
.xterm .xterm-viewport {
/* On OS X this is required in order for the scroll bar to appear fully opaque */
background-color: #000;
overflow-y: scroll;
cursor: default;
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
}
.xterm .xterm-screen {
position: relative;
}
.xterm .xterm-screen canvas {
position: absolute;
left: 0;
top: 0;
}
.xterm .xterm-scroll-area {
visibility: hidden;
}
.xterm-char-measure-element {
display: inline-block;
visibility: hidden;
position: absolute;
top: 0;
left: -9999em;
line-height: normal;
}
.xterm.enable-mouse-events {
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
cursor: default;
}
.xterm.xterm-cursor-pointer,
.xterm .xterm-cursor-pointer {
cursor: pointer;
}
.xterm.column-select.focus {
/* Column selection mode */
cursor: crosshair;
}
.xterm .xterm-accessibility:not(.debug),
.xterm .xterm-message {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 10;
color: transparent;
pointer-events: none;
}
.xterm .xterm-accessibility-tree:not(.debug) *::selection {
color: transparent;
}
.xterm .xterm-accessibility-tree {
user-select: text;
white-space: pre;
}
.xterm .live-region {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
.xterm-dim {
/* Dim should not apply to background, so the opacity of the foreground color is applied
* explicitly in the generated class and reset to 1 here */
opacity: 1 !important;
}
.xterm-underline-1 { text-decoration: underline; }
.xterm-underline-2 { text-decoration: double underline; }
.xterm-underline-3 { text-decoration: wavy underline; }
.xterm-underline-4 { text-decoration: dotted underline; }
.xterm-underline-5 { text-decoration: dashed underline; }
.xterm-overline {
text-decoration: overline;
}
.xterm-overline.xterm-underline-1 { text-decoration: overline underline; }
.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }
.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }
.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }
.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }
.xterm-strikethrough {
text-decoration: line-through;
}
.xterm-screen .xterm-decoration-container .xterm-decoration {
z-index: 6;
position: absolute;
}
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {
z-index: 7;
}
.xterm-decoration-overview-ruler {
z-index: 8;
position: absolute;
top: 0;
right: 0;
pointer-events: none;
}
.xterm-decoration-top {
z-index: 2;
position: relative;
}

View File

@@ -0,0 +1,51 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.fit = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function proposeGeometry(term) {
if (!term.element.parentElement) {
return null;
}
var parentElementStyle = window.getComputedStyle(term.element.parentElement);
var parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height'));
var parentElementWidth = Math.max(0, parseInt(parentElementStyle.getPropertyValue('width')));
var elementStyle = window.getComputedStyle(term.element);
var elementPadding = {
top: parseInt(elementStyle.getPropertyValue('padding-top')),
bottom: parseInt(elementStyle.getPropertyValue('padding-bottom')),
right: parseInt(elementStyle.getPropertyValue('padding-right')),
left: parseInt(elementStyle.getPropertyValue('padding-left'))
};
var elementPaddingVer = elementPadding.top + elementPadding.bottom;
var elementPaddingHor = elementPadding.right + elementPadding.left;
var availableHeight = parentElementHeight - elementPaddingVer;
var availableWidth = parentElementWidth - elementPaddingHor - term._core.viewport.scrollBarWidth;
var geometry = {
cols: Math.floor(availableWidth / term._core.renderer.dimensions.actualCellWidth),
rows: Math.floor(availableHeight / term._core.renderer.dimensions.actualCellHeight)
};
return geometry;
}
exports.proposeGeometry = proposeGeometry;
function fit(term) {
var geometry = proposeGeometry(term);
if (geometry) {
if (term.rows !== geometry.rows || term.cols !== geometry.cols) {
term._core.renderer.clear();
term.resize(geometry.cols, geometry.rows);
}
}
}
exports.fit = fit;
function apply(terminalConstructor) {
terminalConstructor.prototype.proposeGeometry = function () {
return proposeGeometry(this);
};
terminalConstructor.prototype.fit = function () {
fit(this);
};
}
exports.apply = apply;
},{}]},{},[1])(1)
});
//# sourceMappingURL=fit.js.map

View File

@@ -0,0 +1,27 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.fullscreen = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function toggleFullScreen(term, fullscreen) {
var fn;
if (typeof fullscreen === 'undefined') {
fn = (term.element.classList.contains('fullscreen')) ? 'remove' : 'add';
}
else if (!fullscreen) {
fn = 'remove';
}
else {
fn = 'add';
}
term.element.classList[fn]('fullscreen');
}
exports.toggleFullScreen = toggleFullScreen;
function apply(terminalConstructor) {
terminalConstructor.prototype.toggleFullScreen = function (fullscreen) {
toggleFullScreen(this, fullscreen);
};
}
exports.apply = apply;
},{}]},{},[1])(1)
});
//# sourceMappingURL=fullscreen.js.map

View File

@@ -0,0 +1,126 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.search = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SearchHelper = (function () {
function SearchHelper(_terminal) {
this._terminal = _terminal;
}
SearchHelper.prototype.findNext = function (term) {
if (!term || term.length === 0) {
return false;
}
var result;
var startRow = this._terminal._core.buffer.ydisp;
if (this._terminal._core.selectionManager.selectionEnd) {
startRow = this._terminal._core.selectionManager.selectionEnd[1];
}
for (var y = startRow + 1; y < this._terminal._core.buffer.ybase + this._terminal.rows; y++) {
result = this._findInLine(term, y);
if (result) {
break;
}
}
if (!result) {
for (var y = 0; y < startRow; y++) {
result = this._findInLine(term, y);
if (result) {
break;
}
}
}
return this._selectResult(result);
};
SearchHelper.prototype.findPrevious = function (term) {
if (!term || term.length === 0) {
return false;
}
var result;
var startRow = this._terminal._core.buffer.ydisp;
if (this._terminal._core.selectionManager.selectionStart) {
startRow = this._terminal._core.selectionManager.selectionStart[1];
}
for (var y = startRow - 1; y >= 0; y--) {
result = this._findInLine(term, y);
if (result) {
break;
}
}
if (!result) {
for (var y = this._terminal._core.buffer.ybase + this._terminal.rows - 1; y > startRow; y--) {
result = this._findInLine(term, y);
if (result) {
break;
}
}
}
return this._selectResult(result);
};
SearchHelper.prototype._findInLine = function (term, y) {
var lowerStringLine = this._terminal._core.buffer.translateBufferLineToString(y, true).toLowerCase();
var lowerTerm = term.toLowerCase();
var searchIndex = lowerStringLine.indexOf(lowerTerm);
if (searchIndex >= 0) {
var line = this._terminal._core.buffer.lines.get(y);
for (var i = 0; i < searchIndex; i++) {
var charData = line[i];
var char = charData[1];
if (char.length > 1) {
searchIndex -= char.length - 1;
}
var charWidth = charData[2];
if (charWidth === 0) {
searchIndex++;
}
}
return {
term: term,
col: searchIndex,
row: y
};
}
};
SearchHelper.prototype._selectResult = function (result) {
if (!result) {
return false;
}
this._terminal._core.selectionManager.setSelection(result.col, result.row, result.term.length);
this._terminal.scrollLines(result.row - this._terminal._core.buffer.ydisp);
return true;
};
return SearchHelper;
}());
exports.SearchHelper = SearchHelper;
},{}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SearchHelper_1 = require("./SearchHelper");
function findNext(terminal, term) {
var addonTerminal = terminal;
if (!addonTerminal.__searchHelper) {
addonTerminal.__searchHelper = new SearchHelper_1.SearchHelper(addonTerminal);
}
return addonTerminal.__searchHelper.findNext(term);
}
exports.findNext = findNext;
function findPrevious(terminal, term) {
var addonTerminal = terminal;
if (!addonTerminal.__searchHelper) {
addonTerminal.__searchHelper = new SearchHelper_1.SearchHelper(addonTerminal);
}
return addonTerminal.__searchHelper.findPrevious(term);
}
exports.findPrevious = findPrevious;
function apply(terminalConstructor) {
terminalConstructor.prototype.findNext = function (term) {
return findNext(this, term);
};
terminalConstructor.prototype.findPrevious = function (term) {
return findPrevious(this, term);
};
}
exports.apply = apply;
},{"./SearchHelper":1}]},{},[2])(2)
});
//# sourceMappingURL=search.js.map

View File

@@ -0,0 +1,41 @@
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.webLinks = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var protocolClause = '(https?:\\/\\/)';
var domainCharacterSet = '[\\da-z\\.-]+';
var negatedDomainCharacterSet = '[^\\da-z\\.-]+';
var domainBodyClause = '(' + domainCharacterSet + ')';
var tldClause = '([a-z\\.]{2,6})';
var ipClause = '((\\d{1,3}\\.){3}\\d{1,3})';
var localHostClause = '(localhost)';
var portClause = '(:\\d{1,5})';
var hostClause = '((' + domainBodyClause + '\\.' + tldClause + ')|' + ipClause + '|' + localHostClause + ')' + portClause + '?';
var pathClause = '(\\/[\\/\\w\\.\\-%~]*)*';
var queryStringHashFragmentCharacterSet = '[0-9\\w\\[\\]\\(\\)\\/\\?\\!#@$%&\'*+,:;~\\=\\.\\-]*';
var queryStringClause = '(\\?' + queryStringHashFragmentCharacterSet + ')?';
var hashFragmentClause = '(#' + queryStringHashFragmentCharacterSet + ')?';
var negatedPathCharacterSet = '[^\\/\\w\\.\\-%]+';
var bodyClause = hostClause + pathClause + queryStringClause + hashFragmentClause;
var start = '(?:^|' + negatedDomainCharacterSet + ')(';
var end = ')($|' + negatedPathCharacterSet + ')';
var strictUrlRegex = new RegExp(start + protocolClause + bodyClause + end);
function handleLink(event, uri) {
window.open(uri, '_blank');
}
function webLinksInit(term, handler, options) {
if (handler === void 0) { handler = handleLink; }
if (options === void 0) { options = {}; }
options.matchIndex = 1;
term.registerLinkMatcher(strictUrlRegex, handler, options);
}
exports.webLinksInit = webLinksInit;
function apply(terminalConstructor) {
terminalConstructor.prototype.webLinksInit = function (handler, options) {
webLinksInit(this, handler, options);
};
}
exports.apply = apply;
},{}]},{},[1])(1)
});
//# sourceMappingURL=webLinks.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -107,13 +107,7 @@
.btn-group-toggle .btn {
padding: 5px 10px;
}
#leftSidebar, .vscode-web, #rightSidebar {
height: 100%;
overflow: auto;
}
/* 主容器,使用 grid 布局 */
/* 主容器,使用 grid 布局 */
#maxcontainer {
display: grid;
grid-template-columns: 2fr 5px 3fr 5px 2fr; /* 默认宽度比例 */
@@ -122,7 +116,20 @@
/* 各区域基础样式 */
.sidebar {
overflow: auto; /* 确保内容可以滚动 */
display: flex;
flex-direction: column;
overflow: hidden; /* 隐藏溢出内容,让内部元素单独滚动 */
}
/* 左侧边栏样式 */
#leftSidebar {
height: 100%;
}
/* 中间和右侧边栏样式 */
.vscode-web, #rightSidebar {
height: 100%;
overflow: auto;
}
.vscode-web {
@@ -162,55 +169,75 @@
/* Markdown内容区域样式 */
#markdown-content {
flex: 1; /* 占满剩余空间 */
overflow-y: auto; /* 只有内容区域可以垂直滚动 */
overflow-x: hidden; /* 隐藏水平滚动条 */
}
/* 设置进度条容器样式 */
#markdown-content-process {
display: flex;
align-items: flex-end; /* 让进度条靠底部对齐 */
padding: 0 10px 10px 10px; /* 添加底部内边距,调整与底部的距离 */
box-sizing: border-box;
flex-shrink: 0; /* 防止进度条被压缩 */
}
/* 设置每个子框的基本样式 */
.progress-box {
height: 100%; /* 度为 100%,撑满容器 */
width: 100%; /* 度为 100%,撑满容器 */
display: flex;
flex-direction: row; /* 使子框横向排列 */
justify-content: flex-start;
gap: 2px; /* 进度条之间的间距 */
margin-bottom: 0; /* 移除底部边距 */
}
.progress-title {
height: 60px;
text-align: center;
line-height: 60px;
margin-right: 2px;
border: 1px solid #ddd;
transition: background-color 0.3s ease;
height: 8px; /* 更细的进度条 */
flex: 1; /* 均匀分配宽度 */
border-radius: 4px; /* 圆角设计,更扁平化 */
transition: all 0.3s ease; /* 平滑过渡效果 */
position: relative;
/* 新增以下属性实现文字溢出省略 */
white-space: nowrap; /* 防止文字换行 */
overflow: hidden; /* 隐藏溢出内容 */
text-overflow: ellipsis; /* 溢出部分显示为省略号 */
cursor: pointer;
box-shadow: 0 1px 3px rgba(0,0,0,0.1); /* 轻微阴影,增加层次感 */
overflow: visible; /* 允许文字溢出 */
}
/* 颜色方案:已学习为蓝色,当前学习为绿色,未学习为白色 */
.blue {
background-color: #007bff; /* 蓝色 - 已学习 */
}
.green {
background-color: green;
color: white;
background-color: #28a745; /* 绿色 - 当前学习 */
}
.white {
background-color: white;
color: black;
background-color: #e9ecef; /* 浅灰色 - 未学习,比纯白色更美观 */
}
.progress-box > .progress-title:last-child {
margin-bottom: 0; /* 防止最后一个子框出现多余的间距 */
/* 进度条悬停效果 */
.progress-title:hover {
transform: translateY(-1px); /* 轻微上浮效果 */
box-shadow: 0 2px 5px rgba(0,0,0,0.2); /* 增强阴影 */
}
/* 进度条详细信息的样式 */
#progress-detail {
position: absolute;
top: 0;
left: 0;
display: none;
padding: 10px;
background-color: rgba(0, 0, 0, 0.7);
background-color: rgba(0, 0, 0, 0.8);
color: white;
border-radius: 5px;
border-radius: 6px;
max-width: 200px;
font-size: 14px;
z-index: 1000;
pointer-events: none; /* 防止干扰鼠标事件 */
box-shadow: 0 2px 10px rgba(0,0,0,0.3); /* 增强阴影 */
}
.button {

View File

@@ -0,0 +1,51 @@
/* HelpTip 组件样式 */
/* 问号图标样式 */
.help-icon {
display: inline-block;
margin-left: 8px;
color: #888;
font-weight: bold;
cursor: help;
font-size: 14px;
line-height: 1;
transition: color 0.2s ease;
}
.help-icon:hover {
color: #4CAF50;
}
/* 全局提示框样式(挂在 body 下) */
.tooltip-portal {
position: fixed; /* 不受父级 overflow 影响 */
left: 0;
top: 0;
z-index: 999999; /* 足够高,覆盖所有元素 */
display: none;
opacity: 0;
transition: opacity 0.08s linear;
background: rgba(0, 0, 0, 0.9);
color: #fff;
padding: 6px 10px;
border-radius: 6px;
font-size: 13px;
line-height: 1.4;
pointer-events: none; /* 鼠标穿透,避免闪烁 */
white-space: pre-wrap; /* 支持换行符 */
max-width: 300px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
word-wrap: break-word;
}
/* 提示框显示状态 */
.tooltip-portal.show {
display: block;
opacity: 1;
}
/* 提示框动画效果 */
.tooltip-portal.fade {
transition: opacity 0.2s ease;
}

View File

@@ -1,35 +1,3 @@
/* 问号图标 */
.help-icon {
display: inline-block;
margin-left: 8px;
color: #888;
font-weight: bold;
cursor: help;
}
.help-icon:hover { color: #4CAF50; }
/* Portal Tooltip挂在 body 下) */
.tooltip-portal {
position: fixed; /* 不受父级 overflow 影响 */
left: 0; top: 0;
z-index: 999999; /* 足够高,覆盖侧栏等 */
display: none;
opacity: 0;
transition: opacity .08s linear;
background: rgba(0,0,0,.9);
color: #fff;
padding: 6px 10px;
border-radius: 6px;
font-size: 13px;
line-height: 1.4;
pointer-events: none; /* 鼠标穿透,避免闪烁 */
white-space: nowrap;
box-shadow: 0 4px 12px rgba(0,0,0,.25);
}
.add-step-btn, .add-phase-btn {
background-color: #4CAF50;
color: white;

View File

@@ -3,13 +3,28 @@
background: linear-gradient(135deg, var(--primary-blue), var(--accent-blue));
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 0.8rem 1rem;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.navbar .logo h1 {
color: rgb(245, 245, 245);
font-size: 24px;
font-size: 18px;
font-weight: bold;
margin: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 300px;
}
.navbar-links {
display: flex;
justify-content: center;
flex: 1;
margin: 0 20px;
}
.navbar-links a {
@@ -69,4 +84,41 @@
/* 下拉浮框 hover 显示 */
.dropdown:hover .dropdown-content {
display: block;
}
/* 响应式设计 */
@media (max-width: 768px) {
.navbar {
flex-direction: column;
gap: 1rem;
}
.navbar-links {
margin: 0;
flex-wrap: wrap;
justify-content: center;
gap: 0.5rem;
}
.navbar-links a {
margin: 0 0.75rem;
font-size: 16px;
}
.navbar .logo h1 {
font-size: 16px;
max-width: 250px;
}
}
@media (max-width: 480px) {
.navbar .logo h1 {
font-size: 14px;
max-width: 200px;
}
.navbar-links a {
margin: 0 0.5rem;
font-size: 14px;
}
}

View File

@@ -60,6 +60,7 @@
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
cursor: pointer;
position: relative; /* 添加相对定位 */
}
.course-image {
@@ -81,6 +82,27 @@
.course-description {
font-size: 14px;
color: #555;
margin-bottom: 10px;
display: -webkit-box; /* 使用-webkit-box实现文本截断 */
-webkit-line-clamp: 3; /* 限制显示3行 */
-webkit-box-orient: vertical; /* 垂直排列 */
overflow: hidden; /* 隐藏溢出内容 */
text-overflow: ellipsis; /* 用省略号表示截断 */
}
/* 课程日期信息 */
.course-date {
position: absolute; /* 绝对定位到底部 */
bottom: 10px; /* 距离底部10px */
left: 0; /* 左对齐 */
right: 0; /* 右对齐 */
padding: 10px; /* 内边距 */
background-color: white; /* 白色背景 */
border-radius: 5px; /* 圆角 */
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影 */
font-size: 12px; /* 字体大小 */
color: #666; /* 字体颜色 */
line-height: 1.5; /* 行高 */
}
/* 课程目录弹出框 */
@@ -159,11 +181,14 @@
/* 浮窗内容 */
.modal-content {
background-color: #fff;
margin: 15% auto;
margin: 10% auto; /* 修改为10%以缩小顶部距离 */
padding: 20px;
border-radius: 10px;
width: 40%;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 80%; /* 修改为80%以适应小屏幕 */
max-width: 600px; /* 设置最大宽度 */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0 1);
overflow-y: auto; /* 添加垂直滚动条 */
max-height: 80vh; /* 设置最大高度 */
}
/* 按钮样式 */
@@ -205,7 +230,34 @@ label {
margin-top: 20px; /* 上方间距 */
}
/* 选择课程或新建课程的下拉框 */
.course-selection-container {
margin: 10px 0;
font-size: 16px;
}
#course-selection {
width: 100%; /* 占满一行 */
padding: 12px; /* 增加内边距 */
font-size: 16px; /* 调整字体大小 */
margin: 10px 0; /* 上下留间距 */
border: 2px solid #ccc; /* 边框 */
border-radius: 8px; /* 圆角边框 */
background-color: #f9f9f9; /* 背景色 */
transition: border 0.3s ease, box-shadow 0.3s ease; /* 添加过渡效果 */
}
/* 鼠标悬停时下拉框的效果 */
#course-selection:hover {
border-color: #4CAF50; /* 悬停时的边框颜色 */
box-shadow: 0 0 10px rgba(76, 175, 80, 0.5); /* 悬停时的阴影效果 */
}
/* 下拉框选中项的样式 */
#course-selection option {
padding: 10px;
font-size: 16px;
}
/* 添加课程按钮样式 */
.add-course-button {
@@ -433,6 +485,20 @@ label[for="course-description"] {
cursor: pointer;
}
.delete-course-btn {
background-color: #e74c3c;
color: white;
padding: 10px;
border-radius: 5px;
cursor: pointer;
width: 100%;
margin-top: 10px;
}
.delete-course-btn:hover {
background-color: #c0392b;
}
/* 编辑弹窗 */
.edit-modal {
display: none;

View File

@@ -2,6 +2,57 @@
var socket;
let system_message_idx = 0
const activeApprovals = {};
let chatManager; // 全局聊天管理器实例
// 聊天消息管理器 - 更现代的数据结构
class ChatMessageManager {
constructor() {
this.chatbox = document.getElementById('chatbox');
this.messageTemplate = {
user: `<div class="chat-message user-message"><b>你:</b> {{content}}</div>`,
assistant: `<div><b>华实君:</b></div><div class="chat-message server-message"> {{content}}</div>`
};
}
// 渲染单个消息
renderMessage(message) {
let html;
let content;
// 处理不同的数据格式
if (typeof message === 'string') {
// 旧格式:直接字符串
content = marked.parse(message);
html = this.messageTemplate.assistant.replace('{{content}}', content);
} else if (typeof message === 'object' && message !== null) {
// 新格式:{role, content} 对象
content = marked.parse(message.content);
if (message.role === 'user') {
html = this.messageTemplate.user.replace('{{content}}', content);
} else {
html = this.messageTemplate.assistant.replace('{{content}}', content);
}
}
if (html) {
const messageDiv = document.createElement('div');
messageDiv.innerHTML = html;
this.chatbox.appendChild(messageDiv);
this.scrollToBottom();
}
}
// 渲染多条消息(用于恢复历史)
renderMessages(messages) {
messages.forEach(message => this.renderMessage(message));
}
// 滚动到底部
scrollToBottom() {
this.chatbox.scrollTop = this.chatbox.scrollHeight;
}
}
// 清理过期的批准记录
function cleanupExpiredApprovals() {
const now = Date.now();
@@ -15,35 +66,38 @@ function cleanupExpiredApprovals() {
// 定时清理过期记录
setInterval(cleanupExpiredApprovals, 3000); // 每3秒检查一次
document.addEventListener('DOMContentLoaded', function () {
data = window.appData;
user_data = window.appData;
const host = window.location.host;
console.log(`Connecting to WebSocket server at wss://${host}/agent`);
socket = io(`wss://${host}/agent`, {
query: {
user_uuid: data.user_uuid,
folder: data.folder
user_uuid: user_data.user_uuid,
folder: user_data.folder
}
});
// 初始化聊天消息管理器
chatManager = new ChatMessageManager();
socket.on('connect', function () {
console.log('Connected to server');
socket.emit('login',JSON.stringify(data));
console.log('Connected to WebSocket server'+socket.id+"with user"+JSON.stringify(user_data));
socket.emit('login',JSON.stringify(user_data));
});
socket.on('open-iframe', function(data) {
OpenIframe();
socket.on('open-iframe', function() {
OpenIframe(user_data);
});
// 监听来自服务器的消息
socket.on('voiceMessage', function (data) {
console.log(data);
const input = document.getElementById('messageInput');
input.value += data;
input.value = data;
});
socket.on('message', function (data) {
// 显示服务器的回复消息
const serverMessage = document.createElement('div');
serverMessage.innerHTML = `<div><b>华实君:</b></div><div class="chat-message server-message"> ${marked.parse(data)}</div>`;
document.getElementById('chatbox').appendChild(serverMessage);
// 滚动到最新消息
document.getElementById('chatbox').scrollTop = document.getElementById('chatbox').scrollHeight;
// 显示服务器的回复消息 - 单个消息
chatManager.renderMessage(data);
});
socket.on('messages', function (data) {
// 显示服务器发送的消息列表 - 用于恢复对话历史
chatManager.renderMessages(data);
});
socket.on('message-hint', function(data){
console.log('get message-hint');
@@ -90,7 +144,7 @@ document.addEventListener('DOMContentLoaded', function () {
}
const approveButton = document.createElement('button');
approveButton.innerHTML = '<i class="fas fa-check-circle-check"></i>';
approveButton.innerHTML = '<i class="bi bi-check-circle-fill"></i>';
approveButton.data = element;
approveButton.className = 'approve-button';
approveButton.onclick = function (event) {
@@ -210,22 +264,14 @@ function sendMessage() {
const input = document.getElementById('messageInput').value;
if (input.trim() === '') return;
// 使用 marked.js 解析 markdown
const markdownHtml = marked.parse(input);
// 显示用户发送的消息
const userMessage = document.createElement('div');
userMessage.innerHTML = `<div class="chat-message user-message"><b>你:</b> ${markdownHtml}</div>`;
document.getElementById('chatbox').appendChild(userMessage);
// 发送消息到服务器
socket.emit('message', JSON.stringify({ data: input, type: 'text' }));
// 使用聊天管理器显示用户消息
chatManager.renderMessage({ role: 'user', content: input });
// 清空输入框
document.getElementById('messageInput').value = '';
// 滚动到最新消息
document.getElementById('chatbox').scrollTop = document.getElementById('chatbox').scrollHeight;
}
@@ -376,14 +422,11 @@ window.addEventListener('beforeunload', () => {
let currentChapterIndex = -1;
function next_chapter(data) {
// 获取所有的 h3 元素
var iframe = document.getElementById('markdown-content-iframe');
// 访问 iframe 的文档对象
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var titles = []
var h3Elements = iframeDocument.querySelectorAll('h3');
console.log("h3Elements next")
var container = document.getElementById('markdown-content-container');
var titles = [];
var h3Elements = container.querySelectorAll('h3');
console.log("h3Elements next");
if (currentChapterIndex >= h3Elements.length) {
return; // 如果已经到了最后一个章节,则不进行任何操作
}
@@ -391,7 +434,7 @@ function next_chapter(data) {
// 隐藏当前章节及其后的内容
for (let i = 0; i < h3Elements.length; i++) {
h3Elements[i].style.display = 'none';
titles.push(h3Elements[i].innerText)
titles.push(h3Elements[i].innerText);
let nextSibling = h3Elements[i].nextElementSibling;
while (nextSibling && nextSibling.tagName !== 'H3') {
nextSibling.style.display = 'none';
@@ -421,48 +464,31 @@ function generateProgressBar(N, idx, titles) {
const progressBox = document.createElement('div');
progressBox.className = 'progress-box';
// 获取详细信息容器
const detailBox = document.getElementById('progress-detail');
// 根据N值动态调整每个进度节点的宽度
const nodeWidth = 100 / N; // 每个节点的宽度为 100% / N
// 根据N值生成子框并设置颜色
for (let i = 0; i < N; i++) {
const titleBox = document.createElement('div');
titleBox.className = 'progress-title';
// 设置进度条的颜色
// 设置进度条的颜色:已学习为蓝色,当前学习为绿色,未学习为白色
if (i < idx) {
titleBox.classList.add('green'); // 已完成部分
titleBox.classList.add('blue'); // 已完成部分 - 蓝色
} else if (i === idx) {
titleBox.classList.add('green'); // 当前正在学习 - 绿色
} else {
titleBox.classList.add('white'); // 未完成部分
titleBox.classList.add('white'); // 未完成部分 - 白色
}
// 设置每个子框的标题
titleBox.innerHTML = titles[i] || `Step ${i + 1}`;
// 移除进度条上的文字,因为现在进度条很细
titleBox.innerHTML = '';
// 设置每个进度节点的宽度
titleBox.style.width = `${nodeWidth}%`;
// 监听鼠标移入事件来显示详情
titleBox.addEventListener('mouseenter', function () {
detailBox.innerHTML = `Step ${i + 1}: ${titles[i] || "No title"}`;// - Additional details here...`;
detailBox.style.display = 'block';
// 根据进度条位置显示详情
const rect = titleBox.getBoundingClientRect();
detailBox.style.top = `${rect.top + window.scrollY - 100}px`; // 微调位置
detailBox.style.left = `${rect.left + window.scrollX + rect.width / 2 - detailBox.offsetWidth / 2}px`;
});
// 监听鼠标移出事件来隐藏详情
titleBox.addEventListener('mouseleave', function () {
detailBox.style.display = 'none';
});
// 使用attachImmediateTooltip函数使提示框跟随鼠标移动
const tooltipText = `Step ${i + 1}: ${titles[i] || "No title"}`;
attachImmediateTooltip(titleBox, tooltipText);
progressBox.appendChild(titleBox);
}
// 将生成的进度条添加到容器中
container.appendChild(progressBox);
}

View File

@@ -0,0 +1,58 @@
// helpTip.js - 全局tooltip功能可在不同页面复用
// 在页面里复用一个全局 tooltip 节点
let __globalTooltip;
// 确保tooltip节点存在
function ensureTooltip() {
if (!__globalTooltip) {
__globalTooltip = document.createElement('div');
__globalTooltip.className = 'tooltip-portal';
document.body.appendChild(__globalTooltip);
}
return __globalTooltip;
}
// 绑定到任意图标:移入→显示;移动→跟随;移出→隐藏
function attachImmediateTooltip(anchorEl, text) {
const tip = ensureTooltip();
let shown = false;
function show(e) {
tip.textContent = text;
tip.style.display = 'block';
tip.style.opacity = '1';
position(e);
shown = true;
}
function position(e) {
// 以鼠标位置为准
const padding = 8;
const tipRect = tip.getBoundingClientRect();
let x = e.clientX + 12;
let y = e.clientY - tipRect.height - 12;
// 简易防出界
const vw = window.innerWidth, vh = window.innerHeight;
if (x + tipRect.width + padding > vw) x = vw - tipRect.width - padding;
if (y < padding) y = e.clientY + 16; // 放到下面
tip.style.left = `${x}px`;
tip.style.top = `${y}px`;
}
function hide() {
tip.style.opacity = '0';
// 用小延迟避免闪烁
setTimeout(() => { if (!shown) return; tip.style.display = 'none'; }, 100);
shown = false;
}
anchorEl.addEventListener('mouseenter', show);
anchorEl.addEventListener('mousemove', position);
anchorEl.addEventListener('mouseleave', hide);
}
// 导出函数,供其他文件使用
window.attachImmediateTooltip = attachImmediateTooltip;

View File

@@ -1,41 +1,53 @@
function show_books(courses_data, user_selected_courses){
function show_books(courses_data, user_selected_courses) {
console.log(courses_data)
console.log(user_selected_courses)
}
function show_course_details(course_id){
window.location.href = '/course/' + course_id
function show_course_details(course_id) {
window.location.href = '/course/' + course_id
}
function on_click_select_course(event){
function on_click_select_course(event) {
event.stopPropagation(); // 阻止事件冒泡
const courseId = event.currentTarget.getAttribute('data-course-id');
if (event.currentTarget.classList.contains("selected-button")) {alert('课程已选择'); return;}
const button = event.currentTarget;
const courseId = button.getAttribute('data-course-id');
if (!courseId) { alert('缺少课程ID'); return; }
if (button.classList.contains("selected-button")) { alert('课程已选择'); return; }
if (button.disabled) { return; }
button.disabled = true;
fetch(`/select_course`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token() }}' // 如果使用 CSRF 保护
},
body: JSON.stringify({ course_id: courseId })
})
.then(response => response.json())
.then(data => {
if (data.success) {
// 更新按钮样式或显示消息
this.classList.remove('select-button');
this.classList.add('selected-button');
this.textContent = '已选择';
.then(async (response) => {
let data = null;
try {
data = await response.json();
} catch (_) {
}
if (!response.ok) {
throw new Error(data?.message || `请求失败(${response.status})`);
}
return data;
})
.then((data) => {
if (!data?.success) {
throw new Error(data?.message || '选择课程失败');
}
button.classList.remove('select-button');
button.classList.add('selected-button');
button.textContent = '已选课';
alert('选择课程成功');
} else {
alert('选择课程失败');
}
})
.catch(error => {
console.error('Error:', error);
alert('选择课程失败');
});
})
.catch(error => {
console.error('Error:', error);
alert(error?.message || '选择课程失败');
button.disabled = false;
});
}
document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('DOMContentLoaded', function () {
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,116 @@
// 动态加载 Markdown 文件
function loadMarkdown(course_id, chapter_name, lesson_name) {
fetch(`/${course_id}-${chapter_name}-${lesson_name}-markdown`)
.then(response => response.json())
.then(data => {
if (data.markdown_content) {
// 使用 marked 解析 Markdown 内容
const html = marked.parse(data.markdown_content);
// 创建包含 MathJax 支持的 HTML 结构
const markdownContainer = document.createElement('div');
markdownContainer.id = 'markdown-content-container';
markdownContainer.innerHTML = html;
// 处理代码块,实现缩略显示
const codeBlocks = markdownContainer.querySelectorAll('pre code');
codeBlocks.forEach(codeBlock => {
const preBlock = codeBlock.parentElement;
// 保存原始代码内容
const originalContent = preBlock.innerHTML;
// 创建缩略提示元素
const codeHint = document.createElement('div');
codeHint.className = 'code-hint';
codeHint.innerHTML = '<div style="padding: 10px; background-color: #f5f5f5; border: 1px solid #ddd; border-radius: 4px; color: #666; font-size: 14px; text-align: center;">💡 代码已放置在代码区中,点击展开查看</div>';
// 创建展开/折叠按钮
const toggleButton = document.createElement('button');
toggleButton.className = 'toggle-code';
toggleButton.innerHTML = '展开代码';
toggleButton.style.cssText = 'margin: 5px; padding: 5px 10px; background-color: #007bff; color: white; border: none; border-radius: 3px; cursor: pointer; font-size: 12px;';
// 添加到提示元素中
codeHint.appendChild(toggleButton);
// 替换原始代码块为提示
preBlock.innerHTML = '';
preBlock.appendChild(codeHint);
// 保存原始代码,用于切换
preBlock.dataset.originalContent = originalContent;
preBlock.dataset.isExpanded = 'false';
// 添加切换事件
toggleButton.addEventListener('click', () => {
if (preBlock.dataset.isExpanded === 'false') {
// 展开代码
preBlock.innerHTML = preBlock.dataset.originalContent;
toggleButton.innerHTML = '折叠代码';
preBlock.appendChild(toggleButton);
preBlock.dataset.isExpanded = 'true';
// 如果MathJax已加载重新排版
if (typeof MathJax !== 'undefined') {
MathJax.typesetPromise([preBlock]);
}
} else {
// 折叠代码
preBlock.innerHTML = '';
preBlock.appendChild(codeHint.cloneNode(true));
preBlock.appendChild(toggleButton.cloneNode(true));
preBlock.dataset.isExpanded = 'false';
// 重新添加事件监听
const newToggleButton = preBlock.querySelector('.toggle-code');
newToggleButton.addEventListener('click', arguments.callee);
}
});
});
// 清空内容容器并添加渲染后的内容
const contentElement = document.getElementById('markdown-content');
contentElement.innerHTML = '';
contentElement.appendChild(markdownContainer);
// 配置并加载 MathJax
if (typeof MathJax === 'undefined') {
// 动态加载 MathJax
const script = document.createElement('script');
script.src = '/static/cdnback/js/tex-mml-chtml.js';
script.async = true;
script.onload = function() {
MathJax.config = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']]
},
svg: {
fontCache: 'global'
}
};
MathJax.typesetPromise([markdownContainer]);
// 初始化课程进度
next_chapter();
};
document.head.appendChild(script);
} else {
// MathJax 已加载,直接排版
MathJax.typesetPromise([markdownContainer]);
// 初始化课程进度
next_chapter();
}
} else {
console.error('Markdown file not found');
}
})
.catch(error => {
console.error('Error loading markdown:', error);
});
}
// 文档加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
// 从全局变量获取课程信息
if (window.appData) {
loadMarkdown(window.appData.course_id, window.appData.chapter_name, window.appData.lesson_name);
}
});

View File

@@ -292,13 +292,50 @@ function closeAddCourseModal() {
document.getElementById('add-course-modal').style.display = 'none';
}
// 显示删除课程确认弹窗
function showDeleteCourseConfirmation() {
if (!material_id) {
alert('无法删除课程未找到课程ID');
return;
}
if (confirm('确定要删除这个课程吗?此操作无法撤销!')) {
deleteCourse(material_id);
}
}
// 删除课程
function deleteCourse(courseId) {
fetch(`/materials/${courseId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
if (data.message) {
alert(data.message);
if (data.success) {
// 关闭侧边栏并刷新页面
closeCourseDetails();
location.reload();
}
}
})
.catch(error => {
console.error('删除课程时出错:', error);
alert('删除课程失败,请稍后再试!');
});
}
function onTeacherboardPageLoad(){
// 提交表单处理
document.getElementById('add-course-form').addEventListener('submit', function(event) {
event.preventDefault();
const courseName = document.getElementById('course-name').value;
const courseSelection = document.getElementById('course-selection').value;
const courseSelection = document.getElementById('course-selection').value; // 获取选择值
const coverImage = document.getElementById('cover-preview').src;
const courseDescription = document.getElementById('course-description').value;
// 构建发送的数据
@@ -312,7 +349,7 @@ document.getElementById('add-course-form').addEventListener('submit', function(e
// 如果选择了已有课程,可以通过 courseSelection 传递课程ID根据需要修改
if (courseSelection !== 'new') {
// 如果是修改已有课程,设置相关的章节信息或其他数据
data.chapters = ["Chapter 1", "Chapter 2"]; // 示例章节信息
data.chapters = ["Chapter 1", "Chapter 2"];
}
// 发送 POST 请求到 /create_material

View File

@@ -8,6 +8,7 @@
</style>
<link rel="stylesheet" href="/static/css/desktop.css">
<link rel="stylesheet" href="/static/css/chatbox_approve_icon.css">
<link rel="stylesheet" href="/static/css/helpTip.css">
<script>
document.cookie = "vscode-tkn=44edc269-6f88-46ab-9790-dc253f66ac36; path=/; SameSite=None; Secure";
</script>
@@ -140,9 +141,7 @@
</div>
</div>
<script src="/static/js/process_show_floating_window.js"></script>
<script src="/static/js/helpTip.js"></script>
<script src="/static/js/chatbox.js"></script>
<script>
@@ -193,7 +192,6 @@
// 使用 fetch 发送请求到 Flask 服务器,获取 session 信息
fetch('/get_session', {
method: 'GET',
@@ -210,7 +208,7 @@
console.error('Error fetching session:', error);
});
let lastiframe = null;
function OpenIframe(){
function OpenIframe(data){
// 等待1s再加载
setTimeout(() => {
// 在成功获取 session 后创建并插入 iframe
@@ -230,31 +228,6 @@
}
// 动态加载 Markdown 文件
function loadMarkdown(course_id, chapter_name, lesson_name) {
fetch(`/${course_id}-${chapter_name}-${lesson_name}-markdown`)
.then(response => response.json())
.then(data => {
if (data.html_url) {
document.getElementById('markdown-content').innerHTML = `<iframe id="markdown-content-iframe" src="${data.html_url}"style="width: 100%;height: 100%;"></iframe>`;
document.getElementById('markdown-content-iframe').addEventListener('load', function() {
// 在这里执行你想要的操作
console.log('Iframe has finished loading');
next_chapter();
});
} else {
console.error('Markdown file not found');
}
})
.catch(error => {
console.error('Error loading markdown:', error);
});
}
document.addEventListener('DOMContentLoaded', function() {
loadMarkdown('{{course_id}}','{{chapter_name}}','{{lesson_name}}');
});
// 侧边工具栏切换
const sidebarTools = document.getElementById('sidebarTools');
const toggleButton = document.getElementById('toggleButton');
@@ -270,5 +243,7 @@
});
</script>
<!-- 引入 Markdown 渲染脚本 -->
<script src="/static/js/render-desktop-markdown.js"></script>
</body>
</html>

View File

@@ -61,16 +61,26 @@
</head>
<body>
<div class="confirm-container">
<h1>加载历史数据确认</h1>
<p>您即将进入学习环境,是否需要加载您之前的对话历史记录和学习进度数据?</p>
<div class="btn-group">
<a href="{{ url_for('vscode.desktop', user_uuid=user_uuid, course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name, load_history='true') }}" class="btn btn-primary">
是,加载历史数据
</a>
<a href="{{ url_for('vscode.desktop', user_uuid=user_uuid, course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name, load_history='false') }}" class="btn btn-secondary">
否,重新开始
</a>
</div>
{% if is_course_finished %}
<h1>重新学习确认</h1>
<p>您已经完成了该课程的学习,是否要重新开始学习?</p>
<div class="btn-group">
<a href="{{ url_for('vscode.desktop', user_uuid=user_uuid, course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name, load_history='false') }}" class="btn btn-primary">
重新开始学习
</a>
</div>
{% else %}
<h1>加载历史数据确认</h1>
<p>您即将进入学习环境,是否需要加载您之前的对话历史记录和学习进度数据?</p>
<div class="btn-group">
<a href="{{ url_for('vscode.desktop', user_uuid=user_uuid, course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name, load_history='true') }}" class="btn btn-primary">
是,加载历史数据
</a>
<a href="{{ url_for('vscode.desktop', user_uuid=user_uuid, course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name, load_history='false') }}" class="btn btn-secondary">
否,重新开始
</a>
</div>
{% endif %}
</div>
</body>
</html>

View File

@@ -46,7 +46,7 @@
</div>
</div>
</div>
{% include 'foot.html' %}
{% include 'footer-brief.html' %}
</body>
<script>
var course_id = "{{course_id}}";

View File

@@ -4,6 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>华实学伴 - 专业的在线学习平台</title>
<script src="/static/cdnback/jquery.min.js"></script>
<link href="/static/cdnback/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="/static/cdnback/all.min.css">
<link rel="stylesheet" href="/static/css/dashboard.css">
@@ -13,7 +14,6 @@
</head>
<body>
{% include 'navbar.html' %} <!-- 引入navbar.html -->
{% include 'learning-path.html' %} <!-- 引入learning-path.html -->
<section class="search-section">
<div class="container">
<div class="row justify-content-center">
@@ -81,7 +81,7 @@
</div>
</div>
{% include 'foot.html' %}
{% include 'footer-brief.html' %}
<script src="/static/js/dashboard.js"></script>
<script>

View File

@@ -187,7 +187,7 @@
let lastIframe = null;
function OpenIframe(){
function OpenIframe(data){
// 在成功获取 session 后创建并插入 iframe
const iframe = document.createElement('iframe');
const div=document.getElementById('vscodeWeb')

View File

@@ -0,0 +1,11 @@
<link rel="stylesheet" href="/static/css/footer.css">
<footer class="hs-footer">
<div class="footer-main">
<div class="footer-bottom">
<div class="footer-bottom-right">
<span>© 2025 华实学伴. 保留所有权利</span>
<a href="https://beian.miit.gov.cn" target="_blank">沪ICP备2025142149号</a>
</div>
</div>
</footer>

View File

@@ -1,8 +1,9 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>课程选择主页</title>
<meta charset="UTF-8">
<title>课程选择主页</title>
<script src="/static/cdnback/jquery.min.js"></script>
<link href="/static/cdnback/bootstrap.min.css" rel="stylesheet">
@@ -12,6 +13,7 @@
<script src="/static/cdnback/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/static/css/index.css">
</head>
<body>
{% include 'navbar.html' %}
@@ -38,7 +40,7 @@
<h2>课程列表</h2>
<div class="course-cards" id="course-cards">
{% for course in courses_data %}
<!-- <div class="course-card" onclick="show_course_details('{{ course._id }}')">
<!-- <div class="course-card" onclick="show_course_details('{{ course._id }}')">
<img src="{{ course.image_url }}" alt="{{ course.course_name }}">
<h3>{{ course.name }}</h3>
<p>{{ course.description }}</p>
@@ -49,10 +51,9 @@
{% endif %}
</div> -->
<div class="col-md-6 col-lg-4">
<div class="col-md-6 col-lg-4">
<div class="course-card card h-100" onclick="openCourseProgress('{{course._id}}')">
<img src="{{course.image_url}}"
class="course-img" alt="课程封面">
<img src="{{course.image_url}}" class="course-img" alt="课程封面">
<div class="card-body d-flex flex-column">
<span class="course-category">算法设计</span>
<h5 class="course-title">{{course.name}}</h5>
@@ -62,11 +63,15 @@
<span class="course-rating"><i class="fas fa-star"></i> 4.7</span>
</div>
<div class="mt-auto d-grid gap-2 d-md-flex">
<button class="btn btn-view flex-fill" onclick="btn_view(event,'{{course._id}}')"><i class="far fa-eye me-1"></i> 课程</button>
<button class="btn btn-view flex-fill" onclick="btn_view(event,'{{course._id}}')"><i
class="far fa-eye me-1"></i> 课程</button>
{% if course._id in selected_courses %}
<button class="btn btn-process flex-fill selected-button" data-course-id="{{course._id}}">已选课</button>
<button class="btn btn-process flex-fill selected-button"
data-course-id="{{course._id}}">已选课</button>
{% else %}
<button class="btn btn-process flex-fill select-button" onclick="on_click_select_course(event)" data-course-id="{{course._id}}">选择课程</button>
<button class="btn btn-process flex-fill select-button"
onclick="on_click_select_course(event)"
data-course-id="{{course._id}}">选择课程</button>
{% endif %}
</div>
@@ -74,13 +79,13 @@
</div>
</div>
{% endfor %}
</div>
</div>
</main>
{% include 'foot.html' %}
{% include 'footer-brief.html' %}
</body>
<script>
window.appData = {
@@ -88,5 +93,6 @@
}
</script>
<script src="/static/js/index.js"></script>
</html>
<script src="/static/js/dashboard.js"></script>
</html>

View File

@@ -8,6 +8,7 @@
<link rel="stylesheet" href="/static/css/teacherboard.css">
<link rel="stylesheet" href="/static/css/dashboard.css">
<link rel="stylesheet" href="/static/css/lesson.css">
<link rel="stylesheet" href="/static/css/helpTip.css">
<link rel="stylesheet" href="/static/css/teacher_course_setting.css">
<link rel="stylesheet" href="/static/css/lesson_setting.css">
<link rel="stylesheet" href="/static/css/modelinput.css">
@@ -100,6 +101,7 @@
<script src="/static/js/teacherboard.js"></script>
<script src="/static/js/teacher_course_setting.js"></script>
<script src="/static/js/lesson_markdown.js"></script>
<script src="/static/js/helpTip.js"></script>
<script src="/static/js/lesson.js"></script>
<script>

View File

@@ -1,7 +1,6 @@
<link rel="stylesheet" href="/static/css/navbar.css">
<link rel="stylesheet" href="/static/cdnback/all.min.css">
<link rel="stylesheet" href="/static/css/dashboard.css">
<link rel="stylesheet" href="/static/css/navbar.css">
<header class="navbar">
<div class="logo">
<h1>华实学伴:教学练评一体的虚拟助教</h1>

View File

@@ -65,7 +65,7 @@
</div>
</ul>
<button class="add-chapter-btn" onclick="showInputForNewChapter()">新增章节</button>
<button class="delete-course-btn" onclick="showDeleteCourseConfirmation()">删除课程</button>
</div>
<!-- 编辑章节或课时弹窗 -->
@@ -90,9 +90,9 @@
<div class="cover-image-container">
<div id="cover-image" class="cover-image-placeholder">
<span class="plus-sign">+</span>
<input type="file" id="cover-image-input" style="display: none;" accept="image/*" />
<input type="file" id="cover-image-input" style="display: none;" accept="image/*" />
</div>
<img id="cover-preview" src="" alt="封面预览" style="display: none;" />
<img id="cover-preview" src="" alt="封面预览" style="display: none;" />
</div>
<form id="add-course-form">
@@ -100,8 +100,8 @@
<label for="course-selection">从课程创建或新建课程:</label>
<select id="course-selection">
<option value="new">新建课程</option>
{% for course in courses %}
<option value="{{ course.id }}">{{ course.name }}</option>
{% for course in materials %}
<option value="{{ course._id }}">{{ course.name }}</option>
{% endfor %}
</select>
<br><br>
@@ -121,6 +121,6 @@
<script src="/static/js/course_current.js"></script>
<script src="/static/js/teacherboard.js"></script>
<script src="/static/js/teacher_course_setting.js"></script>
{% include 'foot.html' %}
{% include 'footer-brief.html' %}
</body>
</html>

View File

@@ -14,17 +14,8 @@ bp = Blueprint("markdown", __name__)
def convert_md(course_id, chapter_name, lesson_name):
print(f"convert_md: {course_id}, {chapter_name}, {lesson_name}")
md_file = load_markdown_file(course_id, chapter_name, lesson_name)
# 配置Markdown解析器,启用数学公式支持
md = MarkdownIt()
md.use(texmath.texmath_plugin) # 添加数学公式插件
# 转换markdown为html包含公式标记
html = md.render(md_file)
# 包装样式时添加MathJax支持用于在浏览器中渲染公式
html_with_styles = wrap_with_styles(html)
# 保存HTML文件到static
html_output_path = os.path.join(current_app.config["STATIC_DIR"], f"{course_id}-{chapter_name}-{lesson_name}.html")
save_html(html_with_styles, html_output_path)
return jsonify({"html_url": f"/static/{course_id}-{chapter_name}-{lesson_name}.html"})
# 直接返回Markdown源文件内容,不进行服务器端渲染
return jsonify({"markdown_content": md_file})
# 提供静态文件访问
@bp.route("/static/<path:filename>")

View File

@@ -1,4 +1,5 @@
from flask import Blueprint, request, jsonify, current_app, session, render_template, session
from bson import ObjectId
from ..services.course_service import create_material, update_material, get_materials_by_teacher, load_material, get_materials_by_teacher_dict, add_material_chapter, add_material_chapter_lesson, delete_material_chapter_lesson, reorder_material_structure, rename_material_structure
from ..auth.decorators import require_role
from ..services.cos_service import upload_file
@@ -37,24 +38,60 @@ def create_new_material():
material_id = create_material(teacher_id, material_name, description, chapters, image_url)
return jsonify({"message": "教材创建成功", "material_id": material_id}), 201
@bp.route('/materials/<material_id>', methods=['GET'])
@bp.route('/materials/<material_id>', methods=['GET', 'PUT', 'DELETE'])
@require_role(roles="teacher")
def get_material(material_id):
if material_id is None:
return jsonify({"message": "教材名称不能为空"}), 400
material = load_material(material_id)
print(material)
return jsonify( material.model_dump()), 200
def handle_material(material_id):
@bp.route('/materials/<material_id>', methods=['PUT'])
@require_role(roles="teacher")
def update_existing_material(material_id):
data = request.get_json()
chapters = data.get('chapters')
if update_material(material_id, chapters):
return jsonify({"message": "教材更新成功"}), 200
return jsonify({"message": "教材未找到"}), 404
if request.method == 'GET':
if material_id is None:
return jsonify({"message": "教材名称不能为空"}), 400
material = load_material(material_id)
print(material)
return jsonify(material.model_dump()), 200
elif request.method == 'PUT':
data = request.get_json()
chapters = data.get('chapters')
if update_material(material_id, chapters):
return jsonify({"message": "教材更新成功"}), 200
else:
return jsonify({"message": "教材更新失败"}), 500
elif request.method == 'DELETE':
# 获取当前教师信息
teacher_uuid = session.get("user_uuid")
teacher_id = current_app.extensions["uuid2username"][teacher_uuid]
# 检查材料是否存在,并且是否为当前教师创建
mongo = current_app.extensions["mongo"]
print(f"尝试删除课程ID: {material_id}, 当前教师ID: {teacher_id}")
try:
material = mongo.db.materials.find_one({'_id': ObjectId(material_id)})
print(f"找到的材料: {material}")
if not material:
return jsonify({"message": "课程不存在", "success": False}), 404
# 验证是否为当前教师创建的课程
if material.get('teacher_id') != teacher_id:
return jsonify({"message": "权限不足,无法删除他人课程", "success": False}), 403
except Exception as e:
print(f"查询材料时出错: {e}")
return jsonify({"message": f"查询课程时出错: {str(e)}", "success": False}), 500
# 执行删除操作
try:
result = mongo.db.materials.delete_one({'_id': ObjectId(material_id), 'teacher_id': teacher_id})
print(f"删除操作结果: {result.deleted_count}")
except Exception as e:
print(f"删除材料时出错: {e}")
return jsonify({"message": f"删除课程时出错: {str(e)}", "success": False}), 500
if result.deleted_count > 0:
return jsonify({"message": "课程删除成功", "success": True}), 200
else:
return jsonify({"message": "删除失败", "success": False}), 500
@bp.route('/materials/addchapter/<material_id>', methods=['POST'])
@require_role(roles="teacher")

View File

@@ -6,6 +6,7 @@ from ..services.backboard_service import realtime_response
from ..extension_ase.ase_client.manager import ChatManager
import subprocess
from ..auth.decorators import require_role
from ..services.course_service import load_learning_progress
bp = Blueprint("vscode", __name__)
@@ -19,11 +20,14 @@ def desktop(user_uuid, course_id, chapter_name, lesson_name):
return redirect(url_for("auth.login"))
# 检查是否有 load_history 参数
load_history = request.args.get('load_history')
if load_history is None:
load_history_str = request.args.get('load_history')
if load_history_str is None:
# 如果没有参数,跳转到确认页面
return redirect(url_for("vscode.desktop_nouser", course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name))
# 将字符串转换为布尔值
load_history = load_history_str.lower() == 'true'
# 全局映射
user_id = uuid2username[user_uuid]
userid_recorder[f"{user_id}&{course_id}"] = session["user_uuid"]
@@ -65,46 +69,28 @@ def desktop(user_uuid, course_id, chapter_name, lesson_name):
chatmanager = ChatManager(restart=not load_history)
print(f"now user uuid {user_uuid}")
restart = not load_history
chatmanager = ChatManager(restart=restart)
current_app.extensions["user_uuid2chatmanager"][user_uuid] = chatmanager
# 如果restart为True删除mongo中的学习进度
if restart:
try:
mongo = current_app.extensions["mongo"]
mongo.db.learning_progress.delete_one({
"user_id": user_id,
"material_id": course_id,
"chapter_name": chapter_name,
"lesson_name": lesson_name
})
current_app.logger.info(f"删除学习进度成功: user_id={user_id}, course_id={course_id}, chapter={chapter_name}, lesson={lesson_name}")
except Exception as e:
current_app.logger.error(f"删除学习进度失败: {str(e)}")
code_server_port = 10000 + int(uuid.uuid4().int % 10000)
# chatmanager.start_code_server(user_uuid, user_id, path_dir, code_server_port)
caddy_conf = f"""
handle_path /vsc{user_id}/* {{
reverse_proxy localhost:{code_server_port}
}}
"""
caddy_config_path = "/etc/caddy/Caddyfile"
with open(caddy_config_path, "r") as f:
lines = f.readlines()
pattern = re.compile(
r'handle_path\s+/vsc' + re.escape(user_id) + r'/\* {.*?reverse_proxy.*?}',
re.DOTALL
)
for i in range(len(lines)):
if (lines[i].strip()==''): lines[i]=''
content = "".join(lines)
if pattern.search(content):
new_content = pattern.sub('', content)
lines = new_content.splitlines(keepends=True)
if len(lines) >= 2:
insert_position = len(lines) - 2
else:
insert_position = len(lines)
if caddy_conf[-1] not in ['\n', '\r']:
caddy_conf += '\n'
lines.insert(insert_position, caddy_conf)
with open(caddy_config_path, "w") as f:
f.writelines(lines)
try:
subprocess.run(["sudo", "caddy", "reload", "--config", "/etc/caddy/Caddyfile"])
except subprocess.CalledProcessError as e:
print(f"Error reload caddy {e}")
cfg = current_app.config["VSCODE_WEB_PATH"]
path_for_vscode = path_dir
@@ -147,13 +133,33 @@ def desktop(user_uuid, course_id, chapter_name, lesson_name):
def desktop_nouser(course_id, chapter_name, lesson_name):
if "user_uuid" not in session:
return redirect(url_for("auth.login")) # 如果你有 auth 蓝图
user_uuid = session["user_uuid"]
uuid2username = current_app.extensions["uuid2username"]
user_id = uuid2username[user_uuid]
# 检查是否有学习记录
progress_result = load_learning_progress(user_id, course_id, chapter_name, lesson_name)
if not progress_result["exists"]:
# 没有学习记录,直接跳转到学习页面,不显示确认加载历史的页面
return redirect(url_for("vscode.desktop", user_uuid=user_uuid, course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name, load_history="false"))
# 获取学习记录数据
progress_data = progress_result["data"]
chapter_chain_now = progress_data.get("chapter_chain_now", -1)
chapter_chain_length = progress_data.get("chapter_chain_length", 0)
# 检查是否已经学完所有章节
is_course_finished = chapter_chain_now >= chapter_chain_length - 1
return render_template(
"confirm_load_history.html",
user_uuid=user_uuid,
course_id=course_id,
chapter_name=chapter_name,
lesson_name=lesson_name
lesson_name=lesson_name,
is_course_finished=is_course_finished
)
@bp.route("/vscode_data", methods=["POST"])

View File

@@ -5,7 +5,7 @@ api_key = sk-aMpnWklN2IbsK44d1kNpy6YOP9bk1pdPJjFeEmbb0a5ytEFf
model=gpt-4.1-nano
[VSCODE_WEB]
url = https://hsamooc.cn
url = https://hsamooc.com
[CODE_LIKE]
url = /vsc-like
#http://asengine.net:8282
@@ -27,6 +27,6 @@ bucket = hsamooc-cdn-1374354408
region = ap-guangzhou
[ASE_ENGINE]
url = https://test.asengine.net
namespace = /socket.io/7100eebf7a909e1ee3f4e06766f512f0358ecb6ac51d5434c17d31dd70890dc1
url_token = 7100eebf7a909e1ee3f4e06766f512f0358ecb6ac51d5434c17d31dd70890dc1
url = https://asengine.net
namespace = /socket.io/afe58a9e4c03e10fae6fae5985e8adde23a49635
url_token = afe58a9e4c03e10fae6fae5985e8adde23a49635

View File

@@ -0,0 +1 @@
{"username": "_10235101560"}

View File

@@ -0,0 +1 @@
{"username": "shanks"}

View File

@@ -0,0 +1 @@
{"username": "ts88"}

View File

@@ -0,0 +1 @@
{"username": "xuans"}

View File

@@ -0,0 +1 @@
{"username": "xuans_"}

View File

@@ -1,5 +1,209 @@
import eventlet
eventlet.monkey_patch() # 进行猴子补丁操作
import logging
# 配置 eventlet 日志,抑制 IOClosed 等错误日志
logging.getLogger('eventlet.hubs').setLevel(logging.CRITICAL)
logging.getLogger('eventlet.greenio').setLevel(logging.CRITICAL)
# 进行猴子补丁操作
eventlet.monkey_patch()
# 配置 eventlet 以更优雅地处理错误,避免疯狂报错
try:
import eventlet
import traceback
# 1. 首先,禁用 eventlet 的调试日志,减少输出
import logging
logging.getLogger('eventlet').setLevel(logging.CRITICAL)
logging.getLogger('socketio').setLevel(logging.CRITICAL)
logging.getLogger('werkzeug').setLevel(logging.CRITICAL)
# 2. 配置 eventlet 相关设置移除了不存在的debug属性
# 3. 避免重复打印相同错误的机制
seen_errors = set()
max_error_logs = 5 # 每个错误最多打印5次
error_counts = {}
def is_duplicate_error(e):
"""检查是否为重复错误"""
error_key = f"{type(e).__name__}: {e}"
if error_key in seen_errors:
error_counts[error_key] = error_counts.get(error_key, 0) + 1
if error_counts[error_key] > max_error_logs:
return True
else:
seen_errors.add(error_key)
error_counts[error_key] = 1
return False
# 4. 只修改关键的 greenio 方法,确保在致命错误时彻底关闭连接
# 增强 socketio 错误处理,确保不会因为单个连接错误而宕机
try:
from flask_socketio import SocketIO
# 获取当前 socketio 实例并配置错误处理
import sys
original_excepthook = sys.excepthook
def custom_excepthook(exc_type, exc_value, exc_traceback):
"""全局异常钩子,捕获所有未处理的异常"""
if exc_type.__name__ in ['OSError', 'IOError'] and 'Bad file descriptor' in str(exc_value):
# 处理 Bad file descriptor 错误,不导致服务器宕机
if not is_duplicate_error(exc_value):
print(f"[Global Error Handler] {exc_type.__name__}: {exc_value}")
print("[Traceback]")
traceback.print_exception(exc_type, exc_value, exc_traceback)
# 不调用原始的 excepthook防止服务器宕机
return
# 其他异常调用原始的 excepthook
original_excepthook(exc_type, exc_value, exc_traceback)
# 设置全局异常钩子
sys.excepthook = custom_excepthook
except Exception as e:
# 如果修改失败,忽略错误
print(f"[Global Excepthook Patch Error] {e}")
from eventlet import greenio
# 保存并替换原始的 greenio 方法
if hasattr(greenio.base.GreenSocket, '_recv_loop'):
original_recv_loop = greenio.base.GreenSocket._recv_loop
def custom_recv_loop(self, recv_func, recv_args, *args, **kwargs):
try:
return original_recv_loop(self, recv_func, recv_args, *args, **kwargs)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet IO Error] _recv_loop: {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底关闭连接,不再继续处理
try:
self.close()
except Exception:
pass
return b''
greenio.base.GreenSocket._recv_loop = custom_recv_loop
if hasattr(greenio.base.GreenSocket, 'recv_into'):
original_recv_into = greenio.base.GreenSocket.recv_into
def custom_recv_into(self, buffer, nbytes=0, flags=0):
try:
return original_recv_into(self, buffer, nbytes, flags)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet IO Error] recv_into: {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底关闭连接,不再继续处理
try:
self.close()
except Exception:
pass
return 0
greenio.base.GreenSocket.recv_into = custom_recv_into
if hasattr(greenio.base.GreenSocket, '_send_loop'):
original_send_loop = greenio.base.GreenSocket._send_loop
def custom_send_loop(self, send_func, data, *args, **kwargs):
try:
return original_send_loop(self, send_func, data, *args, **kwargs)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet IO Error] _send_loop: {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底关闭连接,不再继续处理
try:
self.close()
except Exception:
pass
return 0
greenio.base.GreenSocket._send_loop = custom_send_loop
if hasattr(greenio.base.GreenSocket, 'send'):
original_send = greenio.base.GreenSocket.send
def custom_send(self, data, flags=0):
try:
return original_send(self, data, flags)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet IO Error] send: {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底关闭连接,不再继续处理
try:
self.close()
except Exception:
pass
return 0
greenio.base.GreenSocket.send = custom_send
# 5. 处理 WSGI 中的错误,确保彻底清理
try:
import eventlet.wsgi
if hasattr(eventlet.wsgi.HttpProtocol, 'handle_one_request'):
original_wsgi_handle_one_request = eventlet.wsgi.HttpProtocol.handle_one_request
def custom_wsgi_handle_one_request(self):
try:
return original_wsgi_handle_one_request(self)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet WSGI Request Error] {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底清理连接,不再继续
try:
self.rfile.close()
self.wfile.close()
self.finish()
except Exception:
pass
return
eventlet.wsgi.HttpProtocol.handle_one_request = custom_wsgi_handle_one_request
if hasattr(eventlet.wsgi.HttpProtocol, 'handle_one_response'):
original_wsgi_handle_one_response = eventlet.wsgi.HttpProtocol.handle_one_response
def custom_wsgi_handle_one_response(self):
try:
return original_wsgi_handle_one_response(self)
except Exception as e:
if not is_duplicate_error(e):
print(f"[Eventlet WSGI Response Error] {type(e).__name__}: {e}")
print("[Traceback]")
traceback.print_exc()
# 彻底清理连接,不再继续
try:
self.rfile.close()
self.wfile.close()
self.finish()
except Exception:
pass
return
eventlet.wsgi.HttpProtocol.handle_one_response = custom_wsgi_handle_one_response
except Exception as e:
# 如果修改失败,忽略错误
print(f"[WSGI Patch Error] {e}")
print("[Eventlet Error Handling] Configured to handle errors gracefully, avoiding duplicate logs")
except Exception as e:
# 如果修改失败,打印错误但继续运行
print(f"[Eventlet Patch Initialization Error] {e}")
traceback.print_exc()
from flask import Flask
from .views.routes import main_bp
from .views.file import file_bp

View File

@@ -13,4 +13,5 @@ class Config:
# 自定义其他全局配置
ROOT_WORKSPACE_PATH = GLOBAL_CONFIG['Global']['ROOT_WORKSPACE_PATH']
DEBUG = GLOBAL_CONFIG['Global'].getboolean('DEBUG', False)

View File

@@ -3,12 +3,12 @@ from flask_socketio import SocketIO
from .config import Config
# 初始化扩展
cors = CORS()
socketio = SocketIO(path='vsc-like-ws',cors_allowed_origins="*",max_payload_size=5242880, async_mode="eventlet") # 不直接传 app
socketio = SocketIO(path='vsc-like-ws',cors_allowed_origins="*",max_payload_size=5242880, async_mode="eventlet",always_connect=False) # 不直接传 app
session_paths = {}
def init_extensions(app):
cors.init_app(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)
socketio.init_app(app, cors_allowed_origins="*", max_payload_size=5242880, async_mode="eventlet")
socketio.init_app(app, cors_allowed_origins="*", max_payload_size=5242880, async_mode="eventlet",always_connect=False)
app.extensions["session_paths"] = session_paths
def register_namespaces(app):

View File

@@ -29,53 +29,122 @@ terminal_bp = Blueprint('terminal', __name__, url_prefix='/vsc-like')
def set_winsize(fd, row, col, xpix=0, ypix=0):
winsize = struct.pack("HHHH", row, col, xpix, ypix)
fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
try:
winsize = struct.pack("HHHH", row, col, xpix, ypix)
fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
except (OSError, IOError):
# File descriptor closed or invalid, do nothing
pass
def read_and_forward_pty_output(fd=None, pid=None, room_id=None,namespace=None):
def read_and_forward_pty_output(fd=None, pid=None, room_id=None, namespace=None):
"""
read data on pty master from the pty slave, and emit to the web terminal visitor
"""
max_read_bytes = 1024 * 20
timeout=0.1
while True:
socketio.sleep(timeout)
timeout=min(timeout*2, 0.4)
# using flask default web server, or uwsgi production web server
# when the child process is terminated, it will not disappear from linux process list
# and keep staying as a zombie process until the parent exits.
try:
child_process = psutil.Process(pid)
except psutil.NoSuchProcess as err:
return
if child_process.status() not in ('running', 'sleeping'):
return
if fd:
timeout_sec = 0
(data_ready, _, _) = select.select([fd], [], [], timeout_sec)
if data_ready:
# output = os.read(fd, max_read_bytes).decode('ascii')
timeout=0.1
# 初始超时时间设置为较短值,确保响应迅速
timeout = 0.05
# 最大超时时间,避免太频繁的检查
max_timeout = 0.5
# 成功读取数据后的重置超时时间
reset_timeout = 0.05
try:
while True:
# 等待一段时间减少CPU占用
socketio.sleep(timeout)
# 使用指数退避算法调整超时时间,但不超过最大值
timeout = min(timeout * 1.5, max_timeout)
# 检查子进程状态
try:
child_process = psutil.Process(pid)
except psutil.NoSuchProcess:
# 进程已终止,清理僵尸进程
try:
output = os.read(fd, max_read_bytes).decode()
except Exception as err:
output = """
***AQUI WEB TERM ERR***
{}
***********************
""".format(err)
# the key for different visitor to get different terminal (instead of mixing up)
# is to let the background task push pty response to each one's own (default) ROOM!
namespace.emit("pty_output", {"output": output}, room=room_id)
os.waitpid(pid, os.WNOHANG)
except Exception:
pass
return
# 检查进程状态,如果不是运行或睡眠状态,则退出
if child_process.status() not in ('running', 'sleeping'):
try:
# 等待进程终止
child_process.wait(timeout=1)
except Exception:
try:
os.waitpid(pid, os.WNOHANG)
except Exception:
pass
return
# 如果文件描述符有效,尝试读取数据
if fd:
try:
# 使用非阻塞select检查是否有数据可读
(data_ready, _, _) = select.select([fd], [], [], 0)
if data_ready:
# 有数据可读,重置超时时间
timeout = reset_timeout
try:
# 读取数据
output = os.read(fd, max_read_bytes).decode()
except (OSError, IOError, EOFError):
# 文件描述符已关闭或其他IO错误优雅退出
return
except UnicodeDecodeError as err:
# 处理编码错误
output = f"""
***AQUI WEB TERM ERR***
Unicode decode error: {err}
***********************
"""
# 发送数据到客户端
try:
namespace.emit("pty_output", {"output": output}, room=room_id)
except Exception:
# 如果发送失败,客户端可能已断开连接,退出
return
except (OSError, IOError):
# 文件描述符无效,优雅退出
return
except Exception as e:
# 捕获任何其他未预期的异常,防止服务器崩溃
current_app.logger.error(f"Unexpected error in read_and_forward_pty_output: {e}")
finally:
# 清理文件描述符
if fd:
try:
os.close(fd)
except Exception:
pass
class VSCLikeNameSpace(Namespace):
def on_connect(self):
"""new client connected"""
if session.get('terminal_config', {}).get('child_pid', None):
print(session['terminal_config']['child_pid'])
# already started child process, don't start another
return
# 确保terminal_config存在于session中
if 'terminal_config' not in session:
session['terminal_config'] = TERM_INIT_CONFIG.copy()
session.modified = True
terminal_config = session['terminal_config']
# 检查是否已经有运行中的子进程
if terminal_config.get('child_pid'):
try:
# 验证进程是否真的存在
child_process = psutil.Process(terminal_config['child_pid'])
if child_process.status() in ('running', 'sleeping'):
current_app.logger.debug("Already running child process: {}".format(terminal_config['child_pid']))
return
except psutil.NoSuchProcess:
# 进程不存在,清理配置
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
# create child process attached to a pty we can read from and write to
(child_pid, fd) = pty.fork()
@@ -84,87 +153,210 @@ class VSCLikeNameSpace(Namespace):
# this is the child process fork.
# anything printed here will show up in the pty, including the output
# of this subprocess
# subprocess.run('bash')
term_type = session.get('terminal_config').get('term_type')
path = TERM_INIT_CONFIG.get('client_path', {}).get(term_type, None)
if not path:
print("Can't locate {} binary, exit".format(term_type))
disconnect()
if term_type == 'telnet':
# switch to the right location of your telnet binary (example comes from OSX which got telnet from brew)
# or you can also make work like auto-detection, or manually but configurable
os.execl(path, 'telnet', '-l', session['terminal_config']['username'],
session['terminal_config']['domain'], '{}'.format(session['terminal_config']['port']))
elif term_type == 'ssh':
os.execl(path,'ssh', '-p','22',
#'{}'.format(session['terminal_config']['port']),
'{}@{}'.format(session['terminal_config']['username'], session['terminal_config']['domain']))
else:
current_app.logger.debug("wrong term type {}".format(term_type))
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
try:
# 获取终端配置
terminal_config = session.get('terminal_config', {})
term_type = terminal_config.get('term_type')
if not term_type:
print("Terminal type not specified, exit")
os._exit(1)
path = TERM_INIT_CONFIG.get('client_path', {}).get(term_type, None)
if not path or not os.path.exists(path):
print("Can't locate {} binary at {}, exit".format(term_type, path))
os._exit(1)
# 获取连接参数
username = terminal_config.get('username')
domain = terminal_config.get('domain', TERM_INIT_CONFIG['domain'])
port = terminal_config.get('port')
if not username or not domain:
print("Missing required connection parameters, exit")
os._exit(1)
if term_type == 'telnet':
# 使用telnet连接
if not port:
print("Port not specified for telnet, exit")
os._exit(1)
os.execl(path, 'telnet', '-l', username, domain, str(port))
elif term_type == 'ssh':
# 使用ssh连接
ssh_port = port if port else 22 # 默认端口22
os.execl(path, 'ssh', '-p', str(ssh_port), '{}@{}'.format(username, domain))
else:
print("Wrong term type {}, exit".format(term_type))
os._exit(1)
except Exception as e:
print("Error in child process: {}", str(e))
os._exit(1)
else:
session['terminal_config']['fd'] = fd
session['terminal_config']['child_pid'] = child_pid
session['terminal_config']['room_id'] = rooms()[0]
# 更新会话配置
terminal_config['fd'] = fd
terminal_config['child_pid'] = child_pid
terminal_config['room_id'] = rooms()[0]
session.modified = True
# 设置初始窗口大小
set_winsize(fd, 50, 50)
# 记录日志
current_app.logger.debug("child pid = {}".format(child_pid))
current_app.logger.debug("rooms of this session = {}".format(rooms()))
socketio.start_background_task(read_and_forward_pty_output, fd, child_pid, rooms()[0],self)
# 启动后台任务读取pty输出
socketio.start_background_task(read_and_forward_pty_output, fd, child_pid, rooms()[0], self)
current_app.logger.debug("background task running")
# print(session)
def on_pty_input(self, data):
"""write to the child pty, which now is the ssh process from this machine to the 'domain' configured
"""
print(f"get data {data}")
# 输入验证
if not isinstance(data, dict):
current_app.logger.error("Invalid input format: expected dictionary")
return
input_data = data.get("input")
if not isinstance(input_data, str):
current_app.logger.error("Invalid input data: expected string")
return
# 限制输入长度,防止缓冲区溢出
if len(input_data) > 1024:
input_data = input_data[:1024]
current_app.logger.warning("Input truncated due to length")
try:
child_process = psutil.Process(session.get('terminal_config').get('child_pid'))
except psutil.NoSuchProcess as err:
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
if child_process.status() not in ('running', 'sleeping'):
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
# print(session)
# print(data, 'from input')
fd = session.get('terminal_config').get('fd')
if fd:
# print("writing to ptd: %s" % data["input"])
# os.write(fd, data["input"].encode('ascii'))
os.write(fd, data["input"].encode())
terminal_config = session.get('terminal_config', {})
child_pid = terminal_config.get('child_pid')
if not child_pid:
current_app.logger.error("No child process found")
return
child_process = psutil.Process(child_pid)
if child_process.status() not in ('running', 'sleeping'):
current_app.logger.debug("Child process not running, cleaning up")
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
return
fd = terminal_config.get('fd')
if fd:
try:
os.write(fd, input_data.encode())
except (OSError, IOError) as e:
# File descriptor closed or invalid, clean up
current_app.logger.debug(f"Error writing to file descriptor: {e}")
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
except psutil.NoSuchProcess:
# Process no longer exists, clean up
terminal_config = session.get('terminal_config', {})
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
except Exception as e:
current_app.logger.error(f"Error in pty_input handling: {e}")
def on_resize(self, data):
# 输入验证
if not isinstance(data, dict):
current_app.logger.error("Invalid resize data format: expected dictionary")
return
rows = data.get("rows")
cols = data.get("cols")
# 验证行和列的值是否为正整数
if not (isinstance(rows, int) and isinstance(cols, int)):
current_app.logger.error("Invalid resize dimensions: expected integers")
return
# 限制窗口大小范围,防止异常值
if rows <= 0 or rows > 1000 or cols <= 0 or cols > 1000:
current_app.logger.error(f"Invalid resize dimensions: {rows}x{cols} (out of range)")
return
try:
child_process = psutil.Process(session.get('terminal_config').get('child_pid'))
except psutil.NoSuchProcess as err:
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
if child_process.status() not in ('running', 'sleeping'):
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
fd = session.get('terminal_config').get('fd')
if fd:
set_winsize(fd, data["rows"], data["cols"])
terminal_config = session.get('terminal_config', {})
child_pid = terminal_config.get('child_pid')
if not child_pid:
current_app.logger.error("No child process found for resize")
return
# 检查子进程是否存在且运行中
child_process = psutil.Process(child_pid)
if child_process.status() not in ('running', 'sleeping'):
current_app.logger.debug("Child process not running, cleaning up resize")
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
return
fd = terminal_config.get('fd')
if fd:
# 检查文件描述符是否有效
try:
os.fstat(fd)
set_winsize(fd, rows, cols)
except (OSError, IOError) as e:
# 文件描述符无效,清理资源
current_app.logger.debug(f"Error resizing terminal: {e}")
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
except psutil.NoSuchProcess:
# 进程不存在,清理资源
terminal_config = session.get('terminal_config', {})
terminal_config.pop('child_pid', None)
terminal_config.pop('fd', None)
session.modified = True
except Exception as e:
current_app.logger.error(f"Error in resize handling: {e}")
def on_disconnect(self):
try:
child_process = psutil.Process(session.get('terminal_config', {}).get('child_pid'))
except psutil.NoSuchProcess as err:
disconnect()
session['terminal_config'] = TERM_INIT_CONFIG
return
if child_process.status() in ('running', 'sleeping'):
# if visitor just close the browser tab then left alone the pty here
# it should be terminated by the parent process after
child_process.terminate()
current_app.logger.debug('user left the pty alone, terminated')
terminal_config = session.get('terminal_config', {})
child_pid = terminal_config.get('child_pid')
fd = terminal_config.get('fd')
# 先关闭文件描述符,避免其他操作尝试使用无效的文件描述符
if fd:
try:
os.close(fd)
except Exception:
pass
if child_pid:
try:
child_process = psutil.Process(child_pid)
if child_process.status() in ('running', 'sleeping'):
# if visitor just close the browser tab then left alone the pty here
# it should be terminated by the parent process after
child_process.terminate()
# Wait for the process to terminate and collect its exit status
child_process.wait(timeout=2)
current_app.logger.debug('user left the pty alone, terminated and waited')
except psutil.NoSuchProcess as err:
# Process already terminated, try to wait anyway to clean up any zombie
try:
os.waitpid(child_pid, os.WNOHANG)
except Exception:
pass
except psutil.TimeoutExpired:
# If process didn't terminate in time, kill it forcefully
try:
child_process.kill()
child_process.wait(timeout=1)
except Exception:
pass
except Exception as err:
current_app.logger.error(f'Error terminating process: {err}')
# Reset session config
session['terminal_config'] = TERM_INIT_CONFIG
current_app.logger.debug('Client disconnected')

View File

@@ -1,5 +1,5 @@
import os
import subprocess
from eventlet.green import subprocess
from flask import Blueprint, request, jsonify, current_app, render_template, session
from ..services.file_service import get_file_tree, load_config
@@ -42,32 +42,34 @@ def vsc_like(user_uuid, user_id, course_id, chapter_name, lesson_name, port):
subprocess.run(["sudo", "chown", "-R", user_id, user_root]) # 设置目录权限为新用户
except subprocess.CalledProcessError as e:
print(f"Error creating user {user_id}: {e}")
# 用户可能已经存在,这是正常情况,继续执行
print(f"Useradd command returned non-zero exit status, this is expected if user already exists: {e}")
try:
# 使用 sudo 执行 mkdir 命令来创建目录
subprocess.run(["sudo", "-u", user_id, "mkdir", "-p", path], check=True)
subprocess.run(["sudo", "-u", user_id, "mkdir", "-p", f'{user_root}/.ssh'], check=True)
subprocess.run(["sudo", "-u", user_id, "mkdir", "-p", path], check=current_app.config['DEBUG'])
subprocess.run(["sudo", "-u", user_id, "mkdir", "-p", f'{user_root}/.ssh'], check=current_app.config['DEBUG'])
flask_pub_key = "/home/flask/.ssh/id_ed25519.pub"
subprocess.run(["sudo", "cp", flask_pub_key, f"{user_root}/.ssh/authorized_keys"], check=True)
subprocess.run(["sudo", "chmod", "700", f"{user_root}/.ssh"], check=True)
subprocess.run(["sudo", "chmod", "600", f"{user_root}/.ssh/authorized_keys"], check=True)
subprocess.run(["sudo", "cp", flask_pub_key, f"{user_root}/.ssh/authorized_keys"], check=current_app.config['DEBUG'])
subprocess.run(["sudo", "chmod", "700", f"{user_root}/.ssh"], check=current_app.config['DEBUG'])
subprocess.run(["sudo", "chmod", "600", f"{user_root}/.ssh/authorized_keys"], check=current_app.config['DEBUG'])
print(f"Directory {path} created successfully for user {user_id}")
except subprocess.CalledProcessError as e:
print(f"Error creating directory {path} details {str(e)}")
try:#使用sudo创建shared_group
subprocess.run(["sudo", "groupadd", f"shared_group_{user_id}"], check=True)
subprocess.run(["sudo", "groupadd", f"shared_group_{user_id}"], check=current_app.config['DEBUG'])
except subprocess.CalledProcessError as e:
print(f"Error creating shared_group: {e}")
# 组可能已经存在,这是正常情况,继续执行
print(f"Groupadd command returned non-zero exit status, this is expected if group already exists: {e}")
try:#使用sudo将user_id加入shared_group
subprocess.run(["sudo", "usermod", "-a", "-G", f"shared_group_{user_id}", user_id], check=True)
subprocess.run(["sudo", "usermod", "-a", "-G", f"shared_group_{user_id}", user_id], check=current_app.config['DEBUG'])
# 自己也加入
subprocess.run(["sudo", "usermod", "-a", "-G", f"shared_group_{user_id}", 'flask'], check=True)
subprocess.run(["sudo", "usermod", "-a", "-G", f"shared_group_{user_id}", 'flask'], check=current_app.config['DEBUG'])
except subprocess.CalledProcessError as e:
print(f"Error adding user {user_id} to shared_group: {e}")
try:
subprocess.run(["sudo", "chown", "-R", f"flask:shared_group_{user_id}", path], check=True)
subprocess.run(["sudo", "chmod", "-R", "755", user_root], check=True)
subprocess.run(["sudo", "chmod", "-R", "775", path], check=True)
subprocess.run(["sudo", "chown", "-R", f"flask:shared_group_{user_id}", path], check=current_app.config['DEBUG'])
subprocess.run(["sudo", "chmod", "-R", "755", user_root], check=current_app.config['DEBUG'])
subprocess.run(["sudo", "chmod", "-R", "775", path], check=current_app.config['DEBUG'])
except subprocess.CalledProcessError as e:
print(f"Error changing directory {path} to shared_group_{user_id}: {e}")

View File

@@ -1,3 +1,4 @@
[Global]
SECRET_KEY = cakebaker
ROOT_WORKSPACE_PATH = /home
DEBUG = False

View File

@@ -1,5 +1,12 @@
from app import create_app
from app.extensions import socketio
import logging
# 配置日志减少eventlet的调试日志
logging.getLogger('eventlet').setLevel(logging.ERROR)
logging.getLogger('socketio').setLevel(logging.ERROR)
logging.getLogger('werkzeug').setLevel(logging.ERROR)
app = create_app()
if __name__ == '__main__':
@@ -9,4 +16,5 @@ if __name__ == '__main__':
port=5200,
debug=False, # 开发期打开
allow_unsafe_werkzeug=True, # 避免 dev server 的安全限制提示
)
log_output=False # 禁用详细输出
)

View File

@@ -4,17 +4,17 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cloud IDE</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs/editor/editor.main.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.1/socket.io.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/xterm/5.5.0/xterm.css" />
<link rel="stylesheet" href="/static/cdnback/css/editor/editor.main.css">
<script src="/static/cdnback/socket.io.min.js"></script>
<link rel="stylesheet" href="/static/cdnback/all.min.css">
<link rel="stylesheet" href="/static/cdnback/css/xterm.css" />
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/xterm/5.5.0/xterm.js"></script> -->
<script src="https://unpkg.com/xterm@3.6.0/dist/xterm.js"></script>
<script src="https://unpkg.com/xterm@3.6.0/dist/addons/fit/fit.js"></script>
<script src="https://unpkg.com/xterm@3.6.0/dist/addons/webLinks/webLinks.js"></script>
<script src="https://unpkg.com/xterm@3.6.0/dist/addons/fullscreen/fullscreen.js"></script>
<script src="https://unpkg.com/xterm@3.6.0/dist/addons/search/search.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<script src="/static/cdnback/js/xterm.js"></script>
<script src="/static/cdnback/js/addons/fit/fit.js"></script>
<script src="/static/cdnback/js/addons/webLinks/webLinks.js"></script>
<script src="/static/cdnback/js/addons/fullscreen/fullscreen.js"></script>
<script src="/static/cdnback/js/addons/search/search.js"></script>
<link rel="stylesheet" href="/static/cdnback/all.min.css">
<link rel="stylesheet" href="/vsc-like/static/css/index.css">
<link rel="stylesheet" href="/vsc-like/static/css/notification.css">
@@ -61,7 +61,7 @@
</div>
<div id="notificationsContainer"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs/loader.js"></script>
<script src="/static/cdnback/js/monaco-editor/0.34.0/min/vs/loader.js"></script>
<script src="/vsc-like/static/js/code-like-extension.js"></script>
<script src="/vsc-like/static/js/file.js"></script>
<script src="/vsc-like/static/js/terminal.js"></script>
@@ -161,7 +161,7 @@
// saveFile
if (saveTimeout) clearTimeout(saveTimeout);
saveTimeout = setTimeout(() => {
postSaveFile(selectedItem.path+'/'+selectedItem.name, editor.getValue());
postSaveFile(filePath, editor.getValue());
}, 5000); // 5000ms = 5秒
});

69
et --hard HEAD@{1} Normal file
View File

@@ -0,0 +1,69 @@
68493d6a (HEAD -> main, origin/main) HEAD@{0}: pull origin main: Fast-forward
0852e121 HEAD@{1}: reset: moving to HEAD
0852e121 HEAD@{2}: commit: cdn fix more
7dc4714a HEAD@{3}: commit: index style
9dc81b14 (origin/feature/paste_detecte_new, feature/paste_detecte_new) HEAD@{4}: merge feature/paste_detecte_new: Fast-forward
7862647b HEAD@{5}: checkout: moving from feature/paste_detecte_new to main
9dc81b14 (origin/feature/paste_detecte_new, feature/paste_detecte_new) HEAD@{6}: commit (merge): Merge branch 'main' into feature/paste_detecte_new
0cf1896b HEAD@{7}: checkout: moving from main to feature/paste_detecte_new
7862647b HEAD@{8}: commit: style fix
6b9c8e9e HEAD@{9}: commit: cdn change to local and use markdown and style change
33844786 HEAD@{10}: commit: use markdown to edit
ce88ae64 HEAD@{11}: commit: use queue to allow send vscode_ws when it is none
6c38e906 HEAD@{12}: pull: Fast-forward
9759c93a HEAD@{13}: commit: fix funciton response
ecf19f49 HEAD@{14}: commit: fix function double promlem
f5d50772 HEAD@{15}: commit: function call can be expire
4a390adb HEAD@{16}: commit: fix style bug
960d1f1d HEAD@{17}: commit: style fix
c73ea447 HEAD@{18}: commit: fix index
33bf569f HEAD@{19}: commit: fix nextchapter bug
b921bda4 HEAD@{20}: commit: auto get domain
9921848d HEAD@{21}: commit: remove prefix of http url
4d81aef8 HEAD@{22}: commit (merge): Merge branch 'feature/paste_deteced'
8fe5ee16 HEAD@{23}: checkout: moving from feature/paste_deteced to main
9ce212e9 (origin/feature/paste_deteced, feature/paste_deteced) HEAD@{24}: checkout: moving from main to feature/paste_deteced
8fe5ee16 HEAD@{25}: commit (merge): 准备合并main
908d5915 HEAD@{26}: checkout: moving from syt to main
57d8ac32 (origin/syt, syt) HEAD@{27}: checkout: moving from main to syt
908d5915 HEAD@{28}: commit: ready
02b12791 HEAD@{29}: checkout: moving from syt to main
57d8ac32 (origin/syt, syt) HEAD@{30}: checkout: moving from main to syt
02b12791 HEAD@{31}: pull: Fast-forward
7d861e34 (origin/zrz) HEAD@{32}: checkout: moving from syt to main
57d8ac32 (origin/syt, syt) HEAD@{33}: commit: first
0196f37e HEAD@{34}: pull: Merge made by the 'ort' strategy.
57eb1197 HEAD@{35}: commit: ok
382f2006 HEAD@{36}: checkout: moving from main to syt
7d861e34 (origin/zrz) HEAD@{37}: commit (merge): Merge branch 'main' of https://gitee.com/CakeCN/code-agent
5f8f6c94 HEAD@{38}: commit: many ok
e24aa12e HEAD@{39}: commit: ready to process
6766ca85 HEAD@{40}: commit (merge): Merge branch 'feature/voice_send'
3c9c7553 HEAD@{41}: checkout: moving from feature/voice_send to main
58a95e9f (origin/feature/voice_send, feature/voice_send) HEAD@{42}: commit: ready merge to main
79125ffc HEAD@{43}: commit: change .cn to .com
2f9bc7df HEAD@{44}: checkout: moving from main to feature/voice_send
3c9c7553 HEAD@{45}: reset: moving to HEAD
3c9c7553 HEAD@{46}: checkout: moving from feature/voice_send to main
2f9bc7df HEAD@{47}: pull: Fast-forward
504c5cae (0v) HEAD@{48}: checkout: moving from main to feature/voice_send
3c9c7553 HEAD@{49}: commit: cn/com allow all
7122c3be HEAD@{50}: commit (merge): fix url
e07c41fb HEAD@{51}: commit: fix code-server reboot problem(close debug)
821e20c9 HEAD@{52}: commit: clear double iframe more safe
053584a7 HEAD@{53}: checkout: moving from feature/voice_send to main
504c5cae (0v) HEAD@{54}: checkout: moving from main to feature/voice_send
053584a7 HEAD@{55}: commit: clear iframe double
10481b0b HEAD@{56}: commit: fix permisson bug
dc0eeaa9 HEAD@{57}: commit: add hint
a24df620 HEAD@{58}: commit: fix some bug
3ad36c29 HEAD@{59}: commit: 25/09/24 10:00~11:30 停机维护
07cf2363 HEAD@{60}: commit: fix many bug
6aac4200 HEAD@{61}: commit: try hello message
271672c9 HEAD@{62}: commit: check to code-server-like
252c426c HEAD@{63}: pull: Merge made by the 'ort' strategy.
588fc3b6 HEAD@{64}: commit: ready to code-like
b1f832a2 (origin/code-like-autosave, code-like-autosave) HEAD@{65}: merge code-like-autosave: Fast-forward
24f191d5 HEAD@{66}: checkout: moving from code-like-autosave to main
b1f832a2 (origin/code-like-autosave, code-like-autosave) HEAD@{67}: checkout: moving from main to code-like-autosave
24f191d5 HEAD@{68}: clone: from https://gitee.com/CakeCN/code-agent.git

BIN
profile_stats Normal file

Binary file not shown.

BIN
profile_stats_extract Normal file

Binary file not shown.