feat: 简介模式菜单按类型 A/B 分套,兼容未配置的旧部署
两套网页可通过 runtime-config.js 的 VITE_COMPACT_MENU_TYPE 加载各自左侧菜单;缺省或旧页面不传参数时仍读取原来的类型 A 数据。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
5e1765d889
commit
acf538ac01
21 files changed
+610
-103
No files matched your search
@@ -342,6 +342,7 @@ FastAPI application on port 8001 with health checks at `GET|HEAD /health`, `/api
|
||||
| **Public Scheduled Tasks** (`/api/public/scheduled-tasks`) | **Unauthenticated** mirror for embedding. Adds `GET /runs/{rid}/html` and `GET /{task_id}/latest-html` for the `html_page` preview; the run result keeps `result.html` (only file paths are redacted). |
|
||||
| **Light Apps** (`/api/light-apps`) | Light-app registry (????? / ????), **global/shared** (no user scoping; `created_by`/`updated_by` audit-only). Two kinds: `window_open` (launched in a new tab from the ???? card grid) and `iframe` (embedded under a parent sidebar menu via `mount_location` and dynamically injected into the sidebar). Both carry `route_params` ? a list of `{key, paramType: login\|theme, source, customValue, themeValue}` descriptors the **frontend** resolves at launch time (login params read from `localStorage.userInfo`; theme params use a literal value) and appends to `url` as query string. `GET /` - list (filters `app_type`/`mount_location`/`enabled_only`/`search`); `GET /{app_id}` - read one (both open to any authenticated user); `POST /`, `PUT /{app_id}`, `DELETE /{app_id}` - **admin only**; iframe apps must carry a `mount_location` (400 otherwise); the unique `name` collides as HTTP 409. Backed by `deerflow.persistence.light_apps` (table `light_apps`, auto-created by `create_all`); store wired in `deps.py` as `app.state.light_app_store`. Tests: `tests/test_light_apps.py`. |
|
||||
| **Menu Overrides** (`/api/menu-overrides`) | Sidebar-menu overrides (菜单管理), **global/shared** (no user scoping; `updated_by` audit-only). The static menu tree (icons/routes/`adminOnly`) lives in the **frontend** code (`core/page-layout/sidebar-menu.ts`); iframe light-apps are injected at render time. This router persists a per-node **overlay** the frontend merges onto that tree: `parent_id` (re-parent, moves the whole subtree; NULL = top level), `sort_order` (reorder among siblings), `label` (rename; NULL keeps code label), `disabled` (停用 — hides the node **and its subtree**). A node with no row renders exactly as code defines it, so new code menus / newly-registered iframe apps appear automatically and are immediately configurable. `GET /` - list all overrides (open to any authenticated user); `PUT /` - **admin only**, atomically **replaces the whole set** (`{overrides: [...]}`); rejects re-parenting that would exceed **3 levels** or form a cycle (`_validate_depth`, HTTP 400). Backed by `deerflow.persistence.menu_overrides` (table `menu_overrides`, auto-created by `create_all`); store wired in `deps.py` as `app.state.menu_override_store`. Frontend: merge logic `core/page-layout/menu-overrides.ts` (`applyMenuOverrides` in `use-sidebar-menu.ts`), client `strategy-components/api/menu-overrides.ts`, admin page `pages/MenuManagementPage.tsx` (@dnd-kit drag-reorder/re-parent + 「移动到」parent selector + ↑↓ arrows + 改名/停用), entry in the bottom-left settings dropdown (`components/page-sidebar.tsx`, admin-only). Tests: `tests/test_menu_overrides.py`, `frontend-web/src/core/page-layout/menu-overrides.test.ts`. |
|
||||
| **Compact Menu Overrides** (`/api/compact-menu-overrides`) | Compact/sidebar-summary left-nav overlay (简介模式菜单), **global/shared**. Two independent sets keyed by `menu_type` (`A` default / `B`); saving one type does not wipe the other. Type B rows use a `B::` node_id prefix so they stay unique on databases that still use `node_id` as the sole PK. `GET ?menu_type=` lists one type (open); `PUT {menu_type, overrides}` admin-only replaces that type. Frontend: `MenuManagementPage` 简介模式 type switcher + `runtime-config.js` `VITE_COMPACT_MENU_TYPE`. Tests: `tests/test_compact_menu_overrides.py`. |
|
||||
| **Sensitive Words** (`/api/sensitive-words`) | Sensitive-word / desensitize map (敏感词管理 / 脱敏词), **global/shared** (no user scoping; `updated_by` audit-only). Each row maps an original `word` → `replacement`, with `enabled` (停用 parks a word without deleting) + `sort_order`. The **frontend** ships a seed map in code (`src/lib/desensitize.ts` `SEED_DESENSITIZE_MAP`) used as the default on a fresh deployment; once an admin saves, this table is the source of truth and the frontend loads it at startup (`DesensitizeWordsLoader` → `replaceDesensitizeMap`, **enabled** rows only). `GET /` - list all words (open to any authenticated user — every page desensitizes); `PUT /` - **admin OR the `lqq` account** (`_require_manager`: `system_role == "admin"` or email `@`-prefix `== "lqq"`), atomically **replaces the whole set** (`{words: [...]}`, de-duped by `word`, last wins). Backed by `deerflow.persistence.sensitive_words` (table `sensitive_words`, PK `word` `String(191)`, auto-created by `create_all`); store wired in `deps.py` as `app.state.sensitive_word_store`. Frontend: client `strategy-components/api/sensitive-words.ts`, page `pages/SensitiveWordsPage.tsx` (route `/page/strategy/admin/sensitive-words`, entry in the bottom-left settings dropdown — **gated on username `lqq`, not admin role**, present in both sidebar modes; 「导入种子词」 merges missing seed entries). Tests: `tests/test_sensitive_words.py`. |
|
||||
| **Dashboard Sessions** (`/api/dashboard-sessions`) | 「大屏绘制智能体」独立页面会话,**按外部 `task_id` 存取,不按 user 分权**(open read + shared writes;`user_id` audit-only)。一个 task 一行(upsert):`transcript`(聊天记录 JSON)+ `report_json`(最新结构化数据,可解析 = 「有效结果」)。`GET /by-task/{task_id}` - 取该 task 会话(无则 404);`PUT /by-task/{task_id}` - upsert(`{transcript?, report_json?}`,只覆盖传入项)。Backed by `deerflow.persistence.dashboard_sessions`(table `dashboard_sessions`, auto-created by `create_all`,无迁移);store wired in `deps.py` as `app.state.dashboard_session_store`。前端独立页 `roundtable-planning/pages/DashboardAgentPage.tsx`(路由 `/page/strategy/dashboard-agent?taskId=`,侧边栏「问答管理 → 大屏绘制」)让智能体分析任务报告 JSON → report-json → 渲染 `DashboardApp`。Tests: `tests/test_dashboard_sessions.py`。 |
|
||||
| **Task Reports** (`/api/task-reports`) | 任务级研判情报报告详情,**按 `task_id` 共享、不按 user 分权**(写入者只留 `updated_by` 审计)。`GET /by-task/{task_id}` 始终返回原 Consumer 兼容外壳 `{state:"200", msg:"操作成功!", data:[...]}`(未保存为 `data: []`);`POST /by-task/{task_id}` 首次保存,已有报告返回 409;`PUT /by-task/{task_id}` 原子替换完整 `data` 数组。`POST /import/by-task/{task_id}` 面向 TaskCOP 导入页,接收 `sq-report-mock.json` 兼容的 `data`/`records` 数组并完整覆盖目标任务;路径中的选定任务 id 优先于文件内的 `taskId`,避免误写。每一项严格是 `{id, taskId, createTime, updateTime, sessionId, contentJson, categoryType}`;`contentJson` 以 JSON **字符串**原样落在 `records_json`,避免破坏大屏按类目解析的输入格式。保存或导入非空 `data` 后,router 会通过 `app.state.taskcop_task_store.mark_analysis_completed` 将同 id 的 TaskCOP 任务升级至状态 `25`,使旧任务列表显示并筛选为“已完成”;普通保存时不存在匹配任务的报告仍可独立保存,导入则要求目标任务存在。Backed by `deerflow.persistence.task_reports`(table `task_reports`, auto-created by `create_all`);store wired in `deps.py` as `app.state.task_report_store`。前端客户端 `strategy-components/api/task-reports.ts`,`core/auth/dashboard-input.ts` 与 rwfx 3q 完成检查均直接读此接口,不再依赖 Consumer 或本地 sq-report mock。Tests: `tests/test_task_reports.py`。 |
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
"""Compact/sidebar-summary menu override API.
|
||||
|
||||
Routes (prefix ``/api/compact-menu-overrides``):
|
||||
GET "" list all compact-menu overrides
|
||||
PUT "" replace the entire override set (admin)
|
||||
GET "" list compact-menu overrides.
|
||||
``menu_type`` omitted / empty → type A (original legacy data).
|
||||
PUT "" replace that type's override set (admin).
|
||||
``menu_type`` omitted / empty → type A, does not wipe type B.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -10,11 +12,15 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.gateway.deps import get_current_user, get_optional_user_from_request
|
||||
from deerflow.persistence.compact_menu_overrides import CompactMenuOverrideStore
|
||||
from deerflow.persistence.compact_menu_overrides import (
|
||||
CompactMenuOverrideStore,
|
||||
DEFAULT_COMPACT_MENU_TYPE,
|
||||
normalize_compact_menu_type,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/compact-menu-overrides", tags=["compact-menu-overrides"])
|
||||
|
||||
@@ -27,15 +33,22 @@ class CompactMenuOverride(BaseModel):
|
||||
|
||||
|
||||
class CompactMenuOverrideResponse(CompactMenuOverride):
|
||||
menu_type: str = DEFAULT_COMPACT_MENU_TYPE
|
||||
updated_by: str | None = None
|
||||
updated_at: datetime | str | None = None
|
||||
|
||||
|
||||
class CompactMenuOverrideListResponse(BaseModel):
|
||||
menu_type: str = DEFAULT_COMPACT_MENU_TYPE
|
||||
overrides: list[CompactMenuOverrideResponse]
|
||||
|
||||
|
||||
class CompactMenuOverrideReplaceRequest(BaseModel):
|
||||
menu_type: str | None = Field(
|
||||
default=None,
|
||||
max_length=32,
|
||||
description="A or B. Omitted/empty = A (original compact-menu set).",
|
||||
)
|
||||
overrides: list[CompactMenuOverride] = Field(default_factory=list)
|
||||
|
||||
|
||||
@@ -55,10 +68,21 @@ async def _require_admin(request: Request) -> None:
|
||||
|
||||
|
||||
@router.get("", response_model=CompactMenuOverrideListResponse)
|
||||
async def list_compact_menu_overrides(request: Request) -> CompactMenuOverrideListResponse:
|
||||
async def list_compact_menu_overrides(
|
||||
request: Request,
|
||||
menu_type: str | None = Query(
|
||||
default=None,
|
||||
max_length=32,
|
||||
description="A or B. Omitted/empty = A, returning the original compact-menu rows.",
|
||||
),
|
||||
) -> CompactMenuOverrideListResponse:
|
||||
t = normalize_compact_menu_type(menu_type)
|
||||
store = _get_store(request)
|
||||
rows = await store.list_overrides()
|
||||
return CompactMenuOverrideListResponse(overrides=[CompactMenuOverrideResponse(**r) for r in rows])
|
||||
rows = await store.list_overrides(t)
|
||||
return CompactMenuOverrideListResponse(
|
||||
menu_type=t,
|
||||
overrides=[CompactMenuOverrideResponse(**r) for r in rows],
|
||||
)
|
||||
|
||||
|
||||
@router.put("", response_model=CompactMenuOverrideListResponse)
|
||||
@@ -67,10 +91,15 @@ async def replace_compact_menu_overrides(
|
||||
body: CompactMenuOverrideReplaceRequest,
|
||||
) -> CompactMenuOverrideListResponse:
|
||||
await _require_admin(request)
|
||||
t = normalize_compact_menu_type(body.menu_type)
|
||||
store = _get_store(request)
|
||||
user_id = await get_current_user(request)
|
||||
rows = await store.replace_all(
|
||||
[o.model_dump() for o in body.overrides],
|
||||
menu_type=t,
|
||||
updated_by=user_id,
|
||||
)
|
||||
return CompactMenuOverrideListResponse(overrides=[CompactMenuOverrideResponse(**r) for r in rows])
|
||||
return CompactMenuOverrideListResponse(
|
||||
menu_type=t,
|
||||
overrides=[CompactMenuOverrideResponse(**r) for r in rows],
|
||||
)
|
||||
+8
@@ -3,16 +3,24 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from deerflow.persistence.compact_menu_overrides.base import CompactMenuOverrideStore
|
||||
from deerflow.persistence.compact_menu_overrides.keys import (
|
||||
ALLOWED_COMPACT_MENU_TYPES,
|
||||
DEFAULT_COMPACT_MENU_TYPE,
|
||||
normalize_compact_menu_type,
|
||||
)
|
||||
from deerflow.persistence.compact_menu_overrides.memory import MemoryCompactMenuOverrideStore
|
||||
from deerflow.persistence.compact_menu_overrides.model import CompactMenuOverrideRow
|
||||
from deerflow.persistence.compact_menu_overrides.sql import CompactMenuOverrideRepository
|
||||
|
||||
__all__ = [
|
||||
"ALLOWED_COMPACT_MENU_TYPES",
|
||||
"CompactMenuOverrideRepository",
|
||||
"CompactMenuOverrideRow",
|
||||
"CompactMenuOverrideStore",
|
||||
"DEFAULT_COMPACT_MENU_TYPE",
|
||||
"MemoryCompactMenuOverrideStore",
|
||||
"make_compact_menu_override_store",
|
||||
"normalize_compact_menu_type",
|
||||
]
|
||||
|
||||
|
||||
|
||||
+10
-4
@@ -8,11 +8,17 @@ from typing import Any
|
||||
|
||||
class CompactMenuOverrideStore(ABC):
|
||||
@abstractmethod
|
||||
async def list_overrides(self) -> list[dict[str, Any]]:
|
||||
"""Return every stored compact-menu override row."""
|
||||
async def list_overrides(self, menu_type: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Return compact-menu override rows for one type (default A)."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def replace_all(self, rows: list[dict[str, Any]], *, updated_by: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Atomically replace the entire compact-menu override set."""
|
||||
async def replace_all(
|
||||
self,
|
||||
rows: list[dict[str, Any]],
|
||||
*,
|
||||
menu_type: str | None = None,
|
||||
updated_by: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Atomically replace the compact-menu override set for one type."""
|
||||
raise NotImplementedError
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
"""Compact-menu type helpers.
|
||||
|
||||
Two website deployments can keep independent compact-sidebar layouts.
|
||||
Type ``A`` is the historical default (existing rows stay as-is). Type ``B``
|
||||
is stored under a prefixed primary key so it never collides with type A on
|
||||
databases that still use ``node_id`` as the sole PK.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
DEFAULT_COMPACT_MENU_TYPE = "A"
|
||||
ALLOWED_COMPACT_MENU_TYPES = ("A", "B")
|
||||
_STORAGE_SEP = "::"
|
||||
_TYPE_ALIASES = {
|
||||
"A": "A",
|
||||
"1": "A",
|
||||
"DEFAULT": "A",
|
||||
"B": "B",
|
||||
"2": "B",
|
||||
"ALT": "B",
|
||||
}
|
||||
|
||||
|
||||
def normalize_compact_menu_type(value: str | None) -> str:
|
||||
raw = (value or "").strip().upper()
|
||||
return _TYPE_ALIASES.get(raw, DEFAULT_COMPACT_MENU_TYPE)
|
||||
|
||||
|
||||
def storage_node_id(menu_type: str, node_id: str) -> str:
|
||||
"""PK value that stays unique across types on a node_id-only primary key."""
|
||||
t = normalize_compact_menu_type(menu_type)
|
||||
nid = str(node_id)
|
||||
if t == DEFAULT_COMPACT_MENU_TYPE:
|
||||
prefix = f"{t}{_STORAGE_SEP}"
|
||||
return nid[len(prefix) :] if nid.startswith(prefix) else nid
|
||||
prefix = f"{t}{_STORAGE_SEP}"
|
||||
return nid if nid.startswith(prefix) else f"{prefix}{nid}"
|
||||
|
||||
|
||||
def public_node_id(stored: str, menu_type: str | None = None) -> str:
|
||||
"""Strip the type prefix so API callers always see the real menu node id."""
|
||||
t = normalize_compact_menu_type(menu_type)
|
||||
nid = str(stored)
|
||||
prefix = f"{t}{_STORAGE_SEP}"
|
||||
if nid.startswith(prefix):
|
||||
return nid[len(prefix) :]
|
||||
return nid
|
||||
+35
-8
@@ -6,12 +6,19 @@ from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from deerflow.persistence.compact_menu_overrides.base import CompactMenuOverrideStore
|
||||
from deerflow.persistence.compact_menu_overrides.keys import (
|
||||
normalize_compact_menu_type,
|
||||
public_node_id,
|
||||
storage_node_id,
|
||||
)
|
||||
|
||||
|
||||
def _normalize(data: dict[str, Any], updated_by: str | None) -> dict[str, Any]:
|
||||
def _normalize(data: dict[str, Any], menu_type: str, updated_by: str | None) -> dict[str, Any]:
|
||||
placement = str(data.get("placement") or "sidebar")
|
||||
node_id = public_node_id(str(data["node_id"]), menu_type)
|
||||
return {
|
||||
"node_id": str(data["node_id"]),
|
||||
"node_id": storage_node_id(menu_type, node_id),
|
||||
"menu_type": menu_type,
|
||||
"placement": placement if placement in {"sidebar", "settings"} else "sidebar",
|
||||
"sort_order": int(data.get("sort_order", 0)),
|
||||
"label": (data.get("label") or None),
|
||||
@@ -20,18 +27,38 @@ def _normalize(data: dict[str, Any], updated_by: str | None) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _public(row: dict[str, Any]) -> dict[str, Any]:
|
||||
menu_type = normalize_compact_menu_type(row.get("menu_type"))
|
||||
out = dict(row)
|
||||
out["menu_type"] = menu_type
|
||||
out["node_id"] = public_node_id(str(row.get("node_id") or ""), menu_type)
|
||||
return out
|
||||
|
||||
|
||||
class MemoryCompactMenuOverrideStore(CompactMenuOverrideStore):
|
||||
def __init__(self) -> None:
|
||||
self._rows: dict[str, dict[str, Any]] = {}
|
||||
|
||||
async def list_overrides(self) -> list[dict[str, Any]]:
|
||||
return [dict(r) for r in sorted(self._rows.values(), key=lambda r: r.get("sort_order", 0))]
|
||||
async def list_overrides(self, menu_type: str | None = None) -> list[dict[str, Any]]:
|
||||
t = normalize_compact_menu_type(menu_type)
|
||||
rows = [r for r in self._rows.values() if normalize_compact_menu_type(r.get("menu_type")) == t]
|
||||
return [_public(r) for r in sorted(rows, key=lambda r: r.get("sort_order", 0))]
|
||||
|
||||
async def replace_all(self, rows: list[dict[str, Any]], *, updated_by: str | None = None) -> list[dict[str, Any]]:
|
||||
self._rows = {}
|
||||
async def replace_all(
|
||||
self,
|
||||
rows: list[dict[str, Any]],
|
||||
*,
|
||||
menu_type: str | None = None,
|
||||
updated_by: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
t = normalize_compact_menu_type(menu_type)
|
||||
self._rows = {
|
||||
k: v for k, v in self._rows.items() if normalize_compact_menu_type(v.get("menu_type")) != t
|
||||
}
|
||||
for r in rows:
|
||||
node_id = r.get("node_id")
|
||||
if not node_id:
|
||||
continue
|
||||
self._rows[str(node_id)] = _normalize(r, updated_by)
|
||||
return [dict(r) for r in self._rows.values()]
|
||||
stored = _normalize(r, t, updated_by)
|
||||
self._rows[str(stored["node_id"])] = stored
|
||||
return await self.list_overrides(t)
|
||||
+3
-1
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Integer, String
|
||||
from sqlalchemy import Index, Integer, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
@@ -17,8 +17,10 @@ from deerflow.persistence.types import BeijingDateTime
|
||||
|
||||
class CompactMenuOverrideRow(Base):
|
||||
__tablename__ = "compact_menu_overrides"
|
||||
__table_args__ = (Index("ix_compact_menu_overrides_menu_type", "menu_type"),)
|
||||
|
||||
node_id: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
menu_type: Mapped[str] = mapped_column(String(32), default="A", server_default="A")
|
||||
placement: Mapped[str] = mapped_column(String(32), default="sidebar")
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
label: Mapped[str | None] = mapped_column(String(255))
|
||||
|
||||
+38
-8
@@ -5,25 +5,36 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy import delete, or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.compact_menu_overrides.base import CompactMenuOverrideStore
|
||||
from deerflow.persistence.compact_menu_overrides.keys import (
|
||||
DEFAULT_COMPACT_MENU_TYPE,
|
||||
normalize_compact_menu_type,
|
||||
public_node_id,
|
||||
storage_node_id,
|
||||
)
|
||||
from deerflow.persistence.compact_menu_overrides.model import CompactMenuOverrideRow
|
||||
|
||||
|
||||
def _to_dict(row: CompactMenuOverrideRow) -> dict[str, Any]:
|
||||
data = row.to_dict()
|
||||
menu_type = normalize_compact_menu_type(data.get("menu_type"))
|
||||
data["menu_type"] = menu_type
|
||||
data["node_id"] = public_node_id(str(data.get("node_id") or ""), menu_type)
|
||||
value = data.get("updated_at")
|
||||
if isinstance(value, datetime):
|
||||
data["updated_at"] = value.isoformat()
|
||||
return data
|
||||
|
||||
|
||||
def _row_from(data: dict[str, Any], updated_by: str | None) -> CompactMenuOverrideRow:
|
||||
def _row_from(data: dict[str, Any], menu_type: str, updated_by: str | None) -> CompactMenuOverrideRow:
|
||||
placement = str(data.get("placement") or "sidebar")
|
||||
node_id = str(data["node_id"])
|
||||
return CompactMenuOverrideRow(
|
||||
node_id=str(data["node_id"]),
|
||||
node_id=storage_node_id(menu_type, node_id),
|
||||
menu_type=menu_type,
|
||||
placement=placement if placement in {"sidebar", "settings"} else "sidebar",
|
||||
sort_order=int(data.get("sort_order", 0)),
|
||||
label=(data.get("label") or None),
|
||||
@@ -35,23 +46,42 @@ class CompactMenuOverrideRepository(CompactMenuOverrideStore):
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
|
||||
async def list_overrides(self) -> list[dict[str, Any]]:
|
||||
async def list_overrides(self, menu_type: str | None = None) -> list[dict[str, Any]]:
|
||||
t = normalize_compact_menu_type(menu_type)
|
||||
stmt = select(CompactMenuOverrideRow).order_by(CompactMenuOverrideRow.sort_order.asc())
|
||||
stmt = stmt.where(_menu_type_filter(t))
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [_to_dict(row) for row in result.scalars()]
|
||||
|
||||
async def replace_all(self, rows: list[dict[str, Any]], *, updated_by: str | None = None) -> list[dict[str, Any]]:
|
||||
async def replace_all(
|
||||
self,
|
||||
rows: list[dict[str, Any]],
|
||||
*,
|
||||
menu_type: str | None = None,
|
||||
updated_by: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
t = normalize_compact_menu_type(menu_type)
|
||||
by_id: dict[str, dict[str, Any]] = {}
|
||||
for r in rows:
|
||||
node_id = r.get("node_id")
|
||||
if node_id:
|
||||
by_id[str(node_id)] = r
|
||||
by_id[public_node_id(str(node_id), t)] = r
|
||||
async with self._sf() as session:
|
||||
await session.execute(delete(CompactMenuOverrideRow))
|
||||
new_rows = [_row_from(r, updated_by) for r in by_id.values()]
|
||||
await session.execute(delete(CompactMenuOverrideRow).where(_menu_type_filter(t)))
|
||||
new_rows = [_row_from(r, t, updated_by) for r in by_id.values()]
|
||||
session.add_all(new_rows)
|
||||
await session.commit()
|
||||
for row in new_rows:
|
||||
await session.refresh(row)
|
||||
return [_to_dict(row) for row in new_rows]
|
||||
|
||||
|
||||
def _menu_type_filter(menu_type: str):
|
||||
if menu_type == DEFAULT_COMPACT_MENU_TYPE:
|
||||
return or_(
|
||||
CompactMenuOverrideRow.menu_type == menu_type,
|
||||
CompactMenuOverrideRow.menu_type.is_(None),
|
||||
CompactMenuOverrideRow.menu_type == "",
|
||||
)
|
||||
return CompactMenuOverrideRow.menu_type == menu_type
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
"""Add compact_menu_overrides.menu_type (简介模式菜单分套).
|
||||
|
||||
Two website deployments keep independent compact/sidebar-summary left menus.
|
||||
Type ``A`` is the historical default; type ``B`` is stored under a prefixed
|
||||
``node_id`` so it never collides on databases that still use ``node_id`` as
|
||||
the sole primary key.
|
||||
|
||||
ORM: ``CompactMenuOverrideRow.menu_type = String(32), NOT NULL, default A``.
|
||||
``create_all`` gives new DBs the column; existing DBs are patched by this
|
||||
revision and by startup ``_ensure_orm_columns_sync``.
|
||||
|
||||
Revision ID: 20260819_01
|
||||
Revises: 20260816_01
|
||||
Create Date: 2026-08-19
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy import inspect
|
||||
|
||||
|
||||
revision = "20260819_01"
|
||||
down_revision = "20260816_01"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _has_table(table_name: str) -> bool:
|
||||
inspector = inspect(op.get_bind())
|
||||
return table_name in inspector.get_table_names()
|
||||
|
||||
|
||||
def _has_column(table_name: str, column_name: str) -> bool:
|
||||
if not _has_table(table_name):
|
||||
return False
|
||||
inspector = inspect(op.get_bind())
|
||||
return any(col["name"] == column_name for col in inspector.get_columns(table_name))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if _has_table("compact_menu_overrides") and not _has_column("compact_menu_overrides", "menu_type"):
|
||||
op.add_column(
|
||||
"compact_menu_overrides",
|
||||
sa.Column("menu_type", sa.String(length=32), nullable=False, server_default="A"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if _has_column("compact_menu_overrides", "menu_type"):
|
||||
op.drop_column("compact_menu_overrides", "menu_type")
|
||||
@@ -142,6 +142,12 @@ CALL _add_column_if_missing('users', 'approved', 'TINYINT(1) NOT NULL DEFAULT 1'
|
||||
-- ORM: UserRow.login_password = String(255), nullable。
|
||||
CALL _add_column_if_missing('users', 'login_password', 'VARCHAR(255) NULL DEFAULT NULL');
|
||||
|
||||
-- ---- compact_menu_overrides.menu_type: 简介模式菜单分套(A/B),对应 migration 20260819_01 ----
|
||||
-- 两套网页部署各自一份左侧简介菜单。存量行视为类型 A;类型 B 的 node_id 带 B:: 前缀,
|
||||
-- 以免在仍以 node_id 为单列主键的旧库上撞主键。
|
||||
-- ORM: CompactMenuOverrideRow.menu_type = String(32), NOT NULL, default A, server_default A。
|
||||
CALL _add_column_if_missing('compact_menu_overrides', 'menu_type', "VARCHAR(32) NOT NULL DEFAULT 'A'");
|
||||
|
||||
-- ---- 清理临时存储过程 --------------------------------------------------------
|
||||
DROP PROCEDURE IF EXISTS _add_column_if_missing;
|
||||
|
||||
@@ -205,5 +211,6 @@ SELECT table_name, column_name
|
||||
OR (table_name = 'roundtable_drafts' AND column_name = 'task_id')
|
||||
OR (table_name = 'roundtable_jobs' AND column_name = 'task_id')
|
||||
OR (table_name = 'position_roundtable_sessions' AND column_name = 'task_scoped')
|
||||
OR (table_name = 'task_buttons' AND column_name IN ('append_auth', 'auth_token_param', 'auth_name_param')))
|
||||
OR (table_name = 'task_buttons' AND column_name IN ('append_auth', 'auth_token_param', 'auth_name_param'))
|
||||
OR (table_name = 'compact_menu_overrides' AND column_name = 'menu_type'))
|
||||
ORDER BY table_name, column_name;
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Tests for compact/sidebar-summary menu overrides (简介模式菜单).
|
||||
|
||||
Overrides are stored per ``menu_type`` (A / B) so two website deployments can
|
||||
keep independent left-nav layouts. Saving type B must not wipe type A.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.compact_menu_overrides import (
|
||||
MemoryCompactMenuOverrideStore,
|
||||
CompactMenuOverrideRepository,
|
||||
normalize_compact_menu_type,
|
||||
)
|
||||
from deerflow.persistence.compact_menu_overrides.keys import public_node_id, storage_node_id
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def store(tmp_path):
|
||||
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'compact-menu.db'}")
|
||||
async with engine.begin() as conn:
|
||||
import deerflow.persistence.compact_menu_overrides.model # noqa: F401
|
||||
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
sf = async_sessionmaker(engine, expire_on_commit=False)
|
||||
return CompactMenuOverrideRepository(sf)
|
||||
|
||||
|
||||
def test_normalize_compact_menu_type():
|
||||
assert normalize_compact_menu_type(None) == "A"
|
||||
assert normalize_compact_menu_type("") == "A"
|
||||
assert normalize_compact_menu_type("a") == "A"
|
||||
assert normalize_compact_menu_type("default") == "A"
|
||||
assert normalize_compact_menu_type("B") == "B"
|
||||
assert normalize_compact_menu_type("alt") == "B"
|
||||
assert normalize_compact_menu_type("2") == "B"
|
||||
|
||||
|
||||
def test_storage_keys_keep_type_a_unprefixed():
|
||||
assert storage_node_id("A", "workspace-chats") == "workspace-chats"
|
||||
assert storage_node_id("B", "workspace-chats") == "B::workspace-chats"
|
||||
assert public_node_id("B::workspace-chats", "B") == "workspace-chats"
|
||||
assert public_node_id("workspace-chats", "A") == "workspace-chats"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_replace_all_roundtrips(store: CompactMenuOverrideRepository):
|
||||
out = await store.replace_all(
|
||||
[
|
||||
{"node_id": "workspace-chats", "placement": "settings", "sort_order": 1, "label": "会话"},
|
||||
{"node_id": "workspace-agents", "placement": "sidebar", "sort_order": 0, "label": None},
|
||||
],
|
||||
updated_by="admin-1",
|
||||
)
|
||||
assert len(out) == 2
|
||||
rows = {r["node_id"]: r for r in await store.list_overrides()}
|
||||
assert rows["workspace-chats"]["label"] == "会话"
|
||||
assert rows["workspace-chats"]["placement"] == "settings"
|
||||
assert rows["workspace-chats"]["menu_type"] == "A"
|
||||
assert rows["workspace-agents"]["updated_by"] == "admin-1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_replace_all_is_full_replacement_within_type(store: CompactMenuOverrideRepository):
|
||||
await store.replace_all([{"node_id": "a"}, {"node_id": "b"}], menu_type="A")
|
||||
await store.replace_all([{"node_id": "c"}], menu_type="A")
|
||||
ids = {r["node_id"] for r in await store.list_overrides("A")}
|
||||
assert ids == {"c"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_types_are_isolated(store: CompactMenuOverrideRepository):
|
||||
await store.replace_all(
|
||||
[{"node_id": "workspace-chats", "placement": "sidebar", "sort_order": 0, "label": "对话A"}],
|
||||
menu_type="A",
|
||||
)
|
||||
await store.replace_all(
|
||||
[{"node_id": "workspace-chats", "placement": "settings", "sort_order": 2, "label": "对话B"}],
|
||||
menu_type="B",
|
||||
)
|
||||
a_rows = await store.list_overrides("A")
|
||||
b_rows = await store.list_overrides("B")
|
||||
assert len(a_rows) == 1
|
||||
assert a_rows[0]["node_id"] == "workspace-chats"
|
||||
assert a_rows[0]["label"] == "对话A"
|
||||
assert a_rows[0]["placement"] == "sidebar"
|
||||
assert len(b_rows) == 1
|
||||
assert b_rows[0]["node_id"] == "workspace-chats"
|
||||
assert b_rows[0]["label"] == "对话B"
|
||||
assert b_rows[0]["placement"] == "settings"
|
||||
|
||||
await store.replace_all([], menu_type="B")
|
||||
assert await store.list_overrides("B") == []
|
||||
leftover = await store.list_overrides("A")
|
||||
assert len(leftover) == 1
|
||||
assert leftover[0]["label"] == "对话A"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_omitted_menu_type_reads_legacy_rows():
|
||||
"""Old pages that do not send menu_type still see the original compact menu."""
|
||||
mem = MemoryCompactMenuOverrideStore()
|
||||
mem._rows["workspace-chats"] = {
|
||||
"node_id": "workspace-chats",
|
||||
"placement": "settings",
|
||||
"sort_order": 1,
|
||||
"label": "旧对话",
|
||||
}
|
||||
rows = await mem.list_overrides(None)
|
||||
assert len(rows) == 1
|
||||
assert rows[0]["node_id"] == "workspace-chats"
|
||||
assert rows[0]["label"] == "旧对话"
|
||||
assert rows[0]["menu_type"] == "A"
|
||||
assert await mem.list_overrides("B") == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sql_blank_menu_type_is_treated_as_original(store: CompactMenuOverrideRepository):
|
||||
from sqlalchemy import update
|
||||
|
||||
from deerflow.persistence.compact_menu_overrides.model import CompactMenuOverrideRow
|
||||
|
||||
await store.replace_all(
|
||||
[{"node_id": "legacy", "placement": "sidebar", "sort_order": 0, "label": "旧菜单"}],
|
||||
)
|
||||
async with store._sf() as session:
|
||||
await session.execute(update(CompactMenuOverrideRow).values(menu_type=""))
|
||||
await session.commit()
|
||||
|
||||
rows = await store.list_overrides(None)
|
||||
assert {r["node_id"] for r in rows} == {"legacy"}
|
||||
assert rows[0]["label"] == "旧菜单"
|
||||
assert await store.list_overrides("B") == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_memory_store_parity():
|
||||
mem = MemoryCompactMenuOverrideStore()
|
||||
await mem.replace_all(
|
||||
[{"node_id": "x", "placement": "settings", "sort_order": 3}],
|
||||
menu_type="B",
|
||||
updated_by="u",
|
||||
)
|
||||
await mem.replace_all([{"node_id": "y", "sort_order": 0}], menu_type="A")
|
||||
b_rows = await mem.list_overrides("B")
|
||||
assert b_rows[0]["node_id"] == "x"
|
||||
assert b_rows[0]["menu_type"] == "B"
|
||||
assert b_rows[0]["placement"] == "settings"
|
||||
a_ids = {r["node_id"] for r in await mem.list_overrides("A")}
|
||||
assert a_ids == {"y"}
|
||||
Reference in new issue
Block a user