功能:完善自定义主题与独立登录会话

This commit is contained in:
董宏凯 committed 2026-07-26 18:19:50 +08:00
1 parent 3779bb69ef
commit f1e53ef5c0
23 files changed
+1742 -196

No files matched your search

@@ -15,12 +15,13 @@ from __future__ import annotations
import json
import logging
import re
import threading
from pathlib import Path
from typing import Literal
from uuid import uuid4
from pydantic import BaseModel, ConfigDict, Field
from pydantic import BaseModel, ConfigDict, Field, field_validator
from deerflow.config.runtime_paths import runtime_home
@@ -29,6 +30,111 @@ logger = logging.getLogger(__name__)
_SETTINGS_FILE = "system_settings.json"
_lock = threading.Lock()
# Built-ins remain source-controlled, while administrator-created themes use a
# stable prefixed id and are persisted in the runtime settings JSON.
BUILTIN_THEME_IDS = frozenset({"light", "dark", "lightblue", "lightgreen", "iceblue", "lightyellow"})
CUSTOM_THEME_ID_PREFIX = "custom-theme-"
_CUSTOM_THEME_ID_RE = re.compile(r"^custom-theme-[a-z0-9-]{8,64}$")
_HEX_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
def _normalize_optional_hex_color(value: str | None, field_name: str) -> str | None:
"""Accept an optional, safe six-digit colour without allowing raw CSS."""
if value is None or not str(value).strip():
return None
normalized = str(value).strip().upper()
if not _HEX_COLOR_RE.fullmatch(normalized):
raise ValueError(f"{field_name} must be a six-digit hexadecimal value such as #0062D9")
return normalized
class CustomThemeColorOverrides(BaseModel):
"""Optional advanced adjustments to an otherwise generated colour scale.
The short list intentionally covers interaction surfaces only. It avoids
turning the theme editor into a fragile form containing every CSS token.
"""
button_hover: str | None = Field(default=None, description="Primary button hover colour")
selected_background: str | None = Field(default=None, description="Selected/active item background")
border: str | None = Field(default=None, description="Card and input border colour")
muted: str | None = Field(default=None, description="Muted/secondary surface colour")
muted_text: str | None = Field(default=None, description="Secondary text colour")
destructive: str | None = Field(default=None, description="Delete and danger action colour")
brand_title: str | None = Field(default=None, description="Branded section-title text colour")
primary_foreground: str | None = Field(
default=None,
description="Text colour on primary surfaces such as the logo and status badges",
)
model_config = ConfigDict(extra="ignore")
@field_validator(
"button_hover",
"selected_background",
"border",
"muted",
"muted_text",
"destructive",
"brand_title",
"primary_foreground",
)
@classmethod
def _validate_color(cls, value: str | None, info) -> str | None:
return _normalize_optional_hex_color(value, f"Theme override {info.field_name}")
class CustomThemePreset(BaseModel):
"""One administrator-managed theme generated from a single brand color.
The frontend derives all surface, text, focus and hover tokens from these
safe inputs at runtime. Storing only the brand color and base mode keeps
arbitrary CSS out of runtime settings and lets contrast rules remain
centrally enforced.
"""
id: str = Field(default_factory=lambda: f"{CUSTOM_THEME_ID_PREFIX}{uuid4().hex}")
name: str = Field(default="自定义主题", min_length=1, max_length=32)
primary: str = Field(default="#0062D9", description="Six-digit CSS hexadecimal brand color")
text_color: str | None = Field(
default=None,
description="Optional primary-button text color; omitted = automatic button foreground",
)
mode: Literal["light", "dark"] = Field(default="light", description="Surface family used to derive the palette")
overrides: CustomThemeColorOverrides = Field(default_factory=CustomThemeColorOverrides)
enabled: bool = Field(default=True)
sort_order: int = Field(default=0, ge=0, le=999)
model_config = ConfigDict(extra="ignore")
@field_validator("id")
@classmethod
def _validate_id(cls, value: str) -> str:
normalized = str(value or "").strip().lower()
if not _CUSTOM_THEME_ID_RE.fullmatch(normalized):
raise ValueError("Custom theme id must use the custom-theme- prefix")
return normalized
@field_validator("name")
@classmethod
def _normalize_name(cls, value: str) -> str:
normalized = str(value or "").strip()
if not normalized:
raise ValueError("Theme name cannot be empty")
return normalized
@field_validator("primary")
@classmethod
def _validate_primary(cls, value: str) -> str:
normalized = str(value or "").strip().upper()
if not _HEX_COLOR_RE.fullmatch(normalized):
raise ValueError("Theme primary color must be a six-digit hexadecimal value such as #0062D9")
return normalized
@field_validator("text_color")
@classmethod
def _validate_text_color(cls, value: str | None) -> str | None:
return _normalize_optional_hex_color(value, "Theme text color")
class PromptPrefixSettings(BaseModel):
"""Admin-configurable first-message prompt prefix."""
@@ -102,9 +208,9 @@ class AppearanceSettings(BaseModel):
toggle, and any future first-time loads.
"""
default_theme: Literal["light", "dark", "lightblue", "lightgreen", "iceblue", "lightyellow"] = Field(
default_theme: str = Field(
default="light",
description="Theme applied for users who haven't picked their own (light / dark / lightblue / lightgreen / iceblue / lightyellow)",
description="Theme applied for users who haven't picked their own (a built-in id or custom-theme-* id)",
)
default_skill_view: Literal["card", "list"] = Field(
default="list",
@@ -122,8 +228,20 @@ class AppearanceSettings(BaseModel):
default_factory=_default_compact_shortcut_buttons,
description="Shortcut buttons rendered before the theme switcher in top bars",
)
custom_themes: list[CustomThemePreset] = Field(
default_factory=list,
description="Administrator-managed runtime themes available to all users",
)
model_config = ConfigDict(extra="ignore")
@field_validator("default_theme")
@classmethod
def _validate_default_theme(cls, value: str) -> str:
normalized = str(value or "").strip().lower()
if normalized in BUILTIN_THEME_IDS or _CUSTOM_THEME_ID_RE.fullmatch(normalized):
return normalized
raise ValueError("Unknown theme id")
class CitationDisplaySettings(BaseModel):
"""System-wide cleanup rules for citation cards and detail dialogs."""
@@ -290,9 +408,7 @@ def get_module_tag_ids(settings: AgentModuleSettings, key: str) -> list[str]:
return list(settings.modules.get(key, []))
def set_module_tag_ids(
settings: AgentModuleSettings, key: str, tag_ids: list[str]
) -> AgentModuleSettings:
def set_module_tag_ids(settings: AgentModuleSettings, key: str, tag_ids: list[str]) -> AgentModuleSettings:
"""Return a copy with ``key`` set to a de-duplicated, stripped tag-id list."""
cleaned = list(dict.fromkeys([str(t).strip() for t in tag_ids if str(t).strip()]))
modules = dict(settings.modules)