页面嵌套修改

This commit is contained in:
董宏凯 committed 2026-07-29 21:53:32 +08:00
1 parent 213dd841b5
commit 4450f342d8
38 files changed
+2020 -309

No files matched your search

@@ -57,6 +57,7 @@ from app.gateway.routers import (
parallel_agents,
position_roundtable,
positions,
position_roles,
public_config,
public_embed,
public_leaderboard,
@@ -1485,7 +1486,10 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
)
# Global business ? agent / chain mapping at /api/business-mapping
app.include_router(business_mapping.router)
app.include_router(business_mapping.router)
# Position-roundtable work-view role configuration at /api/position-roles.
app.include_router(position_roles.router)
# Light-app registry (?????) at /api/light-apps
app.include_router(light_apps.router)
@@ -264,6 +264,14 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
from deerflow.persistence.position_roundtable import make_position_roundtable_store
app.state.position_roundtable_store = make_position_roundtable_store(sf)
# 岗位会商工作视角(名称 / 顺序 / 特殊意图岗)是全局配置,和组织/RBAC
# 岗位分开保存。启动只补齐缺失内置项,不覆盖管理员的既有修改。
from app.gateway.position_role_defaults import POSITION_ROLE_SEED
from deerflow.persistence.position_roles import make_position_role_store
app.state.position_role_store = make_position_role_store(sf)
await app.state.position_role_store.ensure_seed(POSITION_ROLE_SEED)
from deerflow.persistence.business_mapping import make_business_mapping_store
@@ -0,0 +1,47 @@
"""Built-in roles for the position-roundtable workbench.
These ids are part of the persisted business-chain contract. Administrators
may rename, reorder or disable the roles, but a startup seed only inserts
missing entries and therefore never overwrites production configuration.
"""
from __future__ import annotations
POSITION_ROLE_SEED: list[dict[str, object]] = [
{
"id": "intelligence",
"name": "测试分析岗",
"description": "识别任务意图、补齐约束并确认业务链条",
"role_type": "intent",
"enabled": True,
"is_builtin": True,
"sort_order": 0,
},
{
"id": "planning",
"name": "组织测试岗",
"description": "承接上游信息并进行组织测试",
"role_type": "standard",
"enabled": True,
"is_builtin": True,
"sort_order": 1,
},
{
"id": "solution",
"name": "方案设计岗",
"description": "承接上游结果并形成方案产物",
"role_type": "standard",
"enabled": True,
"is_builtin": True,
"sort_order": 2,
},
{
"id": "evaluation",
"name": "综合测试岗",
"description": "测试链条产物并提出综合建议",
"role_type": "standard",
"enabled": True,
"is_builtin": True,
"sort_order": 3,
},
]
@@ -26,6 +26,9 @@ from deerflow.runtime.user_context import get_effective_user_id
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/business-mapping", tags=["business-mapping"])
_EIGHTBF_BUSINESS_CODE = "8BF"
_EIGHTBF_MANAGER_USERNAME = "lqq"
# ── schemas ────────────────────────────────────────────────────────────────
@@ -70,6 +73,20 @@ def _is_admin(request: Request) -> bool:
return user is None or getattr(user, "system_role", None) == "admin"
def _username_of(request: Request) -> str:
"""Read the trusted login account name, not an externally supplied username."""
user = getattr(request.state, "user", None)
email = str(getattr(user, "email", "") or "")
return email.split("@", 1)[0].strip().lower()
def _can_update_mapping(request: Request, business_code: str) -> bool:
"""8BF's public chain is maintained exclusively by the lqq account."""
if business_code.strip().upper() == _EIGHTBF_BUSINESS_CODE:
return _username_of(request) == _EIGHTBF_MANAGER_USERNAME
return _is_admin(request)
def _current_user_id(request: Request) -> str:
user = getattr(request.state, "user", None)
if user is not None:
@@ -119,17 +136,14 @@ async def _validate_public_chain_mapping(
async def list_mappings(request: Request) -> BusinessMappingListResponse:
store = _get_store(request)
rows = await store.list_mappings()
return BusinessMappingListResponse(
mappings=[BusinessMappingResponse(**r) for r in rows]
)
return BusinessMappingListResponse(mappings=[BusinessMappingResponse(**r) for r in rows])
@router.put("/{business_code}", response_model=BusinessMappingResponse)
async def update_mapping(
request: Request, business_code: str, body: BusinessMappingUpdateRequest
) -> BusinessMappingResponse:
if not _is_admin(request):
raise HTTPException(status_code=403, detail="Only administrators can update business mappings")
async def update_mapping(request: Request, business_code: str, body: BusinessMappingUpdateRequest) -> BusinessMappingResponse:
if not _can_update_mapping(request, business_code):
detail = "Only the lqq account can update the 8BF business mapping" if business_code.strip().upper() == _EIGHTBF_BUSINESS_CODE else "Only administrators can update business mappings"
raise HTTPException(status_code=403, detail=detail)
store = _get_store(request)
# Only forward fields the caller explicitly sent (distinguish omitted vs null).
fields = body.model_dump(exclude_unset=True)
@@ -51,11 +51,11 @@ SSE 协议(与前端 ``streamIntent`` 对齐)
from __future__ import annotations
import asyncio
import json
import logging
import re
from typing import Any, AsyncIterator
from collections.abc import AsyncIterator
from typing import Any
import httpx
from fastapi import APIRouter, Body, HTTPException, Request
@@ -69,7 +69,7 @@ from app.gateway.routers._roundtable_seed import ensure_roundtable_functional_ag
from app.gateway.routers.multi_agent import (
_ROUNDTABLE_THREAD_METADATA,
_auth_headers,
_create_thread,
_create_thread_direct,
_diagnose_exception,
_find_dispatch_message,
_find_trailing_ai_text,
@@ -311,21 +311,18 @@ async def init_intent(request: Request, payload: dict = Body(...)) -> dict[str,
# 缺失则就地用嵌入模板补建,避免下一步 /stream 报 500。
ensure_roundtable_functional_agents()
base = _loopback_base(request)
headers = _auth_headers(request)
# TCP loopback 到 127.0.0.1:<gateway port>(详见 multi_agent._make_loopback_client)。
# 不要在这里替换成 httpx.ASGITransport——曾试过,会整段 buffer SSE 流导致前端
# 看不到逐 token 增量。
# Keep Step-1 initialization aligned with multi-agent initialization:
# create the empty thread in-process rather than looping back through
# 127.0.0.1:<gateway-port>. Intranet proxies and port mappings can make
# that loopback fail only for automatic page initialization. Streaming
# below still uses the TCP loopback so SSE remains incrementally flushed.
raw_task_context = payload.get("task_context")
task_context = raw_task_context if isinstance(raw_task_context, dict) else None
try:
async with _make_loopback_client(request) as client:
thread_id = await _create_thread(
client,
base,
headers,
metadata=_intent_thread_metadata(task_context),
)
thread_id = await _create_thread_direct(
request,
metadata=_intent_thread_metadata(task_context),
)
except HTTPException:
# 上游已用结构化方式失败,原样传给前端不需要二次包装。
raise
@@ -0,0 +1,148 @@
"""Global position-roundtable role configuration API.
This directory is intentionally different from ``/api/positions``: the
latter is the organisation/RBAC position model, whereas this router controls
the work views that appear in the 岗位多智能体会商 page.
"""
from __future__ import annotations
import re
from datetime import datetime
from typing import Literal
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field, field_validator
from app.gateway.deps import get_current_user, get_optional_user_from_request
from app.gateway.position_role_defaults import POSITION_ROLE_SEED
from deerflow.persistence.position_roles import PositionRoleStore
router = APIRouter(prefix="/api/position-roles", tags=["position-roles"])
ROLE_ID_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9_-]{0,127}$")
class PositionRole(BaseModel):
id: str = Field(..., min_length=1, max_length=128)
name: str = Field(..., min_length=1, max_length=128)
description: str = Field(default="", max_length=512)
role_type: Literal["standard", "intent"] = "standard"
enabled: bool = True
# Response values are preserved by the repository; clients must not use
# this flag to promote a custom role into a protected built-in role.
is_builtin: bool = False
sort_order: int = Field(default=0, ge=0)
@field_validator("id")
@classmethod
def validate_id(cls, value: str) -> str:
value = value.strip()
if not ROLE_ID_PATTERN.fullmatch(value):
raise ValueError("岗位标识须以字母开头,只能包含字母、数字、- 或 _")
return value
@field_validator("name")
@classmethod
def normalize_name(cls, value: str) -> str:
value = value.strip()
if not value:
raise ValueError("岗位名称不能为空")
return value
class PositionRoleResponse(PositionRole):
updated_by: str | None = None
updated_at: datetime | str | None = None
class PositionRoleListResponse(BaseModel):
roles: list[PositionRoleResponse]
class PositionRoleReplaceRequest(BaseModel):
roles: list[PositionRole] = Field(default_factory=list)
def _get_store(request: Request) -> PositionRoleStore:
store = getattr(request.app.state, "position_role_store", None)
if store is None:
raise HTTPException(status_code=503, detail="Position role store not available")
return store
async def _require_admin(request: Request) -> None:
"""Reject non-admins but retain the local auth-disabled developer mode."""
user = await get_optional_user_from_request(request)
if user is None:
return
if getattr(user, "system_role", None) != "admin":
raise HTTPException(status_code=403, detail="岗位角色配置仅限管理员")
def _validate_payload(
rows: list[PositionRole],
existing: list[dict[str, object]],
) -> list[dict[str, object]]:
"""Apply directory invariants before the atomic replacement.
Keeping built-ins prevents old business-chain sessions from becoming
unreadable. They remain fully editable (including disable/retype); custom
roles can be removed freely.
"""
if not rows:
raise HTTPException(status_code=422, detail="至少保留一个启用的岗位")
ids = [row.id for row in rows]
if len(ids) != len(set(ids)):
raise HTTPException(status_code=422, detail="岗位标识不能重复")
names = [row.name.casefold() for row in rows]
if len(names) != len(set(names)):
raise HTTPException(status_code=422, detail="岗位名称不能重复")
enabled = [row for row in rows if row.enabled]
intent_rows = [row for row in enabled if row.role_type == "intent"]
if len(intent_rows) != 1:
raise HTTPException(
status_code=422,
detail="请保留且仅保留一个启用的意图识别岗(它承载会商入口和收口智能体)",
)
builtin_ids = {str(item["id"]) for item in existing if item.get("is_builtin")}
missing_builtin = builtin_ids.difference(ids)
if missing_builtin:
raise HTTPException(
status_code=422,
detail="内置岗位不能删除;如暂不使用,请将它停用",
)
existing_builtin = {str(item["id"]): bool(item.get("is_builtin")) for item in existing}
return [
{
**row.model_dump(),
"is_builtin": existing_builtin.get(row.id, False),
"sort_order": index,
}
for index, row in enumerate(rows)
]
@router.get("", response_model=PositionRoleListResponse)
async def list_position_roles(request: Request) -> PositionRoleListResponse:
# Startup performs the same idempotent seed. Repeating it here makes an
# upgraded running instance recover gracefully when the table was created
# after startup or a deployment starts with an empty database.
rows = await _get_store(request).ensure_seed(POSITION_ROLE_SEED)
return PositionRoleListResponse(roles=[PositionRoleResponse(**row) for row in rows])
@router.put("", response_model=PositionRoleListResponse)
async def replace_position_roles(
request: Request,
body: PositionRoleReplaceRequest,
) -> PositionRoleListResponse:
await _require_admin(request)
store = _get_store(request)
normalized = _validate_payload(body.roles, await store.list_roles())
user_id = await get_current_user(request)
rows = await store.replace_all(normalized, updated_by=user_id)
return PositionRoleListResponse(roles=[PositionRoleResponse(**row) for row in rows])
@@ -331,15 +331,57 @@ def _delivered_nodes(nodes: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [node for node in nodes if node.get("status") == "done"]
def _all_nodes_delivered(nodes: list[dict[str, Any]]) -> bool:
def _all_nodes_delivered(
nodes: list[dict[str, Any]],
*,
intent_position_id: str | None = None,
) -> bool:
return bool(nodes) and all(
node.get("status") == "done" and (_is_intent_position_node(node) or _node_has_markdown_delivery(node))
node.get("status") == "done"
and (_is_intent_position_node(node, intent_position_id) or _node_has_markdown_delivery(node))
for node in nodes
)
def _is_intent_position_node(node: dict[str, Any]) -> bool:
return str(node.get("position_id") or "").strip().lower() in {"intelligence", "intel", "intent"}
def _is_intent_position_node(
node: dict[str, Any],
intent_position_id: str | None = None,
) -> bool:
position_id = str(node.get("position_id") or "").strip()
if intent_position_id:
return position_id == intent_position_id
# Existing persisted sessions predate the configurable directory. Retain
# their historical interpretation until they are archived/recreated.
return position_id.lower() in {"intelligence", "intel", "intent"}
def _session_intent_position_id(session: dict[str, Any]) -> str | None:
chain = session.get("chain_snapshot") if isinstance(session.get("chain_snapshot"), dict) else {}
value = chain.get("_intent_position_id")
return value.strip() if isinstance(value, str) and value.strip() else None
async def _configured_intent_position_id(request: Request) -> str:
"""Get the one enabled special role for a newly activated session.
The chosen id is frozen into ``chain_snapshot`` on activation. A later
configuration change therefore applies to future workspaces without
reinterpreting completion rules in an in-flight historical business chain.
"""
store = getattr(request.app.state, "position_role_store", None)
if store is not None:
rows = await store.list_roles()
selected = next(
(
row.get("id")
for row in rows
if row.get("enabled") and row.get("role_type") == "intent" and isinstance(row.get("id"), str)
),
None,
)
if isinstance(selected, str) and selected.strip():
return selected.strip()
return "intelligence"
def _is_markdown_artifact(artifact: Any) -> bool:
@@ -419,12 +461,17 @@ def _has_confirmed_intent(intent: Any) -> bool:
return bool(objective and isinstance(constraints, list))
def _prime_intent_nodes(nodes: list[dict[str, Any]], intent: Any) -> list[dict[str, Any]]:
def _prime_intent_nodes(
nodes: list[dict[str, Any]],
intent: Any,
*,
intent_position_id: str | None = None,
) -> list[dict[str, Any]]:
now_answer = _intent_node_answer(intent)
primed: list[dict[str, Any]] = []
for node in nodes:
next_node = dict(node)
if _is_intent_position_node(next_node):
if _is_intent_position_node(next_node, intent_position_id):
next_node.update(
{
"status": "done",
@@ -461,7 +508,7 @@ def _build_node_context_text(
objective = _text_from_keys(intent, ["objective", "goal"], "暂无意图结论")
constraints = intent.get("constraints") if isinstance(intent.get("constraints"), list) else []
agent_name, position_id = _seat_meta(session, current)
md_required = not _is_intent_position_node(current)
md_required = not _is_intent_position_node(current, _session_intent_position_id(session))
lines = [
"岗位多智能体会商上下文(隐藏注入,不要向用户复述本标签):",
"",
@@ -716,7 +763,7 @@ async def _handoff_context(request: Request, session_id: str, node_key: str) ->
),
"delivery_requirement": {
"type": "markdown_report",
"required": not _is_intent_position_node(current),
"required": not _is_intent_position_node(current, _session_intent_position_id(session)),
"completion_rule": "普通业务席位必须在 /mnt/user-data/outputs/ 下交付一份 .md 报告文档才会标记完成;情报分析/情报收集岗以意图识别完成为准。",
},
"task": session.get("task_snapshot") or {},
@@ -1137,16 +1184,26 @@ async def activate_session(
for seat in (chain.get("seats") if isinstance(chain.get("seats"), list) else [])
if seat.get("agent_id")
}
# Freeze the currently configured special role with this session. This
# prevents a later global config edit from changing the completion rule of
# an already running historical chain.
chain_snapshot = dict(chain)
intent_position_id = await _configured_intent_position_id(request)
chain_snapshot["_intent_position_id"] = intent_position_id
nodes = _chain_nodes(
chain,
chain_snapshot,
available_agent_ids=await _available_agent_ids(request, seat_ids),
)
nodes = _prime_intent_nodes(nodes, current.get("intent_snapshot"))
nodes = _prime_intent_nodes(
nodes,
current.get("intent_snapshot"),
intent_position_id=intent_position_id,
)
activated = await store.activate_session(
session_id,
user_id,
chain_id=body.chain_id,
chain_snapshot=chain,
chain_snapshot=chain_snapshot,
nodes=nodes,
)
if activated is None:
@@ -1215,7 +1272,7 @@ async def update_node_conversation(
node_key: str,
body: ConversationStateUpdateRequest,
) -> NodeResponse:
store, user_id, _ = await _require_writable_session(request, session_id)
store, user_id, session = await _require_writable_session(request, session_id)
current = await store.get_node(session_id, node_key, user_id)
if current is None:
raise HTTPException(status_code=404, detail="Position roundtable node not found")
@@ -1247,7 +1304,7 @@ async def build_node_context(request: Request, session_id: str, node_key: str) -
async def complete_node_turn(
request: Request, session_id: str, node_key: str, body: CompleteTurnRequest
) -> NodeResponse:
store, user_id, _ = await _require_writable_session(request, session_id)
store, user_id, session = await _require_writable_session(request, session_id)
node = await store.get_node(session_id, node_key, user_id)
if node is None:
raise HTTPException(status_code=404, detail="Position roundtable node not found")
@@ -1268,7 +1325,7 @@ async def complete_node_turn(
requires_fresh_delivery = node.get("status") in {"rejected", "stale"}
next_status = (
"done"
if _is_intent_position_node(node)
if _is_intent_position_node(node, _session_intent_position_id(session))
else "done"
if has_markdown and (not requires_fresh_delivery or markdown_changed)
else "running"
@@ -1280,7 +1337,7 @@ async def complete_node_turn(
new_effective_delivery = (
next_status == "done"
and (
_is_intent_position_node(node)
_is_intent_position_node(node, _session_intent_position_id(session))
or node.get("status") != "done"
or markdown_changed
)
@@ -1384,7 +1441,7 @@ async def _prepare_builtin_run(
nodes = await store.list_nodes(session_id, user_id)
if nodes is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
if not _all_nodes_delivered(nodes):
if not _all_nodes_delivered(nodes, intent_position_id=_session_intent_position_id(session)):
raise HTTPException(status_code=409, detail="所有岗位产物完成后才能生成或更新内置交付")
if kind == "action_plan":
@@ -1428,7 +1485,7 @@ async def _complete_builtin_run(
nodes = await store.list_nodes(session_id, user_id)
if nodes is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
if not _all_nodes_delivered(nodes):
if not _all_nodes_delivered(nodes, intent_position_id=_session_intent_position_id(session)):
raise HTTPException(status_code=409, detail="上游岗位产物已变更或未完成,不能写入旧的内置交付")
current_revisions = _source_revisions(nodes)
if body.source_revisions != current_revisions:
@@ -35,9 +35,10 @@ from deerflow.runtime.user_context import get_effective_user_id
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/roundtable-chains", tags=["roundtable-chains"])
# Seat-count bounds mirror the roundtable selection bounds (2 ≤ N ≤ 8).
# Stored business chains support up to 20 seats. The frontend may choose a
# lower deployment-specific cap, but must never exceed this server contract.
MIN_SEATS = 2
MAX_SEATS = 8
MAX_SEATS = 20
# ── schemas ────────────────────────────────────────────────────────────────
@@ -183,7 +184,7 @@ def _get_store(request: Request):
def _validate_seats(seats: list[ChainSeatSchema]) -> None:
"""Enforce 2 ≤ N ≤ 8 and reject duplicate agent ids within a chain."""
"""Enforce 2 ≤ N ≤ 20 and reject duplicate agent ids within a chain."""
if len(seats) < MIN_SEATS or len(seats) > MAX_SEATS:
raise HTTPException(
status_code=400,