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
@@ -251,6 +251,7 @@ FastAPI application on port 8001 with health check at `GET /health`. Set `GATEWA
|
||||
| **Scheduled Tasks** (`/api/scheduled-tasks`) | Per-user cron-like agent tasks. `GET/POST /` - list/create owned tasks; `PATCH/DELETE /{id}` - update/delete (owner); `POST /{id}/{pause,resume,trigger}`; `GET /{id}/runs`, `GET /runs/{rid}`, run-file preview/edit/download; `GET /runs/{rid}/messages` - agent messages for the run's underlying agent run (used to inspect a stuck/running run; authorized via `_load_run`); `GET /runs/{rid}/html` - generated HTML document for an `html_page` run; `DELETE /runs/{rid}` - owner-scoped, with an admin fallback so admins can delete any user's run; publish/subscribe under `/{id}/{publish,unpublish,subscribe}` and `GET /published`. **Admin (cross-user):** `GET /admin/all` - every task; `PATCH/DELETE /admin/{id}` - edit/delete any task; `POST /admin/{id}/trigger`; `GET /admin/{id}/runs`. Admin routes require `system_role == "admin"`. |
|
||||
| **HTML Page Favorites** (`/api/html-page-favorites`) | Bookmarked generated HTML pages, owner-scoped. `GET /` - list; `POST /` `{page_id, title?, description?, tags?}` - bookmark a `scheduled_html_pages` row (extracts a reusable style/layout summary via GLM5 at favorite time); a page can only be favorited once per user (`DuplicateFavoriteError` → HTTP 409). `GET/DELETE /{id}` - read/delete (the create-task reference picker deletes favorites here). A favorite can be selected as a style reference when creating a new `html_page` task. |
|
||||
| **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`. |
|
||||
| **Knowledge** (`/api/knowledge`) | Product knowledge base, **global/shared** (no user isolation; writes record `created_by`/`updated_by` for audit). `POST /ingest/thread/{thread_id}` - sediment one thread into a note (reads messages from the checkpointer, `threads:read` owner-checked); `POST /ingest/threads/batch` - batch-sediment the caller's recent threads (`skip_existing` via `.manifest.json` dedup). **Optional model selection**: both ingest endpoints accept `model_name` (overrides `knowledge.extract_model_name` for that capture; threaded through `KnowledgeService.capture_thread` → `extract_thread_llm_multi`). **Model-error surfacing**: when the chosen model produces nothing usable (timeout / API error / non-JSON) capture still **falls back to rule-based extraction and lands a draft** (`llm_fallback:true`); the single-thread (non-background) response and the batch response (`llm_fallback` count) carry this so the UI tells the user "已改用规则抽取". The "保存到知识库" chat button stays background/fire-and-forget (passes `model_name`, no per-save error toast); the batch-import dialog is synchronous and shows the fallback count. `POST /ingest/file` - **import an uploaded file** (multipart: `file` + optional `title`/`tags`/`status`/`model_name`) into wiki note(s): the file is converted to Markdown (md/txt read directly, pdf/word/ppt/excel via `convert_file_to_markdown`), distilled by the same wiki-capture LLM pipeline as thread capture (`source_type="file"`), and falls back to a verbatim **draft** note when the model returns nothing usable (`llm_fallback:true`); `POST /ingest/search` - sediment search/tool results as a reference note; `POST /notes` - manual note; `GET /notes` (keyword/tag/source_type/status + pagination); `GET/PUT/DELETE /notes/{id}` (DELETE is soft = archive, `?hard=true` removes the vault file); `POST /search` - `mode=keyword\|vector\|hybrid` (vector→keyword fallback when no embedding endpoint); `GET /notes/{id}/versions` - edit history; `GET /duplicates` + `POST /merge` - dedup; `POST /reindex` - rebuild vector index; `GET /graph` - product graph data (notes + entities, graph-blacklist filtered); `GET/POST /graph/blacklist` + `DELETE /graph/blacklist/{id}` - graph node blacklist (labels = entity names / note titles, case-insensitive match; blacklisted nodes and their edges are dropped from `/graph` and the wiki-export artifacts; table `knowledge_graph_blacklist`, auto-created); `POST /export/graph` + `GET /export/files/{graph.json\|graph.html\|graph.graphml\|cypher.txt}` - obsidian-wiki `wiki-export` artifacts (self-contained `graph.html` for iframe); `POST /resolve` `{targets:[…]}` + `GET /notes/{id}/wikilinks` - resolve `[[wikilink]]` targets to a note id / vault page / missing (powers clickable wikilinks); `GET /vault-page?path=` - read a raw vault meta/hub Markdown page (no DB note). Backed by the `deerflow.knowledge` module (see below). |
|
||||
|
||||
Proxied through nginx: `/api/langgraph/*` → LangGraph, all other `/api/*` → Gateway.
|
||||
|
||||
@@ -40,6 +40,7 @@ from app.gateway.routers import (
|
||||
html_page_favorites,
|
||||
intent,
|
||||
knowledge,
|
||||
light_apps,
|
||||
llm_metrics,
|
||||
mcp,
|
||||
memory,
|
||||
@@ -1321,6 +1322,9 @@ 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)
|
||||
|
||||
# Light-app registry (轻应用中心) at /api/light-apps
|
||||
app.include_router(light_apps.router)
|
||||
|
||||
# Standalone parallel multi-agent panel: fan-out streaming + saved tasks
|
||||
app.include_router(parallel_agents.router)
|
||||
app.include_router(parallel_agent_tasks.router)
|
||||
|
||||
@@ -204,6 +204,10 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
|
||||
app.state.business_mapping_store = make_business_mapping_store(sf)
|
||||
|
||||
from deerflow.persistence.light_apps import make_light_app_store
|
||||
|
||||
app.state.light_app_store = make_light_app_store(sf)
|
||||
|
||||
from deerflow.persistence.parallel_agent_tasks import make_parallel_agent_task_store
|
||||
|
||||
app.state.parallel_agent_task_store = make_parallel_agent_task_store(sf)
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Light-app registry API (轻应用中心 / 应用管理).
|
||||
|
||||
Registered mini-applications, **global / shared** (no user scoping). Two kinds:
|
||||
|
||||
- ``window_open`` — launched in a new browser tab from the 应用列表 card grid.
|
||||
- ``iframe`` — embedded under a parent sidebar menu (``mount_location``) and
|
||||
injected into the sidebar as a child item.
|
||||
|
||||
Both kinds carry ``route_params`` — a list of 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.
|
||||
|
||||
Reads are open to any authenticated user; writes require admin.
|
||||
|
||||
Routes (prefix ``/api/light-apps``):
|
||||
GET "" list apps (filters: app_type / mount_location / enabled_only / search)
|
||||
POST "" create app (admin)
|
||||
GET "/{app_id}" read one
|
||||
PUT "/{app_id}" update one (admin)
|
||||
DELETE "/{app_id}" delete one (admin)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
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.light_apps import DuplicateLightAppNameError, LightAppStore
|
||||
|
||||
router = APIRouter(prefix="/api/light-apps", tags=["light-apps"])
|
||||
|
||||
_VALID_TYPES = {"window_open", "iframe"}
|
||||
|
||||
|
||||
# ── schemas ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class RouteParam(BaseModel):
|
||||
key: str = Field(..., min_length=1, max_length=128)
|
||||
paramType: str = Field(..., pattern="^(login|theme)$")
|
||||
# login: which userInfo field, or "other"
|
||||
source: str | None = Field(default=None, max_length=64)
|
||||
# login + source == "other": literal value
|
||||
customValue: str | None = Field(default=None, max_length=2048)
|
||||
# theme: the theme value (e.g. dark-blue / red / blue), editable
|
||||
themeValue: str | None = Field(default=None, max_length=128)
|
||||
|
||||
|
||||
class LightAppResponse(BaseModel):
|
||||
app_id: str
|
||||
name: str
|
||||
description: str | None = None
|
||||
app_type: str
|
||||
url: str
|
||||
route_params: list[RouteParam] = Field(default_factory=list)
|
||||
mount_location: str | None = None
|
||||
icon: str | None = None
|
||||
enabled: bool = True
|
||||
sort_order: int = 0
|
||||
created_by: str | None = None
|
||||
updated_by: str | None = None
|
||||
created_at: datetime | str | None = None
|
||||
updated_at: datetime | str | None = None
|
||||
|
||||
|
||||
class LightAppListResponse(BaseModel):
|
||||
apps: list[LightAppResponse]
|
||||
|
||||
|
||||
class LightAppCreateRequest(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=127)
|
||||
description: str | None = Field(default=None, max_length=1000)
|
||||
app_type: str = Field(..., pattern="^(window_open|iframe)$")
|
||||
url: str = Field(..., min_length=1)
|
||||
route_params: list[RouteParam] = Field(default_factory=list)
|
||||
mount_location: str | None = Field(default=None, max_length=64)
|
||||
icon: str | None = Field(default=None, max_length=64)
|
||||
enabled: bool = True
|
||||
sort_order: int = 0
|
||||
|
||||
|
||||
class LightAppUpdateRequest(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=1, max_length=127)
|
||||
description: str | None = Field(default=None, max_length=1000)
|
||||
app_type: str | None = Field(default=None, pattern="^(window_open|iframe)$")
|
||||
url: str | None = Field(default=None, min_length=1)
|
||||
route_params: list[RouteParam] | None = None
|
||||
mount_location: str | None = Field(default=None, max_length=64)
|
||||
icon: str | None = Field(default=None, max_length=64)
|
||||
enabled: bool | None = None
|
||||
sort_order: int | None = None
|
||||
|
||||
|
||||
# ── helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _get_store(request: Request) -> LightAppStore:
|
||||
store = getattr(request.app.state, "light_app_store", None)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Light app store not available")
|
||||
return store
|
||||
|
||||
|
||||
async def _require_admin(request: Request) -> None:
|
||||
"""Reject non-admins. Lets the call through when auth is disabled."""
|
||||
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(app_type: str | None, mount_location: str | None) -> None:
|
||||
if app_type == "iframe" and not mount_location:
|
||||
raise HTTPException(status_code=400, detail="iframe 类型必须选择挂载菜单")
|
||||
|
||||
|
||||
def _dump_params(params) -> list[dict]:
|
||||
return [p.model_dump() if isinstance(p, RouteParam) else dict(p) for p in (params or [])]
|
||||
|
||||
|
||||
# ── routes ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@router.get("", response_model=LightAppListResponse)
|
||||
async def list_light_apps(
|
||||
request: Request,
|
||||
app_type: str | None = Query(default=None),
|
||||
mount_location: str | None = Query(default=None),
|
||||
enabled_only: bool = Query(default=False),
|
||||
search: str | None = Query(default=None),
|
||||
) -> LightAppListResponse:
|
||||
store = _get_store(request)
|
||||
rows = await store.list_apps(app_type=app_type, mount_location=mount_location, enabled_only=enabled_only)
|
||||
if search:
|
||||
needle = search.strip().lower()
|
||||
rows = [r for r in rows if needle in str(r.get("name", "")).lower() or needle in str(r.get("description") or "").lower()]
|
||||
return LightAppListResponse(apps=[LightAppResponse(**r) for r in rows])
|
||||
|
||||
|
||||
@router.post("", response_model=LightAppResponse)
|
||||
async def create_light_app(request: Request, body: LightAppCreateRequest) -> LightAppResponse:
|
||||
await _require_admin(request)
|
||||
_validate_payload(body.app_type, body.mount_location)
|
||||
store = _get_store(request)
|
||||
user_id = await get_current_user(request)
|
||||
try:
|
||||
row = await store.create_app(
|
||||
{
|
||||
"name": body.name,
|
||||
"description": body.description,
|
||||
"app_type": body.app_type,
|
||||
"url": body.url,
|
||||
"route_params": _dump_params(body.route_params),
|
||||
"mount_location": body.mount_location if body.app_type == "iframe" else None,
|
||||
"icon": body.icon,
|
||||
"enabled": body.enabled,
|
||||
"sort_order": body.sort_order,
|
||||
"created_by": user_id,
|
||||
}
|
||||
)
|
||||
except DuplicateLightAppNameError:
|
||||
raise HTTPException(status_code=409, detail="应用名称已存在")
|
||||
return LightAppResponse(**row)
|
||||
|
||||
|
||||
@router.get("/{app_id}", response_model=LightAppResponse)
|
||||
async def get_light_app(request: Request, app_id: str) -> LightAppResponse:
|
||||
store = _get_store(request)
|
||||
row = await store.get_app(app_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="应用不存在")
|
||||
return LightAppResponse(**row)
|
||||
|
||||
|
||||
@router.put("/{app_id}", response_model=LightAppResponse)
|
||||
async def update_light_app(request: Request, app_id: str, body: LightAppUpdateRequest) -> LightAppResponse:
|
||||
await _require_admin(request)
|
||||
store = _get_store(request)
|
||||
user_id = await get_current_user(request)
|
||||
|
||||
fields = body.model_dump(exclude_unset=True)
|
||||
if "route_params" in fields:
|
||||
fields["route_params"] = _dump_params(body.route_params)
|
||||
|
||||
# Resolve the effective type/mount to validate the iframe→mount invariant.
|
||||
existing = await store.get_app(app_id)
|
||||
if existing is None:
|
||||
raise HTTPException(status_code=404, detail="应用不存在")
|
||||
eff_type = fields.get("app_type", existing.get("app_type"))
|
||||
eff_mount = fields.get("mount_location", existing.get("mount_location"))
|
||||
_validate_payload(eff_type, eff_mount)
|
||||
if eff_type == "window_open":
|
||||
fields["mount_location"] = None
|
||||
|
||||
fields["updated_by"] = user_id
|
||||
try:
|
||||
row = await store.update_app(app_id, fields)
|
||||
except DuplicateLightAppNameError:
|
||||
raise HTTPException(status_code=409, detail="应用名称已存在")
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="应用不存在")
|
||||
return LightAppResponse(**row)
|
||||
|
||||
|
||||
@router.delete("/{app_id}")
|
||||
async def delete_light_app(request: Request, app_id: str) -> dict:
|
||||
await _require_admin(request)
|
||||
store = _get_store(request)
|
||||
deleted = await store.delete_app(app_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="应用不存在")
|
||||
return {"success": True}
|
||||
@@ -10,20 +10,6 @@ gateway:
|
||||
port: 8001
|
||||
|
||||
models:
|
||||
<<<<<<< Updated upstream
|
||||
# - name: deepseek-chat
|
||||
# display_name: DeepSeek Chat
|
||||
# use: langchain_openai:ChatOpenAI
|
||||
# model: deepseek-chat
|
||||
# api_key: sk-3fee562f834a4c08bb0d471ef44cb445
|
||||
# base_url: https://api.deepseek.com
|
||||
# request_timeout: 600.0
|
||||
# max_retries: 2
|
||||
# max_tokens: 4096
|
||||
# temperature: 1.0
|
||||
# supports_vision: false
|
||||
# supports_thinking: true
|
||||
=======
|
||||
- name: deepseek-chat
|
||||
display_name: DeepSeek Chat
|
||||
use: langchain_openai:ChatOpenAI
|
||||
@@ -36,7 +22,6 @@ models:
|
||||
temperature: 1.0
|
||||
supports_vision: false
|
||||
supports_thinking: true
|
||||
>>>>>>> Stashed changes
|
||||
|
||||
# - name: zai-org/GLM-5-FP8
|
||||
# display_name: zai-org/GLM-5-FP8
|
||||
|
||||
+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