fix: 经验保存缺 app context(后台线程 db 报错被吞)——register_blueprints 注入 app,线程内 db 操作包 app_context

This commit is contained in:
2026-09-04 13:37:33 +08:00
parent 1ada51a7f6
commit c0c1be05f8
2 changed files with 28 additions and 13 deletions
+2
View File
@@ -23,7 +23,9 @@ def register_blueprints(app):
from .devices_api import bp as devices_bp
from .apks_api import bp as apks_bp
from .tailscale_api import bp as tailscale_bp
from . import agent_api as _agent_mod
from .agent_api import bp as agent_bp
_agent_mod.set_app(app)
for bp in (auth_bp, monitor_bp, tasks_bp, admin_bp, tools_bp,
devices_bp, apks_bp, tailscale_bp, agent_bp):
app.register_blueprint(bp)
+13
View File
@@ -43,6 +43,12 @@ _run = {"id": None, "state": "idle", "prompt": "", "serial": "",
_queues = {} # run_id -> queue.Queue(SSE 消费者读取)
_stop_events = {} # run_id -> threading.Event(用户中断)
_lock = threading.Lock()
_flask_app = None # web_server 注册时注入(后台线程 db 操作需 app context)
def set_app(app):
global _flask_app
_flask_app = app
def _meta_get(key):
@@ -90,6 +96,9 @@ def _bigrams(text):
def _find_experiences(prompt, limit=2, threshold=0.10):
"""按 bigram 重叠检索相似历史经验(prompt 与任务描述的字符相似度)。"""
try:
if _flask_app is None:
return ""
with _flask_app.app_context():
_ensure_exp_table()
rows = db.session.execute(db.text(
"SELECT task_prompt, recipe, hits FROM agent_experience "
@@ -141,7 +150,11 @@ def _distill_experience(cfg, prompt, tool_seq):
def _save_experience(prompt, recipe, tool_seq):
"""保存经验(后台线程调用,包 app context)。"""
try:
if _flask_app is None:
return
with _flask_app.app_context():
_ensure_exp_table()
from datetime import datetime
db.session.execute(db.text(