agent-Specialization/server/tasks/helpers.py
JOJO e29ccb318e fix(multi-agent): 修复情况2主消息池派发链路
修复多智能体模式下主智能体空闲时收不到子智能体输出推送的一系列 bug:

1. poll_multi_agent_notifications 死锁:原实现先等所有 running 实例
   退出再 drain 消息池,导致 ask_master 在 await 期间永远等不到主对话
   回答。改为池优先:pool 有消息立即派发,不管 running 状态。

2. _dispatch_multi_agent_idle_messages 缺 import:调用
   inject_multi_agent_master_message 但文件顶部从未导入,NameError
   被外层 except 吞掉,task 永远建不起来。

3. dispatch 内调试日志引用 rec 错位:dispatch_ma_idle_sender_user_message
   被放到 create_chat_task 之前,触发 UnboundLocalError,task 同样建不起来。

4. session_data['auto_user_message_payload'] / preceding_user_notices
   payload 漏写 auto_message_type:前端 isMultiAgentMessage() 只认
   auto_message_type.startsWith('multi_agent_'),空字符串走 fallback
   通知渲染。

5. dispatch 第①步重复持久化:对包含 last 的全部消息都调
   inject_multi_agent_master_message 落盘,之后 task 又在 handle_task_with_sender
   再 add_conversation,导致历史里出现两条相同 user 消息(前一条多智能体渲染,
   后一条通知渲染)。前置 N-1 条只持久化一次,最后一条交给后续 task 自己持久化。

6. last 赋值时机错位:last_emit_payload 在 last=parsed_messages[-1] 之前引用,
   UnboundLocalError 再次吃掉后续链路。

7. handle_task_with_sender 多智能体分支漏写 visibility='chat':
   _user_message_ui_defaults('sub_agent') 默认 visibility='compact',
   透传到落盘 metadata 后,前端从后端加载历史时走通知渲染分支。显式
   user_message_metadata['visibility']='chat' 强制走多智能体专用渲染。
2026-07-13 20:05:02 +08:00

91 lines
3.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""简单任务 API将聊天任务与 WebSocket 解耦,支持后台运行与轮询。"""
from __future__ import annotations
from server.tasks import tasks_bp
import mimetypes
import json
import time
import threading
import uuid
import re
from collections import deque
from pathlib import Path
from typing import Dict, Any, Optional, List
from flask import Blueprint, request, jsonify
from flask import current_app, session
from server.auth_helpers import api_login_required, get_current_username
from server.context import get_user_resources, ensure_conversation_loaded
from server.chat_flow import run_chat_task_sync
from server.state import stop_flags
from server.utils_common import debug_log, log_conn_diag
from utils.host_workspace_debug import write_host_workspace_debug
from config import DATA_DIR, WORKSPACE_SKILLS_DIRNAME
from modules.goal_state_manager import GoalStateManager, REASON_USER_CANCEL
from server.tasks.models import TaskRecord
SKILL_FRONTMATTER_RE = re.compile(r"^---\s*\n(?P<body>.*?)\n---\s*\n?", re.S)
SKILL_FIELD_RE = re.compile(r"^(?P<key>name|description)\s*:\s*(?P<value>.*)$")
def _conversation_title_for_task(rec: TaskRecord) -> Optional[str]:
conv_id = (getattr(rec, "conversation_id", None) or "").strip()
if not conv_id:
return None
if not conv_id.startswith("conv_"):
conv_id = f"conv_{conv_id}"
try:
if rec.username == "host":
path = Path(DATA_DIR).expanduser().resolve() / "conversations" / rec.workspace_id / f"{conv_id}.json"
else:
import server.state as state
workspace = state.user_manager.ensure_user_workspace(rec.username, rec.workspace_id or "default")
path = Path(workspace.data_dir).expanduser().resolve() / "conversations" / f"{conv_id}.json"
if not path.exists():
return None
data = json.loads(path.read_text(encoding="utf-8"))
title = str(data.get("title") or "").strip()
return title or None
except Exception:
return None
def _workspace_label_for_task(rec: TaskRecord) -> Optional[str]:
try:
if rec.username == "host":
from modules.host_workspace_manager import load_host_workspace_catalog
catalog = load_host_workspace_catalog()
for item in catalog.get("workspaces") or []:
if item.get("workspace_id") == rec.workspace_id:
return str(item.get("label") or rec.workspace_id)
else:
import server.state as state
item = state.user_manager.list_user_workspaces(rec.username).get(rec.workspace_id)
if item:
return str(item.get("label") or rec.workspace_id)
except Exception:
pass
return rec.workspace_id
def _task_public_payload(rec: TaskRecord, *, include_title: bool = True) -> Dict[str, Any]:
payload = {
"task_id": rec.task_id,
"username": rec.username,
"workspace_id": rec.workspace_id,
"workspace_label": _workspace_label_for_task(rec),
"status": rec.status,
"created_at": rec.created_at,
"updated_at": rec.updated_at,
"message": rec.message,
"conversation_id": rec.conversation_id,
"error": rec.error,
"message_source": (rec.session_data or {}).get("message_source"),
"goal_mode": bool((rec.session_data or {}).get("goal_mode")),
"goal_progress": (rec.session_data or {}).get("goal_progress"),
"task_type": getattr(rec, "task_type", "chat"),
}
if include_title:
payload["conversation_title"] = _conversation_title_for_task(rec)
return payload