feat: light app center and iframe refactor
This commit is contained in:
1 parent
728a4b1170
commit
9d73f27146
35 files changed
+1878
-246
No files matched your search
+23
@@ -0,0 +1,23 @@
|
||||
"""Light-app registry persistence (轻应用中心)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deerflow.persistence.light_apps.base import DuplicateLightAppNameError, LightAppStore
|
||||
from deerflow.persistence.light_apps.memory import MemoryLightAppStore
|
||||
from deerflow.persistence.light_apps.model import LightAppRow
|
||||
from deerflow.persistence.light_apps.sql import LightAppRepository
|
||||
|
||||
__all__ = [
|
||||
"DuplicateLightAppNameError",
|
||||
"LightAppRepository",
|
||||
"LightAppRow",
|
||||
"LightAppStore",
|
||||
"MemoryLightAppStore",
|
||||
"make_light_app_store",
|
||||
]
|
||||
|
||||
|
||||
def make_light_app_store(session_factory):
|
||||
if session_factory is None:
|
||||
return MemoryLightAppStore()
|
||||
return LightAppRepository(session_factory)
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
"""Abstract light-app registry persistence API.
|
||||
|
||||
Global / shared store: no ``user_id`` scoping. Reads are open to any caller; the
|
||||
router gates writes behind admin. ``created_by`` / ``updated_by`` are audit-only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
|
||||
class DuplicateLightAppNameError(ValueError):
|
||||
"""Raised when creating/updating an app would collide on the unique name."""
|
||||
|
||||
|
||||
class LightAppStore(ABC):
|
||||
@abstractmethod
|
||||
async def list_apps(
|
||||
self,
|
||||
*,
|
||||
app_type: str | None = None,
|
||||
mount_location: str | None = None,
|
||||
enabled_only: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Return registered apps (newest first), optionally filtered."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def get_app(self, app_id: str) -> dict[str, Any] | None:
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def create_app(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Create an app. Raises ``DuplicateLightAppNameError`` on a name clash."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def update_app(self, app_id: str, data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""Partial update. Returns None if the app does not exist. Raises
|
||||
``DuplicateLightAppNameError`` when renaming onto an existing name."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def delete_app(self, app_id: str) -> bool:
|
||||
raise NotImplementedError
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
"""In-memory light-app registry store (used when no DB is configured / tests)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from deerflow.persistence.light_apps.base import DuplicateLightAppNameError, LightAppStore
|
||||
|
||||
_WRITABLE = {
|
||||
"name",
|
||||
"description",
|
||||
"app_type",
|
||||
"url",
|
||||
"route_params",
|
||||
"mount_location",
|
||||
"icon",
|
||||
"enabled",
|
||||
"sort_order",
|
||||
"updated_by",
|
||||
}
|
||||
|
||||
|
||||
class MemoryLightAppStore(LightAppStore):
|
||||
def __init__(self) -> None:
|
||||
self._apps: dict[str, dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _public(row: dict[str, Any]) -> dict[str, Any]:
|
||||
out = dict(row)
|
||||
out["route_params"] = list(out.get("route_params") or [])
|
||||
return out
|
||||
|
||||
def _name_taken(self, name: str, *, exclude_id: str | None = None) -> bool:
|
||||
return any(r["name"] == name and r["app_id"] != exclude_id for r in self._apps.values())
|
||||
|
||||
async def list_apps(
|
||||
self,
|
||||
*,
|
||||
app_type: str | None = None,
|
||||
mount_location: str | None = None,
|
||||
enabled_only: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
rows = list(self._apps.values())
|
||||
if app_type:
|
||||
rows = [r for r in rows if r["app_type"] == app_type]
|
||||
if mount_location:
|
||||
rows = [r for r in rows if r.get("mount_location") == mount_location]
|
||||
if enabled_only:
|
||||
rows = [r for r in rows if r.get("enabled", True)]
|
||||
rows.sort(key=lambda r: (r.get("sort_order", 0), r.get("created_at", "")))
|
||||
return [self._public(r) for r in rows]
|
||||
|
||||
async def get_app(self, app_id: str) -> dict[str, Any] | None:
|
||||
row = self._apps.get(app_id)
|
||||
return self._public(row) if row is not None else None
|
||||
|
||||
async def create_app(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
if self._name_taken(data["name"]):
|
||||
raise DuplicateLightAppNameError(data["name"])
|
||||
now = datetime.now(UTC).isoformat()
|
||||
app_id = data.get("app_id") or uuid.uuid4().hex[:12]
|
||||
row = {
|
||||
"app_id": app_id,
|
||||
"name": data["name"],
|
||||
"description": data.get("description"),
|
||||
"app_type": data["app_type"],
|
||||
"url": data["url"],
|
||||
"route_params": data.get("route_params") or [],
|
||||
"mount_location": data.get("mount_location"),
|
||||
"icon": data.get("icon"),
|
||||
"enabled": data.get("enabled", True),
|
||||
"sort_order": data.get("sort_order", 0),
|
||||
"created_by": data.get("created_by"),
|
||||
"updated_by": data.get("created_by"),
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
self._apps[app_id] = row
|
||||
return self._public(row)
|
||||
|
||||
async def update_app(self, app_id: str, data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
row = self._apps.get(app_id)
|
||||
if row is None:
|
||||
return None
|
||||
new_name = data.get("name")
|
||||
if new_name is not None and new_name != row["name"] and self._name_taken(new_name, exclude_id=app_id):
|
||||
raise DuplicateLightAppNameError(new_name)
|
||||
for key, value in data.items():
|
||||
if key in _WRITABLE:
|
||||
row[key] = value
|
||||
row["updated_at"] = datetime.now(UTC).isoformat()
|
||||
return self._public(row)
|
||||
|
||||
async def delete_app(self, app_id: str) -> bool:
|
||||
return self._apps.pop(app_id, None) is not None
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
"""ORM model for the light-app registry (轻应用中心).
|
||||
|
||||
Global / shared — there is no ``user_id`` scoping; every account sees the same
|
||||
registered apps. ``created_by`` / ``updated_by`` are audit-only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Boolean, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.types import BeijingDateTime, PortableJSON
|
||||
|
||||
|
||||
class LightAppRow(Base):
|
||||
__tablename__ = "light_apps"
|
||||
__table_args__ = (UniqueConstraint("name", name="uq_light_apps_name"),)
|
||||
|
||||
app_id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(127))
|
||||
description: Mapped[str | None] = mapped_column(Text)
|
||||
# "window_open" (open in a new tab) | "iframe" (embed under a parent menu)
|
||||
app_type: Mapped[str] = mapped_column(String(32))
|
||||
url: Mapped[str] = mapped_column(Text)
|
||||
# List of route-param descriptors resolved at launch time by the frontend:
|
||||
# {"key": str, "paramType": "login"|"theme", "source": str,
|
||||
# "customValue": str, "themeValue": str}
|
||||
route_params_json: Mapped[list] = mapped_column(PortableJSON(), default=list)
|
||||
# iframe only: the parent sidebar menu id to mount under
|
||||
# (e.g. "xk-center-task" / "pg-center-task" / "ty-center-task" /
|
||||
# "comprehensive-management"). NULL for window_open apps.
|
||||
mount_location: Mapped[str | None] = mapped_column(String(64), index=True)
|
||||
icon: Mapped[str | None] = mapped_column(String(64))
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
created_by: Mapped[str | None] = mapped_column(String(64))
|
||||
updated_by: Mapped[str | None] = mapped_column(String(64))
|
||||
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), default=lambda: datetime.now(UTC))
|
||||
updated_at: Mapped[datetime] = mapped_column(BeijingDateTime(), default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC))
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
"""SQLAlchemy-backed light-app registry store (global / shared)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.light_apps.base import DuplicateLightAppNameError, LightAppStore
|
||||
from deerflow.persistence.light_apps.model import LightAppRow
|
||||
|
||||
# Columns a caller may set/patch (everything except identity + timestamps).
|
||||
_WRITABLE = {
|
||||
"name",
|
||||
"description",
|
||||
"app_type",
|
||||
"url",
|
||||
"route_params",
|
||||
"mount_location",
|
||||
"icon",
|
||||
"enabled",
|
||||
"sort_order",
|
||||
"updated_by",
|
||||
}
|
||||
|
||||
|
||||
def _to_dict(row: LightAppRow) -> dict[str, Any]:
|
||||
data = row.to_dict()
|
||||
for key in ("created_at", "updated_at"):
|
||||
value = data.get(key)
|
||||
if isinstance(value, datetime):
|
||||
data[key] = value.isoformat()
|
||||
data["route_params"] = data.pop("route_params_json", None) or []
|
||||
return data
|
||||
|
||||
|
||||
def _column_for(key: str) -> str:
|
||||
return "route_params_json" if key == "route_params" else key
|
||||
|
||||
|
||||
class LightAppRepository(LightAppStore):
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
|
||||
async def list_apps(
|
||||
self,
|
||||
*,
|
||||
app_type: str | None = None,
|
||||
mount_location: str | None = None,
|
||||
enabled_only: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
stmt = select(LightAppRow)
|
||||
if app_type:
|
||||
stmt = stmt.where(LightAppRow.app_type == app_type)
|
||||
if mount_location:
|
||||
stmt = stmt.where(LightAppRow.mount_location == mount_location)
|
||||
if enabled_only:
|
||||
stmt = stmt.where(LightAppRow.enabled.is_(True))
|
||||
stmt = stmt.order_by(LightAppRow.sort_order.asc(), LightAppRow.created_at.desc())
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [_to_dict(row) for row in result.scalars()]
|
||||
|
||||
async def get_app(self, app_id: str) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(LightAppRow, app_id)
|
||||
return _to_dict(row) if row is not None else None
|
||||
|
||||
async def _name_taken(self, session: AsyncSession, name: str, *, exclude_id: str | None = None) -> bool:
|
||||
stmt = select(LightAppRow.app_id).where(LightAppRow.name == name)
|
||||
if exclude_id is not None:
|
||||
stmt = stmt.where(LightAppRow.app_id != exclude_id)
|
||||
result = await session.execute(stmt.limit(1))
|
||||
return result.first() is not None
|
||||
|
||||
async def create_app(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
row = LightAppRow(
|
||||
app_id=data.get("app_id") or uuid.uuid4().hex[:12],
|
||||
name=data["name"],
|
||||
description=data.get("description"),
|
||||
app_type=data["app_type"],
|
||||
url=data["url"],
|
||||
route_params_json=data.get("route_params") or [],
|
||||
mount_location=data.get("mount_location"),
|
||||
icon=data.get("icon"),
|
||||
enabled=data.get("enabled", True),
|
||||
sort_order=data.get("sort_order", 0),
|
||||
created_by=data.get("created_by"),
|
||||
updated_by=data.get("created_by"),
|
||||
)
|
||||
async with self._sf() as session:
|
||||
if await self._name_taken(session, row.name):
|
||||
raise DuplicateLightAppNameError(row.name)
|
||||
session.add(row)
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError as exc:
|
||||
await session.rollback()
|
||||
raise DuplicateLightAppNameError(row.name) from exc
|
||||
await session.refresh(row)
|
||||
return _to_dict(row)
|
||||
|
||||
async def update_app(self, app_id: str, data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(LightAppRow, app_id)
|
||||
if row is None:
|
||||
return None
|
||||
new_name = data.get("name")
|
||||
if new_name is not None and new_name != row.name and await self._name_taken(session, new_name, exclude_id=app_id):
|
||||
raise DuplicateLightAppNameError(new_name)
|
||||
for key, value in data.items():
|
||||
if key not in _WRITABLE:
|
||||
continue
|
||||
setattr(row, _column_for(key), value)
|
||||
row.updated_at = datetime.now(UTC)
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError as exc:
|
||||
await session.rollback()
|
||||
raise DuplicateLightAppNameError(new_name or row.name) from exc
|
||||
await session.refresh(row)
|
||||
return _to_dict(row)
|
||||
|
||||
async def delete_app(self, app_id: str) -> bool:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(LightAppRow, app_id)
|
||||
if row is None:
|
||||
return False
|
||||
await session.delete(row)
|
||||
await session.commit()
|
||||
return True
|
||||
+2
@@ -36,6 +36,7 @@ from deerflow.knowledge.models import (
|
||||
KnowledgeSourceRow,
|
||||
KnowledgeTagRow,
|
||||
)
|
||||
from deerflow.persistence.light_apps.model import LightAppRow
|
||||
from deerflow.persistence.llm_metrics.model import LlmCallMetricRow
|
||||
from deerflow.persistence.models.run_event import RunEventRow
|
||||
from deerflow.persistence.notifications.model import NotificationRow
|
||||
@@ -83,6 +84,7 @@ __all__ = [
|
||||
"KnowledgeRelationRow",
|
||||
"KnowledgeSourceRow",
|
||||
"KnowledgeTagRow",
|
||||
"LightAppRow",
|
||||
"LlmCallMetricRow",
|
||||
"NotificationRow",
|
||||
"ParallelAgentTaskRow",
|
||||
|
||||
Reference in new issue
Block a user